Skip to content

[core] Support entropy-inject-template external paths - #10978

Open
wzx140 wants to merge 9 commits into
apache:masterfrom
wzx140:codex/entropy-inject-template
Open

wzx140 wants to merge 9 commits into
apache:masterfrom
wzx140:codex/entropy-inject-template

Conversation

@wzx140

@wzx140 wzx140 commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Purpose

Add the entropy-inject-template external path strategy so that multiple databases and tables can share hash prefixes ahead of the table context. Data files retain their fully expanded externalPath in metadata. Snapshot expiration uses these paths, orphan-file cleanup explicitly rejects this strategy, and table deletion removes manifest-referenced files before deleting metadata.

Design: shared hash prefixes across Paimon tables

The design below is based on the original design document and updated to match this implementation. The older-version compatibility results are historical results reported by the source design.

Background

Distributing lake-table requests across prefixes

  • Iceberg: The hash can precede the database and table names, for example s3://data-bucket/1001/my_db/my_table/<file>.parquet. After partitions have been provisioned for s3://data-bucket/{0000~1111}, files belonging to different tables can share the S3 partitions warmed or scaled for these prefixes.
  • Paimon: The existing layout is s3://data-bucket/my_db/my_table/bucket-0/1001/<file>.parquet. The hash follows the table, partition, and bucket directories. S3 partitions warmed or scaled for that hash prefix serve only files under this directory. Other tables cannot share them and require separate warming or scaling for their own paths.

Iceberg supports shared S3 hash-prefix partitions across databases and tables to distribute requests and increase throughput. With write.object-storage.enabled enabled and write.data.path set to a shared root outside the table location, its built-in path generator inserts a hash after the root and then appends the last two components of the table location as table context.

-- Spark SQL; iceberg_catalog and my_db are already configured.
CREATE TABLE iceberg_catalog.my_db.my_table (
    id BIGINT,
    dt STRING
)
USING iceberg
PARTITIONED BY (dt)
LOCATION 's3://metadata-bucket/warehouse/my_db/my_table'
TBLPROPERTIES (
    'write.object-storage.enabled' = 'true',
    'write.data.path' = 's3://data-bucket',
    'write.object-storage.partitioned-paths' = 'true'
);

-- Illustrative data-file path; the hash is only an example:
-- s3://data-bucket/1001/1001/1001/10011001/my_db/my_table/dt=2026-11-02/<file>.parquet

Paimon's existing entropy-inject strategy inserts the hash after the Paimon bucket directory. This design follows Iceberg's approach by moving the hash ahead of the table context, allowing multiple databases and tables to share prefix partitions.

-- Existing Paimon behavior in Spark SQL;
-- paimon_catalog and my_db are already configured.
CREATE TABLE paimon_catalog.my_db.my_table (
    id BIGINT,
    dt STRING
)
USING paimon
PARTITIONED BY (dt)
TBLPROPERTIES (
    'bucket' = '-1',
    'data-file.external-paths' = 's3://data-bucket/my_db/my_table',
    'data-file.external-paths.strategy' = 'entropy-inject'
);

-- Illustrative data-file path; the hash is only an example:
-- s3://data-bucket/my_db/my_table/dt=2026-11-02/bucket-0/1001/1001/1001/10011001/<file>.parquet

Configuration and path layout

Configure data-file.external-paths with a single path template containing {hash}. The placeholder position is chosen by the user; put it before the database and table directories to share hash prefixes across tables. Multiple templates are rejected, and other external-path strategies do not accept {hash}.

CREATE TABLE paimon_catalog.my_db.my_table (
    id BIGINT,
    dt STRING
)
USING paimon
PARTITIONED BY (dt)
TBLPROPERTIES (
    'bucket' = '-1',
    'data-file.external-paths' = 's3://bucket-a/{hash}/my_db.db/my_table',
    'data-file.external-paths.strategy' = 'entropy-inject-template'
);
  1. Initialize the provider with the single configured template. There is no random starting point or round-robin selection.
  2. Compute the existing Paimon MurmurHash3 32-bit hash of the complete filename, take the low 20 bits, and arrange them into 4/4/4/8 segments. The partition path does not participate in hashing.
  3. Replace {hash} in place with the four-level hash directory.
  4. Append the existing relative bucket path and filename, and persist the fully expanded path as externalPath.
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/<file>.parquet

