Skip to content

Add Idempotency-Key support for Iceberg REST createTable - #4659

Closed
huaxingao wants to merge 15 commits into
apache:mainfrom
huaxingao:idempotency_new
Closed

huaxingao wants to merge 15 commits into
apache:mainfrom
huaxingao:idempotency_new

Conversation

@huaxingao

Copy link
Copy Markdown
Contributor

Adds support for the Iceberg REST Idempotency-Key header on createTable,
using an optimistic-commit model (a.k.a. Model B).

  • A client may send an Idempotency-Key (UUIDv7) header on createTable.
  • The terminal outcome is recorded only after the operation succeeds — there
    is no "reserve a slot first" step.
  • A retry with the same key replays an equivalent response rebuilt from current
    catalog state
    instead of returning a conflict. No HTTP response body is stored.
  • Reusing the same key for a different caller/operation/resource returns 422.

Checklist

  • 🛡️ Don't disclose security issues! (contact [email protected])
  • 🔗 Clearly explained why the changes are needed, or linked related issues: Fixes #
  • 🧪 Added/updated tests with good coverage, or manually tested (and explained how)
  • 💡 Added comments for complex logic
  • 🧾 Updated CHANGELOG.md (if needed)
  • 📚 Updated documentation in site/content/in-dev/unreleased (if needed)

Copilot AI review requested due to automatic review settings June 9, 2026 00:26
@github-project-automation github-project-automation Bot moved this to PRs In Progress in Basic Kanban Board Jun 9, 2026

Copilot AI 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.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Adds handler-level idempotency support for Iceberg REST createTable, backed by a pluggable per-realm idempotency store and optional background purging.

Changes:

  • Introduces IdempotencyHandlerSupport, IdempotencyConfiguration, CDI wiring, and a purge maintenance task.
  • Integrates idempotency into IcebergCatalogAdapter → IcebergCatalogHandler#createTableDirect flow and updates test fixtures.
  • Adds in-memory/JDBC store implementations and new unit/integration tests validating behavior.

Reviewed changes

Copilot reviewed 26 out of 26 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
runtime/service/src/testFixtures/java/org/apache/polaris/service/TestServices.java Allows tests to opt into idempotency wiring and passes support into adapter/handler.
runtime/service/src/test/java/org/apache/polaris/service/idempotency/IdempotencyHandlerSupportTest.java Unit tests for key validation and binding/conflict behavior.
runtime/service/src/test/java/org/apache/polaris/service/idempotency/IdempotencyCreateTableTest.java End-to-end idempotency tests for createTable via REST adapter.
runtime/service/src/test/java/org/apache/polaris/service/catalog/iceberg/IcebergCatalogHandlerTest.java Updates handler construction to include idempotency support.
runtime/service/src/main/java/org/apache/polaris/service/idempotency/InMemoryCdiIdempotencyStoreFactory.java CDI wrapper for selecting the in-memory store backend by identifier.
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyStoreFactoryProducer.java Produces the configured IdempotencyStoreFactory backend via @Identifier selection.
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyMaintenance.java Adds periodic purge of expired idempotency records.
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyHandlerSupport.java Core handler-side idempotency helper (validation, hashing, preflight/record).
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfiguration.java Quarkus config mapping for enabling and tuning idempotency.
runtime/service/src/main/java/org/apache/polaris/service/catalog/iceberg/IcebergCatalogHandlerFactory.java Injects and supplies idempotency support into handlers.
runtime/service/src/main/java/org/apache/polaris/service/catalog/iceberg/IcebergCatalogHandler.java Implements createTable idempotency flow with replay and binding checks.
runtime/service/src/main/java/org/apache/polaris/service/catalog/iceberg/IcebergCatalogAdapter.java Validates the Idempotency-Key param and forwards it to the handler.
polaris-core/src/test/java/org/apache/polaris/core/persistence/InMemoryIdempotencyStoreTest.java Tests for the in-memory store semantics (record/load/purge).
polaris-core/src/main/java/org/apache/polaris/core/persistence/InMemoryIdempotencyStoreFactory.java New core factory vending per-realm in-memory stores.
polaris-core/src/main/java/org/apache/polaris/core/persistence/InMemoryIdempotencyStore.java New core in-memory IdempotencyStore implementation.
polaris-core/src/main/java/org/apache/polaris/core/persistence/IdempotencyStoreFactory.java New SPI for per-realm store factories.
polaris-core/src/main/java/org/apache/polaris/core/persistence/IdempotencyStore.java Simplifies SPI to optimistic-commit model (load + recordIfAbsent + purge).
polaris-core/src/main/java/org/apache/polaris/core/entity/IdempotencyRecord.java Updates record model to finalized-only fields (principal hash, status, ttl).
persistence/relational-jdbc/src/test/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStorePostgresIT.java Updates JDBC store ITs to match new SPI and schema.
persistence/relational-jdbc/src/main/resources/postgres/schema-v4.sql Updates schema for finalized-only idempotency records + indexes for purge.
persistence/relational-jdbc/src/main/resources/h2/schema-v4.sql Same finalized-only schema changes for H2.
persistence/relational-jdbc/src/main/resources/cockroachdb/schema-v4.sql Same finalized-only schema changes for CockroachDB.
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/models/ModelIdempotencyRecord.java Updates JDBC model mapping to new record columns.
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStoreFactory.java Adds CDI factory for JDBC-backed idempotency store.
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStore.java Reworks JDBC store to recordIfAbsent optimistic-insert semantics.
CHANGELOG.md Documents new handler-level idempotency behavior and configuration.

