Skip to content
2 changes: 1 addition & 1 deletion docs/generated/core_configuration.html
Original file line number Diff line number Diff line change
Expand Up @@ -654,7 +654,7 @@
<td><h5>data-file.external-paths.strategy</h5></td>
<td style="word-wrap: break-word;">none</td>
<td><p>Enum</p></td>
<td>The strategy of selecting an external path when writing data.<br /><br />Possible values:<ul><li>"none": Do not choose any external storage, data will still be written to the default warehouse path.</li><li>"specific-fs": Select a specific file system as the external path. Currently supported are S3 and OSS.</li><li>"round-robin": When writing a new file, a path is chosen from data-file.external-paths in turn.</li><li>"entropy-inject": When writing a new file, a path is chosen based on the hash value of the file's content.</li><li>"weight-robin": When writing a new file, a path is chosen based on configured weights.</li></ul></td>
<td>The strategy of selecting an external path when writing data.<br /><br />Possible values:<ul><li>"none": Do not choose any external storage, data will still be written to the default warehouse path.</li><li>"specific-fs": Select a specific file system as the external path. Currently supported are S3 and OSS.</li><li>"round-robin": When writing a new file, a path is chosen from data-file.external-paths in turn.</li><li>"entropy-inject": When writing a new file, a path is chosen based on the hash value of the file's content.</li><li>"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.</li><li>"weight-robin": When writing a new file, a path is chosen based on configured weights.</li></ul></td>
</tr>
<tr>
<td><h5>data-file.external-paths.weights</h5></td>
Expand Down
7 changes: 7 additions & 0 deletions paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
Original file line number Diff line number Diff line change
Expand Up @@ -6061,6 +6061,13 @@ public enum ExternalPathStrategy implements DescribedEnum {
"entropy-inject",
"When writing a new file, a path is chosen based on the hash value of the file's content."),

ENTROPY_INJECT_TEMPLATE(
"entropy-inject-template",
"Uses a single path template in data-file.external-paths containing a '{hash}' placeholder. "
+ "The placeholder is replaced in place by hash directories computed from the file name. "
+ "Place '{hash}' before the database and table directories to share object storage prefixes across tables. "
+ "This strategy cannot be enabled or disabled on an existing table."),

WEIGHTED(
"weight-robin",
"When writing a new file, a path is chosen based on configured weights.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand All @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.paimon.fs;

import javax.annotation.concurrent.ThreadSafe;

import java.util.List;

import static org.apache.paimon.fs.EntropyInjectExternalPathProvider.computeHash;
import static org.apache.paimon.utils.Preconditions.checkArgument;

/**
* Provider for external data paths which injects the hash directories into a path template.
*
* <p>{@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:
*
* <pre>
* 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
* </pre>
*
* <p>Multiple databases and tables pointing at the same template root therefore share the same hash
* prefixes.
*
* <p>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<Path> externalTablePathTemplates, Path relativeBucketPath) {
checkArgument(
externalTablePathTemplates.size() == 1,
"Only a single external path template is supported, but got %s.",
externalTablePathTemplates);
Path template = externalTablePathTemplates.get(0);
checkTemplate(template);
this.externalTablePathTemplate = template;
this.relativeBucketPath = relativeBucketPath;
}

@Override
public Path getNextExternalDataPath(String fileName) {
Path externalTablePath = expand(externalTablePathTemplate, fileName);
return new Path(new Path(externalTablePath, relativeBucketPath), fileName);
}

/** Validates that the normalized URI path contains the hash placeholder. */
public static void checkTemplate(Path template) {
String path = template.toUri().getPath();
checkArgument(
path != null && path.contains(HASH_PLACEHOLDER),
"External path '%s' must contain the '%s' placeholder.",
template,
HASH_PLACEHOLDER);
}

private static Path expand(Path template, String fileName) {
return new Path(template.toString().replace(HASH_PLACEHOLDER, computeHash(fileName)));
}
}
Original file line number Diff line number Diff line change
@@ -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<Path> 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}");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.apache.paimon.function.Function;
import org.apache.paimon.function.FunctionChange;
import org.apache.paimon.operation.Lock;
import org.apache.paimon.operation.TemplateFileDeletionPlan;
import org.apache.paimon.options.Options;
import org.apache.paimon.partition.Partition;
import org.apache.paimon.partition.PartitionStatistics;
Expand All @@ -38,6 +39,7 @@
import org.apache.paimon.schema.Schema;
import org.apache.paimon.schema.SchemaChange;
import org.apache.paimon.schema.SchemaManager;
import org.apache.paimon.schema.SchemaValidation;
import org.apache.paimon.schema.TableSchema;
import org.apache.paimon.table.FileStoreTable;
import org.apache.paimon.table.FormatTable;
Expand Down Expand Up @@ -71,6 +73,7 @@
import java.util.stream.Collectors;