Compatibility with older versions

An unknown strategy does not cause every operation to fail. The source design reports a unit test on a checkout where entropy-inject-template did not yet exist: first write one real record with the existing round-robin strategy, then directly replace the strategy and template options in the persisted schema to simulate older code opening newer metadata. The test used FileSystemCatalog, LocalFileIO, and an append-only table without a primary key; production code was not modified.

Operation Reported unit-test result
catalog.getTable Succeeds: loads a table with an unknown strategy and reads the raw options.
latestSnapshot() Succeeds: reads existing snapshot metadata.
Read: newReadBuilder().newScan().plan() Throws an IllegalArgumentException mentioning the unknown strategy during read planning.
Write: create a batch writer and attempt a write Throws an IllegalArgumentException mentioning the unknown strategy; the write cannot complete.
newExpireSnapshots().expire() Throws an IllegalArgumentException mentioning the unknown strategy; expiration cannot complete.
LocalOrphanFilesClean.clean() Throws an IllegalArgumentException mentioning the unknown strategy; orphan cleanup cannot complete.
catalog.dropTable Succeeds, but only deletes files under the literal path s3://bucket-a/{hash}/my_db.db/my_table; it does not accidentally delete files from other tables.

expire_snapshot

Existing behavior

  1. Determine expired snapshots according to the retention policy and derive deletion candidates from manifests.
  2. Exclude files still protected by retained references.
  3. Locate and delete files and extra files through the complete externalPath in file metadata, without scanning external directories.
  4. Attempt to reclaim empty bucket and partition directories under the table directory.

Required changes

The actual file-deletion logic does not need to change: it continues to use the complete externalPath. The configuration enum and path-provider factory must recognize the new strategy. Expiration creates an ExternalPathProvider while constructing DataFilePathFactory, so adding an enum value alone is insufficient. The writer persists the fully expanded path, and regression tests cover expiration deletion. The first version does not reclaim empty directories in the shared layout or introduce directory scans.

remove_orphan_files

Existing behavior

  1. Find partition and bucket directories under table-local directories and external paths, and collect their direct child files.
  2. Filter by olderThan to obtain candidate files.
  3. Collect snapshot, tag, and changelog references from valid branches, and exclude referenced files from the candidates.
  4. Delete the remaining files and reclaim empty directories.

Revised behavior

Not supported for this strategy. Constructing the orphan-file cleaner throws UnsupportedOperationException.

Dropping a table (DROP TABLE)

Existing behavior

  1. AbstractCatalog.dropTable collects all schemas from main and other branches.
  2. getSchemaExternalPaths extracts the raw external paths and global-index path.
  3. These paths are passed to dropTableImpl(identifier, paths).
  4. Each catalog deletes metadata and directories according to its own semantics.

Existing DROP TABLE behavior recursively deletes directories configured in the schemas rather than reading data-file lists from manifests and deleting files individually.

These external paths are currently treated as table-exclusive directories. FileSystemCatalog deletes them recursively; managed tables in HiveCatalog and tables in JdbcCatalog also delete these directories. Hive external tables retain metadata-only deletion semantics.

Revised behavior

AbstractCatalog checks the latest schema of main and each other branch. For non-external tables, it invokes EntropyInjectTemplateFilesDeletion separately for each branch whose current strategy is entropy-inject-template. The helper operates only on the supplied branch:

  1. Traverse the branch's retained snapshots, tags, and changelogs, and read their referenced base, delta, and changelog manifests. Collect recorded data files and extra files from both ADD and DELETE entries without merging them. Process referenced index manifests as well. Reading only the live files in the latest snapshot is insufficient.
  2. Collect and deduplicate complete file paths within each manifest, then delete them using their recorded paths, including externalPath where present. Paths referenced by different manifests or branches may be deleted more than once; missing files are ignored. The helper does not expand templates, scan hash directories, or reclaim empty directories. It processes file paths one manifest at a time, while retaining snapshot and manifest references for the branch.
  3. Complete the manifest-based deletion attempts before calling dropTableImpl. Manifest read failures abort the drop and retain metadata for retry. File deletion uses deleteQuietly: failures are logged and do not prevent metadata deletion. Hive external tables skip manifest-based data deletion and retain metadata-only deletion semantics.