Comment on lines +36 to +41
@Produces
@Singleton
public IdempotencyStoreFactory idempotencyStoreFactory(
IdempotencyConfiguration configuration, @Any Instance<IdempotencyStoreFactory> factories) {
return factories.select(Identifier.Literal.of(configuration.type())).get();
}
Comment on lines 126 to 131
} catch (SQLException e) {
throw new IdempotencyPersistenceException("Failed to finalize idempotency record", e);
if (datasourceOperations.isUniquenessConstraintViolation(e)) {
return new RecordResult(RecordResultType.DUPLICATE, load(realmId, idempotencyKey));
}
throw new IdempotencyPersistenceException("Failed to record idempotency entry", e);
}
Comment on lines +533 to +541
String resourceId =
idempotencySupport()
.resourceHash(
"create-table:"
+ namespace.toString()
+ ":"
+ request.name()
+ ":"
+ delegationModesToken(delegationModes));
Comment on lines +211 to +214
public Builder idempotencySupport(IdempotencyHandlerSupport idempotencySupport) {
this.idempotencySupport = idempotencySupport;
return this;
}
Comment on lines +63 to +85
void onStart(@Observes StartupEvent event) {
if (!configuration.enabled() || !configuration.purgeEnabled()) {
return;
}
long intervalMs = configuration.purgeInterval().toMillis();
purgeTimerId =
vertx.setPeriodic(
intervalMs,
ignored -> {
if (!purgeRunning.compareAndSet(false, true)) {
return;
}
Infrastructure.getDefaultWorkerPool()
.execute(
() -> {
try {
purgeOnce();
} finally {
purgeRunning.set(false);
}
});
});
}
@huaxingao
huaxingao force-pushed the idempotency_new branch 2 times, most recently from 99c53b6 to b983f61 Compare June 9, 2026 06:19

@dimas-b dimas-b 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.

Posting a couple of preliminary comments about CDI... will review in depth later.

@dimas-b dimas-b 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.

Posting some more comments... This is a complex PR, I hope you do not mind multiple review rounds.

sb.append("realm=").append(realmId).append('|');
sb.append("roles=");
new TreeSet<>(principal.getRoles()).forEach(r -> sb.append(r).append(','));
return sha256Hex(sb.toString());

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.