import static org.apache.paimon.CoreOptions.DATA_FILE_EXTERNAL_PATHS;
import static org.apache.paimon.CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY;
import static org.apache.paimon.CoreOptions.GLOBAL_INDEX_EXTERNAL_PATH;
import static org.apache.paimon.CoreOptions.PATH;
import static org.apache.paimon.CoreOptions.TYPE;
Expand Down Expand Up @@ -387,15 +390,25 @@ public void dropTable(Identifier identifier, boolean ignoreIfNotExists)
Set<Path> externalPaths = new HashSet<>();
Path tablePath = getTableLocation(identifier);
if (tableExistsInFileSystem(tablePath, DEFAULT_MAIN_BRANCH)) {
TableType tableType = CoreOptions.fromMap(loadTableSchema(identifier).options()).type();
if (tableType == TableType.TABLE || tableType == TableType.MATERIALIZED_TABLE) {
// Cleanup only needs persisted metadata, even if runtime options are invalid.
CoreOptions options = CoreOptions.fromMap(loadTableSchema(identifier).options());
if (options.type() == TableType.TABLE
|| options.type() == TableType.MATERIALIZED_TABLE) {
FileIO tableFileIO = fileIO(tablePath);
SchemaManager schemaManager = new FileSystemSchemaManager(tableFileIO, tablePath);
externalPaths.addAll(getSchemaExternalPaths(schemaManager.listAll()));
for (String branch : FileSystemBranchManager.branches(tableFileIO, tablePath)) {
externalPaths.addAll(
getSchemaExternalPaths(schemaManager.copyWithBranch(branch).listAll()));
boolean isExternal = loadTableMetadata(identifier).isExternal();
List<String> 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<TableSchema> latest = branchSchema.latest();
if (!isExternal
&& latest.isPresent()
&& TemplateFileDeletionPlan.isTemplate(latest.get())) {
TemplateFileDeletionPlan.save(
tableFileIO, tablePath, branch, latest.get(), false);
}
}
}
}
Expand All @@ -417,7 +430,9 @@ private List<Path> getSchemaExternalPaths(List<TableSchema> schemas) {
Map<String, String> options = schema.toSchema().options();
return Arrays.stream(
new String[] {
options.get(DATA_FILE_EXTERNAL_PATHS.key()),
TemplateFileDeletionPlan.isTemplate(schema)
? null
: options.get(DATA_FILE_EXTERNAL_PATHS.key()),
options.get(GLOBAL_INDEX_EXTERNAL_PATH.key())
});
})
Expand Down Expand Up @@ -450,6 +465,8 @@ public void createTable(Identifier identifier, Schema schema, boolean ignoreIfEx
} catch (TableNotExistException ignored) {
}

Path tablePath = getTableLocation(identifier);
TemplateFileDeletionPlan.checkCanCreateTable(fileIO(tablePath), tablePath);
copyTableDefaultOptions(schema.options());
validateCreateTable(schema, false);

Expand Down Expand Up @@ -560,6 +577,9 @@ public void replaceTable(Identifier identifier, Schema newSchema, boolean ignore
+ "). Drop and re-create the table instead.");
}

String strategy = DATA_FILE_EXTERNAL_PATHS_STRATEGY.key();
SchemaValidation.validateExternalPathStrategyChange(
existing.options().get(strategy), newSchema.options().get(strategy));
replaceTableImpl(identifier, (FileStoreTable) existing, newSchema);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -122,6 +123,7 @@ public TableSchema loadTableSchema(Identifier identifier) throws TableNotExistEx
@Override
protected void dropTableImpl(Identifier identifier, List<Path> 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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -487,6 +488,9 @@ public void createObjectTable(Identifier identifier, Schema schema) {
@Override
protected void dropTableImpl(Identifier identifier, List<Path> externalPaths) {
try {
Path path = getTableLocation(identifier);
TemplateFileDeletionPlan.init(fileIO, path).execute();

int deletedRecords =
execute(
connections,
Expand All @@ -507,7 +511,7 @@ protected void dropTableImpl(Identifier identifier, List<Path> externalPaths) {
identifier.getDatabaseName(),
identifier.getTableName());
}
Path path = getTableLocation(identifier);

try {
if (fileIO.exists(path)) {
fileIO.deleteDirectoryQuietly(path);
Expand Down Expand Up @@ -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;
}

Expand Down
Loading
Loading