The existing directory cleanup remains unchanged: paths from all historical schemas, including literal template paths and global-index paths, are still passed to dropTableImpl. The helper supplements that cleanup for expanded template files. A branch that previously used the template strategy but whose latest schema uses another strategy does not receive this additional manifest-based deletion.

@wzx140
wzx140 force-pushed the codex/entropy-inject-template branch from d962b2d to 719ef55 Compare November 3, 2026 13:54

@JingsongLi JingsongLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requirement fit: SUPPORTED. Implementation: FINDINGS.

The configurable shared-prefix layout has end-to-end value. Normal JDK 8 Maven checks and the 66 existing targeted provider/catalog/template tests pass on this head. Three additional real-table lifecycle regressions reproduce the issues below (two assertion failures and one exception); reviewer-only source changes were removed afterward. The red Flink 1/Spark E2E job 125961705207 failed resolving Netty artifacts with a Maven Central connection reset before tests, so I have not attributed it to this PR.

if (!isExternal
&& latestMainSchema.isPresent()
&& EntropyInjectTemplateFilesDeletion.isTemplate(latestMainSchema.get())) {
EntropyInjectTemplateFilesDeletion.delete(table);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Delete data only after the catalog accepts DROP

This deletes live files before dropTableImpl has accepted the drop. Hive's implementation first calls HMS dropTable, and JDBC first deletes its catalog record; either can fail with authorization/transport/SQL errors while leaving the table registered. I reproduced the ordering with a real template append table and a catalog whose dropTableImpl throws: getTable still succeeds after the failed DROP, but the previously present data file is gone. Baseline defers file deletion until the catalog operation succeeds. Please collect the referenced paths first and perform physical deletion only after successful catalog deletion, with the same ordering for branch files.

FileIO tableFileIO = fileIO(tablePath);
SchemaManager schemaManager = new FileSystemSchemaManager(tableFileIO, tablePath);
externalPaths.addAll(getSchemaExternalPaths(schemaManager.listAll()));
FileStoreTable table = (FileStoreTable) getTable(identifier);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep DROP metadata-only for existing non-template tables

The unconditional getTable constructs read wrappers even when no branch uses the new strategy. A valid existing chain table can have its snapshot branch removed through branchManager().dropBranch("snapshot"); DROP now throws NoSuchElementException in createChainTable at this new call instead of deleting the table. I reproduced this with both chain branch options and no external paths, after first confirming the intact chain loads. The parent implementation only reads persisted schemas and can drop it. Please create a raw branch-local table only when template cleanup actually requires it, preserving the previous metadata-only cleanup path.

Optional<TableSchema> latestMainSchema = schemaManager.latest();
if (!isExternal
&& latestMainSchema.isPresent()
&& EntropyInjectTemplateFilesDeletion.isTemplate(latestMainSchema.get())) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Include historical template strategies in DROP cleanup

External paths and strategies are mutable, but cleanup is selected only from the latest schema. With a real table, I wrote one file using the template, changed both options to a new ordinary path with round-robin, then dropped the table. DROP succeeds and removes its metadata while the old expanded template file remains. getSchemaExternalPaths(listAll()) only supplies the literal {hash} path, so it cannot reclaim that file, and the surviving manifest references have been lost. Please inspect the schema history of each branch when deciding whether to collect manifest-referenced files, rather than requiring its latest strategy to remain the template.

@JingsongLi JingsongLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Four additional findings on 719ef55, verified with targeted reproductions.

}