Should this be performed by PolarisPrincipal itself with the contract that materially different principals yield different hashes?

@adutra : WDYT?

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.

(posting this comment just to group unresolved issues under the latest review).

Comment on lines +238 to +246
if (!expectedPrincipalHash.equals(existing.principalHash())) {
throw new ConflictException(
"Idempotency-Key already used by a different caller for the same key");
}
if (!expectedResourceHash.equals(existing.resourceHash())
|| !expectedOperationType.equals(existing.operationType())) {
throw new ConflictException(
"Idempotency-Key already used for a different operation or resource");
}

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.

nit: Is it so critical to distinguish these two cases?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

collapsed them into a single ConflictException

@dimas-b dimas-b Jun 11, 2026 •

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.

I meant this to be more of a persistence thing - we could store only one hash value (not a blocker) .... WDYT?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Makes sense as a persistence simplification. I'd lean to keep them as separate columns, though: operation_type stays human-readable for debugging/observability, and the two extra hash columns are cheap. Happy to revisit as a follow-up if you feel strongly.

@dimas-b dimas-b 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.

@huaxingao : Thanks for the previous updates and for bearing with me. More incremental review comments below.

sb.append("realm=").append(realmId).append('|');
sb.append("roles=");
new TreeSet<>(principal.getRoles()).forEach(r -> sb.append(r).append(','));
return sha256Hex(sb.toString());

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.

(posting this comment just to group unresolved issues under the latest review).

@dimas-b dimas-b 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.

This round of comments concludes my first end-to-end review. Thanks for bearing with me @huaxingao !

The PR LGTM overall 👍

My biggest concern ATM is the maintenance / cleanup work. I'd propose to split it into a separate PR to enable the API call path changes to merge sooner.

@dimas-b dimas-b 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.

LGTM 👍 Just one remaining CDI concern.

public interface IdempotencyStoreFactory {

/** Returns the {@link IdempotencyStore} to use for the given realm. */
IdempotencyStore getOrCreateIdempotencyStore(RealmContext realmContext);

@dimas-b dimas-b Jun 15, 2026 •

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.

AdminToolProducers have an @ApplicationScoped dummyRealmConfig().

This should be able to fit nicely into IdempotencyStoreProducer.idempotencyStore(), I think 🤔

Could you share your actual build error?

dimas-b
dimas-b previously approved these changes Jun 16, 2026

@dimas-b dimas-b 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.

LGTM 👍 Thanks for bearing with me, @huaxingao !

@github-project-automation github-project-automation Bot moved this from PRs In Progress to Ready to merge in Basic Kanban Board Jun 16, 2026
dimas-b
dimas-b previously approved these changes Jun 16, 2026
@dimas-b

dimas-b commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

@huaxingao : could you mention this PR on dev for visibility? TBH, I lost track of the relevant thread there 😅

I'm fine merging this at any time.

@huaxingao

Copy link
Copy Markdown
Contributor Author

Thanks, @dimas-b. I just sent a discussion thread on dev to make the PR more visible.

And thanks again for spending so much time reviewing this PR. I really appreciate your thorough feedback and all your help! 🙏

@snazy snazy left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Could we make the changelog wording a bit more explicit about the exact guarantee here?

The current wording may be easy to read as "a concurrent retry with the same key will always replay instead of returning 409". As I understand the implementation, replay depends on the matching idempotency record being visible within the bounded lookup window; otherwise the original 409 can still be returned.

Small process note: this PR has to reshape the relational idempotency_records table because the earlier schema was added before the request-path semantics were actually settled or wired.

That is manageable here because the previous table was unused, but I think it is a useful example of why we should avoid landing persistence schema for speculative follow-up designs. Schema is one of the harder things to revise later, and premature DDL creates upgrade/documentation noise even when no real data migration is needed.

For future work, I think we should add relational schema only together with the implementation that actually uses it, or clearly mark it as temporary/experimental if it is intentionally provisional.

Comment thread CHANGELOG.md Outdated
- Added support for `register table` overwrite semantics in the Iceberg REST catalog flow (`overwrite=true`) for internal Polaris catalogs. With overwrite enabled, existing table pointers can be updated to a new metadata location while preserving default behavior for `overwrite=false`.
- Added `REGISTER_TABLE_OVERWRITE` authorization operation mapped to `TABLE_FULL_METADATA` for deterministic overwrite authorization.
- Added Polaris Spark 4.0 client.
- Added handler-level support for the Iceberg REST `Idempotency-Key` header on `createTable`, using an optimistic-commit model: the terminal outcome is recorded only after a successful (2xx) response and retries replay an equivalent response rebuilt from current catalog state (no response body is stored). The key is bound to the request-derived resource (operation, namespace, name and access-delegation modes) and the caller principal, so reusing a key for a different resource or by a different caller is rejected with HTTP 422. A retry that loses a concurrent create race replays the winning request instead of returning 409, and a replay returns 422 if the table has advanced beyond the originally-created state. Only successful outcomes are recorded — a retry after a failure simply re-runs the operation. Idempotency is disabled by default and configured under `polaris.idempotency`; records are kept in a standalone idempotency store decoupled from the metastore persistence.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
- Added handler-level support for the Iceberg REST `Idempotency-Key` header on `createTable`, using an optimistic-commit model: the terminal outcome is recorded only after a successful (2xx) response and retries replay an equivalent response rebuilt from current catalog state (no response body is stored). The key is bound to the request-derived resource (operation, namespace, name and access-delegation modes) and the caller principal, so reusing a key for a different resource or by a different caller is rejected with HTTP 422. A retry that loses a concurrent create race replays the winning request instead of returning 409, and a replay returns 422 if the table has advanced beyond the originally-created state. Only successful outcomes are recorded — a retry after a failure simply re-runs the operation. Idempotency is disabled by default and configured under `polaris.idempotency`; records are kept in a standalone idempotency store decoupled from the metastore persistence.
- Added experimental, disabled-by-default handler-level support for the Iceberg REST `Idempotency-Key` header on `createTable`. Polaris records successful outcomes only after `createTable` completes and rebuilds retry responses from current catalog state; it does not store response bodies or prevent duplicate in-flight execution. Concurrent create retries can replay the matching successful create if its idempotency record becomes visible within a bounded lookup window; otherwise the original 409 conflict is returned. Failed outcomes are not recorded, so retries after failures re-run the operation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks @snazy ! Applied your changelog suggestion. And good point on the schema: agreed it's better to land relational schema together with the code that uses it (or mark it provisional). I'll keep that in mind for the follow-up operations.

@dimas-b

dimas-b commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

@huaxingao : Could you check CI failures, please?

-- specific language governing permissions and limitations
-- under the License.

-- CockroachDB schema v4 (matching PostgreSQL schema v4)

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.

Header says "CockroachDB schema v4 (matching PostgreSQL schema v4)" but this is the v5 file — fix the label.

Comment on lines +570 to +571
String metadataLocation = response.tableMetadata().metadataFileLocation();
idempotencySupport().recordOutcome(preflight, 200, metadataLocation);

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.

Should we persist idempotency key and table creation in the same transaction? I'm bit worry about the correctness issue, for example, if create table succeeded, but idempotency key persistence failed. Polaris will response to client with a table create failure, right?

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.

This is a significant change in the overall feature design. I think this needs re-opening the end-to-end design discussion on dev.

IIRC, currently transaction boundaries are expected to be at each Persistence SPI method call level.

Cf. https://lists.apache.org/thread/rf5orxs815zs4h64p4rwp03q3pbgxb5r

@dimas-b dimas-b Jun 23, 2026 •

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.

... or if you could make an alternative PR for that impl. it would be nice, then we'd be able to compare the two approaches with concrete code in mind 👍

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.

Cf. #4912

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.

5 participants