Skip to content

Implement entity-property idempotency for createTable - #4912

Merged
flyrain merged 12 commits into
apache:mainfrom
huaxingao:idempotency_entity_property
Jul 10, 2026
Merged

flyrain merged 12 commits into
apache:mainfrom
huaxingao:idempotency_entity_property

Conversation

@huaxingao

@huaxingao huaxingao commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Prototype of single-transaction idempotency for Iceberg REST createTable: the Idempotency-Key is embedded in the table entity's internal properties and committed atomically with the create — no separate idempotency store write, no record-after-success gap.

This is a comparison PR against #4659 (decoupled IdempotencyStore + record-after-success). Scope is createTable only.

How it works

  1. First request: LocalIcebergCatalog.doCommit stamps the key (with TTL expiry) into the new table entity's internal properties under polaris-idempotency-keys ({uuid → expiryMillis} JSON), in the same metastore transaction as the create.
  2. Retry: createTableDirect resolves the existing table, runs EntityIdempotency.hasLiveKey(...), and if the key is live → replays by loading the table and building LoadTableResponse (no re-execute, no stored response body).

Config (disabled by default):

  • polaris.idempotency.enabled (default false)
  • polaris.idempotency.ttl (default PT5M)

Comparison vs #4659

Entity-property (this PR) Separate store (#4659)
Atomicity (key + table same txn) Yes No (record-after-success gap)
Backend portability (JDBC, NoSQL, …) Free — uses existing entity write Needs per-backend IdempotencyStore impl
New SPI / schema None IdempotencyStore + idempotency_record table
Hot-table read cost Grows with key window on entity Idempotency reads separate from entity
Idempotency isolated from metastore No Yes

Benchmark (JMH, A/B with vs without key)

JMH microbenchmark (EntityIdempotencyBench) comparing the same entity internal-properties work without vs with an idempotency key. Measures CPU only (JSON serialize/parse); does not include metastore I/O or network.
Run: ./gradlew :polaris-core:jmh

Path Number of keys on entity no key with key added by idempotency
create (serialize on write) 1 448 ns 1,300 ns +852 ns (~0.9 µs)
create 8 450 ns 3,307 ns +2.9 µs
create 64 580 ns 18,325 ns +17.7 µs
load/retry (parse + replay check) 1 942 ns 1,487 ns +545 ns (~0.5 µs)
load/retry 8 943 ns 2,788 ns +1.8 µs
load/retry 64 913 ns 14,205 ns +13.3 µs

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 26, 2026 17:46
@github-project-automation github-project-automation Bot moved this to PRs In Progress in Basic Kanban Board Jun 26, 2026
@huaxingao
huaxingao marked this pull request as draft June 26, 2026 17:47

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

Introduces a prototype “entity-property” idempotency mechanism for createTable, embedding an Idempotency-Key marker directly into the created table entity’s internal properties so retries can replay the original success from current catalog state (instead of returning a 409 conflict).

Changes:

  • Add core utilities + tests to record and validate idempotency keys in entity internal properties (including TTL handling).
  • Plumb idempotency through the REST adapter and catalog handler, including replay-on-retry behavior for createTable.
  • Add end-to-end service tests and a JMH microbenchmark to evaluate overhead.

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
runtime/service/src/testFixtures/java/org/apache/polaris/service/TestServices.java Wires an IdempotencyConfiguration into IcebergCatalogAdapter for integration tests.
runtime/service/src/test/java/org/apache/polaris/service/idempotency/EntityIdempotencyCreateTableTest.java Adds end-to-end tests covering replay vs. conflict behavior for createTable with/without keys.
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfiguration.java Introduces deploy-time config mapping for enabling idempotency and setting TTL.
runtime/service/src/main/java/org/apache/polaris/service/catalog/iceberg/LocalIcebergCatalog.java Stamps the idempotency key + expiry into new table entities during commit.
runtime/service/src/main/java/org/apache/polaris/service/catalog/iceberg/IcebergCatalogHandler.java Implements replay-on-retry and concurrent-race replay for createTableDirect.
runtime/service/src/main/java/org/apache/polaris/service/catalog/iceberg/IcebergCatalogAdapter.java Gates honoring Idempotency-Key by config and forwards key/expiry to the handler.
polaris-core/src/test/java/org/apache/polaris/core/entity/EntityIdempotencyTest.java Adds unit tests for EntityIdempotency key recording, expiry, and purge-on-write behavior.
polaris-core/src/main/java/org/apache/polaris/core/entity/EntityIdempotency.java Adds the core encode/decode + “has live key” logic for internal-properties idempotency windows.
polaris-core/src/jmh/java/org/apache/polaris/core/entity/EntityIdempotencyBench.java Adds a microbenchmark to compare baseline vs. idempotency overhead for create/load paths.
polaris-core/build.gradle.kts Enables JMH support for polaris-core and adds required JMH dependencies.

Comment on lines +311 to +314
Instant idempotencyExpiry =
effectiveKey
.map(k -> Instant.now().plus(idempotencyConfiguration.ttl()))
.orElse(null);
Comment on lines +467 to +473
public LoadTableResponse createTableDirect(
Namespace namespace,
CreateTableRequest request,
EnumSet<AccessDelegationMode> delegationModes,
Optional<String> refreshCredentialsEndpoint,
Optional<UUID> idempotencyKey,
Instant idempotencyExpiry) {
Comment on lines +1796 to +1803
Map<String, String> internalProperties = storedProperties;
if (pendingIdempotencyKey != null) {
// Embed the idempotency key into the new entity's internal properties so it is persisted
// in the same transaction as the table create (no separate idempotency-store write).
internalProperties =
EntityIdempotency.recordKey(
storedProperties, pendingIdempotencyKey, pendingIdempotencyExpiry, Instant.now());
}
Comment on lines +85 to +93
private static Map<String, Long> decode(String raw) {
if (raw == null || raw.isEmpty()) {
return Map.of();
}
Map<String, String> asStrings = PolarisObjectMapperUtil.deserializeProperties(raw);
Map<String, Long> window = new HashMap<>(asStrings.size());
asStrings.forEach((k, v) -> window.put(k, Long.parseLong(v)));
return window;
}

@flyrain flyrain 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.

Thanks @huaxingao for the POC. I like this direction:

  • No additional persistence layer. It works immediately with any persistence implementation.
  • Entity operations (create/update) and idempotency key persistence are always transactional.
  • No additional maintenance procedure is needed. This is similar to how stale metadata.json entries are cleaned up during Iceberg table updates.

The only caveat is the number of idempotency keys a table may accumulate with frequent updates. I think it's manageable given how Iceberg tables are typically updated. We can also publish benchmark results to validate the overhead.

@huaxingao

Copy link
Copy Markdown
Contributor Author

Thanks @flyrain

Re benchmarks: I already added JMH results in the PR description (A/B with vs without key). For createTable (number of keys on entity = 1), overhead is about +0.9 µs on write and +0.5 µs on replay.

The number of keys = 8 / 64 rows are hypothetical for a future updateTable path (this PR is create-only). With the default TTL of 5 minutes, the number of live keys is roughly:

number of keys ≈ (update rate) × 5 min

So 64 keys corresponds to about one keyed update every ~5 seconds sustained over that window (300 s ÷ 64 ≈ 4.7 s). For comparison:

8 keys ≈ one update every ~40 s
64 keys ≈ one update every ~5 s
300 keys ≈ one update per second

@flyrain

flyrain commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Awesome. I think +0.9 µs is negligible with one key. Do we also have benchmark data for the following scenarios?

8 keys ≈ one update every ~40 s
64 keys ≈ one update every ~5 s
300 keys ≈ one update per second

@huaxingao

Copy link
Copy Markdown
Contributor Author

Benchmark results (JMH, CPU only)

Measures in-memory JSON serialize/parse + key check. Does not include metastore I/O, object store, or network.

How to read: “no key” = baseline entity (no idempotency keys). “with key” = entity with N keys (+ stamp or check). “extra” = with − no. Counts 8 / 64 / 300 are hypothetical (manually stamped); createTable always has 1 key.

Number of keys Create: no key Create: with key Create: extra Retry check: no key Retry check: with key Retry check: extra
1 0.32 µs 0.96 µs +0.65 µs 0.77 µs 1.08 µs +0.31 µs
8 0.32 µs 2.39 µs +2.1 µs 0.75 µs 2.02 µs +1.3 µs
64 0.39 µs 14.2 µs +13.8 µs 0.73 µs 10.1 µs +9.3 µs
300 0.39 µs 66.0 µs +66 µs 0.70 µs 47.3 µs +47 µs

Run: ./gradlew :polaris-core:jmh

@flyrain

flyrain commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Thanks @huaxingao for the benchmark. These number looks encouraging.
Even assuming a future updateTable path with a sustained rate of one keyed update per second (roughly 300 live keys with a 5 minute TTL), the additional CPU work is still only around 66 µs on write and 47 µs on retry checks. That is still well below 0.1 ms, which is tiny compared to the overall request latency.

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

Looks like this approach can work.

At the same time, it is significantly different from the previous impl. approach, so it probably deserves a mention on the dev ML.

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

The general direction of this PR LGTM 👍

Posting some more incremental review comments.

@dimas-b

dimas-b commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

The PR is still "draft", so I'm not sure if more changes are planned.... I may not be able to review until next week, but the general approach LGTM. Please feel free to merge if someone else approves earlier.

String keyString = key.toString();
window.removeIf(entry -> entry.key.equals(keyString));
while (window.size() >= MAX_WINDOW_SIZE) {
window.sort(BY_EXPIRY);

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.

Why sort repeatedly?

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.

PriorityQueue is probably a good fit for this use case.

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.

Switched to PriorityQueue

}
} else {
String json =
raw.startsWith(WINDOW_FORMAT_JSON_V1)

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.

Do we have to support both formats? This code has not even been merged to main yet 🤔

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.

removed WINDOW_FORMAT_JSON_V1

asMap.put(entry.key, entry.expiryMillis);
}
try {
byte[] smile = SMILE_MAPPER.writeValueAsBytes(asMap);

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.

Why not write the List directly? That should allow reconstructing it without re-sorting.

Also, the PageToken example shows how to reduce property name overhead by using single chars in @JsonProperty, while maintaining reasonable java method names.

Cf. https://github.com/apache/polaris/blob/46e6891a2c4f2f8b1d7e1015cff54d25a20a0df7/polaris-core/src/main/java/org/apache/polaris/core/persistence/pagination/PageToken.java#L52C3-L52C16

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.

Writing the List directly now (via TypeReference on read), and KeyEntry uses short @JsonProperty names (k/e) like PageToken.

Response.ok(response), response, namespace, createTableRequest.name())
.build();
} finally {
idempotencyRequestContext.clearPending();

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 probably not necessary. idempotencyRequestContext is request-scoped and setPendingKey() guards against overwrites, right?

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.

You are right. I dropped try/finally.

? Optional.ofNullable(idempotencyKey)
: Optional.empty();
try {
idempotencyRequestContext.setPendingKey(effectiveKey.orElse(null));

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.

idempotencyKey comes from a header, right? It might be best to have a filter to call setPendingKey()... similar to RealmContextHolder.set() called from RealmContextFilter

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.

Moved the header handling into a dedicated IdempotencyKeyFilter. It gates on the flag, parses the Idempotency-Key UUID, and sets it on the request-scoped IdempotencyRequestContext. The adapter now just forwards context.pendingKey().

@huaxingao
huaxingao marked this pull request as ready for review July 7, 2026 02:14
@huaxingao huaxingao changed the title Prototype entity-property idempotency for createTable Implement entity-property idempotency for createTable Jul 7, 2026
PriorityQueue<KeyEntry> window = new PriorityQueue<>(BY_EXPIRY);
for (KeyEntry entry : decode(internalProperties.get(IDEMPOTENCY_KEYS_PROPERTY))) {
if (entry.expiryMillis > nowMillis && !entry.key.equals(keyString)) {
window.add(entry);

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.

Sorry, my previous suggestion to use a PriorityQueue was not a good idea 😰

I think decode should return a List<KeyEntry> sorted by expiry time. On overflow, we simply remove the last entry.

Use Collections.binarySearch() to find the insertion point. This will keep the list sorted all the time. No re-sorting should be necessary.

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

Alternatively, we can just keep UUIDs in this list, sorted by timestamp (part of UUID v7).

On overflow, we'll drop the oldest UUID.

Lookup efficiently via Collections.binarySearch().

Expiry by itself probably does not help much in current impl. I suppose the list will be full most of the time, so the purging will be driven by the intake of new elements rather than by passage of time.

If we still want to purge expired entries, we can do so by applying the idempotencyConfiguration.ttl() to the UUID timestamp (as opposed to computing expiry Instant at request start).

If fake UUID timestamps is a concern, we can validate that they are within a grace window at the REST layer.

Furthermore, UUIDs can be serialized as two long values, which will be more efficient than their string form.

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.

I prefer the first one. recordKey now keeps a List<KeyEntry> sorted by expiry, inserts via Collections.binarySearch , and drops the earliest-expiring entry on overflow.

assertThat(EntityIdempotency.hasLiveKey(updated, fresh, muchLater)).isTrue();
assertThat(EntityIdempotency.hasLiveKey(updated, stale, muchLater)).isFalse();
// Confirm the stale entry was physically removed, not just expired.
assertThat(updated.get(IDEMPOTENCY_KEYS_PROPERTY)).doesNotContain(stale.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.

This assert is not meaningful since the value being tested is a Base64-encoded binary. It cannot possibly contain stale.

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.

removed

Map<String, String> internal = EntityIdempotency.recordKey(Map.of(), key, LATER, NOW);

assertThat(internal).containsKey(IDEMPOTENCY_KEYS_PROPERTY);
assertThat(EntityIdempotency.hasLiveKey(internal, key, NOW)).isTrue();

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 assert does not contribute to the purpose of this test: recordKeyStampsKeyWithExpiry 🤔 What does it have to do with expiry?

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.

I feel this test is redundant. I removed it.

// *before* inserting, so the key just recorded is always retained even when every entry shares
// the same expiry (e.g. a burst of writes at one instant) and expiry order can't rank recency.
while (window.size() >= MAX_WINDOW_SIZE) {
window.remove(0);

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.

Please add a test for this... I could not find it :)

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.

Added a new testrecordKeyEvictsEarliestWhenFull

createTableRequest,
delegationModes,
refreshCredentialsEndpoint,
effectiveKey);

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.

Changes in this class look like they just pass idempotency data through... WDYT about injecting IdempotencyRequestContext into the catalog? Then this class should not need any changes 🤔

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.

injected IdempotencyRequestContext into the handler so it reads the key itself. createTableDirect dropped its idempotency parameter and the adapter no longer references idempotency at all.

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.

Does this class belong in polaris-core? It is only used by runtime/service classes 🤔

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.

moved it (and its test) to org.apache.polaris.service.idempotency in runtime/service

return null; // could be an external catalog
}

private boolean idempotencyActive(Optional<UUID> idempotencyKey) {

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 method can probably be in IdempotencyRequestContext... 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.

Moved to IdempotencyRequestContext

huaxingao added 2 commits July 9, 2026 17:19
…property

Co-authored-by: Cursor <[email protected]>

# Conflicts:
#	runtime/service/src/main/java/org/apache/polaris/service/catalog/iceberg/LocalIcebergCatalog.java
#	runtime/service/src/testFixtures/java/org/apache/polaris/service/TestServices.java

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

Just a few more comments. I think this PR is almost ready.

public class IdempotencyRequestContext {

private final IdempotencyConfiguration idempotencyConfiguration;
private @Nullable UUID pendingKey;

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.

Would you mind using AtomicReference as this class may reused across threads (filter vs. REST service code)?

Cf.

private final AtomicReference<RealmContext> realmContext = new AtomicReference<>();

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.

switched to a single AtomicReference


// Read at NOW, when every recorded key would still be live if present, so absence == eviction.
assertThat(EntityIdempotency.hasLiveKey(internal, newest, NOW)).isTrue();
assertThat(EntityIdempotency.hasLiveKey(internal, earliest, NOW)).isFalse();

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.

It'd probably be prudent to assert that the second earliest key is still live too.

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.

added an assertion that the second-earliest key stays live

idempotencyRequestContext != null ? idempotencyRequestContext.pendingKey() : null;
Instant pendingIdempotencyExpiry =
idempotencyRequestContext != null ? idempotencyRequestContext.pendingExpiry() : null;
if (pendingIdempotencyKey != null) {

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 check idempotencyRequestContext.isActive() instead?

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.

added idempotencyRequestContext.isActive() check

fileIOFactory,
polarisEventDispatcher,
eventMetadataFactory,
null);

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.

How about adding a constant for a "disabled" context, then idempotencyRequestContext will not have to be @Nullable 🤔

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.

added a DISABLED no-op constant and used it from the non-CDI constructor, so the field is no longer @Nullable.

@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 Jul 10, 2026

@flyrain flyrain 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 @huaxingao !

return List.of();
}
if (!raw.startsWith(WINDOW_FORMAT_SMILE_V1)) {
throw new IllegalArgumentException("Unrecognized idempotency key window format");

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: should we consider treating a malformed window as "no live keys" (return empty) rather than throwing, so a bad property degrades to a normal 409 instead of a hard failure?

@flyrain
flyrain merged commit ef17e01 into apache:main Jul 10, 2026
25 checks passed
@github-project-automation github-project-automation Bot moved this from Ready to merge to Done in Basic Kanban Board Jul 10, 2026
@huaxingao

Copy link
Copy Markdown
Contributor Author

Thanks you so much @dimas-b @flyrain !!

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.

4 participants