for (String externalPath : paths) {
boolean isTemplate = TemplateEntropyInjectExternalPathProvider.isTemplate(externalPath);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P0] Keep template paths out of recursive DROP cleanup

An empty table can be created with file:///shared/{hash}/.. because this check sees {hash} in the raw option. Path normalizes it to file:///shared, and getSchemaExternalPaths passes that directory to recursive cleanup. I reproduced this with FileSystemCatalog. Dropping the empty table deleted a neighboring table's committed data file while leaving that table registered. Please validate that the placeholder survives URI path normalization and exclude template data paths from recursive deletion.

CoreOptions.DATA_FILE_EXTERNAL_PATHS_STRATEGY.key(),
ExternalPathStrategy.ENTROPY_INJECT_TEMPLATE));
}
if (!templateStrategy && isTemplate) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve literal {hash} directories for existing strategies

An existing round-robin table can use a directory literally named {hash}. I created and wrote such a table with the baseline validation, then reopened it on this head. Both scan planning and writer creation fail at this check because runtime validation also applies to persisted schemas. Please interpret {hash} only when entropy-inject-template is selected.

&& EntropyInjectTemplateFilesDeletion.isTemplate(latestMainSchema.get())) {
EntropyInjectTemplateFilesDeletion.delete(table);
}
for (String branch : FileSystemBranchManager.branches(tableFileIO, tablePath)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Retain cleanup references when dropping a template branch

I wrote one file only to dev on a template append table, dropped dev, and then dropped the table. The file remained in the shared prefix. dropBranch removes the metadata that points to the branch's manifests, so this loop can no longer find the file. The orphan cleaner also rejects template tables. Please retain the branch's cleanup references until its files can be reclaimed, while protecting files still referenced by surviving branches.


private static void validateExternalPaths(CoreOptions options) {
String externalPaths = options.dataFileExternalPaths();
if (externalPaths == null || externalPaths.isEmpty()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Require a non-empty template when the strategy is selected

CREATE TABLE accepts entropy-inject-template with no data-file.external-paths. Writes then go to the table directory, while the orphan cleaner still refuses the table. An explicitly empty path also makes DROP TABLE fail when it constructs a Path. Please require exactly one non-empty template for this strategy during CREATE and ALTER.

@wzx140
wzx140 force-pushed the codex/entropy-inject-template branch from 923324a to 087d455 Compare November 19, 2026 03:22

@JingsongLi JingsongLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shared object-store prefixes have a concrete use case. At this head I ran the external-path and catalog suites. The earlier template validation case is covered. Please also rebase the SchemaValidation change, which conflicts with the review base.

}

dropTableImpl(identifier, new ArrayList<>(externalPaths));
templateDeletions.forEach(EntropyInjectTemplateFilesDeletion::deleteCollectedFiles);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep a retry path for failed external-file cleanup

I wrote a real file to an expanded template path, then injected a one-time IOException for deletion of that external file. DROP returned successfully and removed the table metadata. Repeating DROP IF EXISTS after storage recovered left the file behind. The orphan cleaner intentionally rejects template-managed tables, so the ordinary recovery workflow has no way to find the abandoned file. Retain a durable cleanup plan across DROP, or provide a retryable cleanup path with a clear status when file deletion fails.

@wzx140
wzx140 force-pushed the codex/entropy-inject-template branch from 087d455 to ff1f485 Compare November 22, 2026 13:32
@wzx140
wzx140 requested a review from JingsongLi November 23, 2026 02:18
- 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.
- 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.
- SchemaValidation.java: interpret the placeholder only for the template strategy.
- EntropyInjectTemplateTest.java: verify a literal round-robin path can write and plan a scan.
- SchemaValidation.java: reject missing, blank and multiple template paths during schema validation.
- EntropyInjectTemplateTest.java: check CREATE and ALTER both require the path.
- 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.
- 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.
- 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.
- 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.
@wzx140
wzx140 force-pushed the codex/entropy-inject-template branch from ff1f485 to 0675813 Compare November 23, 2026 06:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants