Repository navigation
Implement entity-property idempotency for createTable - #4912
Conversation
There was a problem hiding this comment.
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. |
| Instant idempotencyExpiry = | ||
| effectiveKey | ||
| .map(k -> Instant.now().plus(idempotencyConfiguration.ttl())) | ||
| .orElse(null); |
| public LoadTableResponse createTableDirect( | ||
| Namespace namespace, | ||
| CreateTableRequest request, | ||
| EnumSet<AccessDelegationMode> delegationModes, | ||
| Optional<String> refreshCredentialsEndpoint, | ||
| Optional<UUID> idempotencyKey, | ||
| Instant idempotencyExpiry) { |
| 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()); | ||
| } |
| 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
left a comment
There was a problem hiding this comment.
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.
|
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 |
|
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 |
|
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);
Run: |
|
Thanks @huaxingao for the benchmark. These number looks encouraging. |
dimas-b
left a comment
There was a problem hiding this comment.
The general direction of this PR LGTM 👍
Posting some more incremental review comments.
|
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); |
There was a problem hiding this comment.
PriorityQueue is probably a good fit for this use case.
There was a problem hiding this comment.
Switched to PriorityQueue
| } | ||
| } else { | ||
| String json = | ||
| raw.startsWith(WINDOW_FORMAT_JSON_V1) |
There was a problem hiding this comment.
Do we have to support both formats? This code has not even been merged to main yet 🤔
There was a problem hiding this comment.
removed WINDOW_FORMAT_JSON_V1
| asMap.put(entry.key, entry.expiryMillis); | ||
| } | ||
| try { | ||
| byte[] smile = SMILE_MAPPER.writeValueAsBytes(asMap); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
This is probably not necessary. idempotencyRequestContext is request-scoped and setPendingKey() guards against overwrites, right?
There was a problem hiding this comment.
You are right. I dropped try/finally.
| ? Optional.ofNullable(idempotencyKey) | ||
| : Optional.empty(); | ||
| try { | ||
| idempotencyRequestContext.setPendingKey(effectiveKey.orElse(null)); |
There was a problem hiding this comment.
idempotencyKey comes from a header, right? It might be best to have a filter to call setPendingKey()... similar to RealmContextHolder.set() called from RealmContextFilter
There was a problem hiding this comment.
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().
| 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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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()); |
There was a problem hiding this comment.
This assert is not meaningful since the value being tested is a Base64-encoded binary. It cannot possibly contain stale.
| Map<String, String> internal = EntityIdempotency.recordKey(Map.of(), key, LATER, NOW); | ||
|
|
||
| assertThat(internal).containsKey(IDEMPOTENCY_KEYS_PROPERTY); | ||
| assertThat(EntityIdempotency.hasLiveKey(internal, key, NOW)).isTrue(); |
There was a problem hiding this comment.
This assert does not contribute to the purpose of this test: recordKeyStampsKeyWithExpiry 🤔 What does it have to do with expiry?
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
Please add a test for this... I could not find it :)
There was a problem hiding this comment.
Added a new testrecordKeyEvictsEarliestWhenFull
| createTableRequest, | ||
| delegationModes, | ||
| refreshCredentialsEndpoint, | ||
| effectiveKey); |
There was a problem hiding this comment.
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 🤔
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Does this class belong in polaris-core? It is only used by runtime/service classes 🤔
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
This method can probably be in IdempotencyRequestContext... WDYT?
There was a problem hiding this comment.
Moved to IdempotencyRequestContext
…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
left a comment
There was a problem hiding this comment.
Just a few more comments. I think this PR is almost ready.
| public class IdempotencyRequestContext { | ||
|
|
||
| private final IdempotencyConfiguration idempotencyConfiguration; | ||
| private @Nullable UUID pendingKey; |
There was a problem hiding this comment.
Would you mind using AtomicReference as this class may reused across threads (filter vs. REST service code)?
Cf.
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
It'd probably be prudent to assert that the second earliest key is still live too.
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
Should we check idempotencyRequestContext.isActive() instead?
There was a problem hiding this comment.
added idempotencyRequestContext.isActive() check
| fileIOFactory, | ||
| polarisEventDispatcher, | ||
| eventMetadataFactory, | ||
| null); |
There was a problem hiding this comment.
How about adding a constant for a "disabled" context, then idempotencyRequestContext will not have to be @Nullable 🤔
There was a problem hiding this comment.
added a DISABLED no-op constant and used it from the non-CDI constructor, so the field is no longer @Nullable.
dimas-b
left a comment
There was a problem hiding this comment.
LGTM 👍 Thanks for bearing with me, @huaxingao !
flyrain
left a comment
There was a problem hiding this comment.
LGTM. Thanks @huaxingao !
| return List.of(); | ||
| } | ||
| if (!raw.startsWith(WINDOW_FORMAT_SMILE_V1)) { | ||
| throw new IllegalArgumentException("Unrecognized idempotency key window format"); |
There was a problem hiding this comment.
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?
Summary
Prototype of single-transaction idempotency for Iceberg REST
createTable: theIdempotency-Keyis 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 iscreateTableonly.How it works
LocalIcebergCatalog.doCommitstamps the key (with TTL expiry) into the new table entity's internal properties underpolaris-idempotency-keys({uuid → expiryMillis}JSON), in the same metastore transaction as the create.createTableDirectresolves the existing table, runsEntityIdempotency.hasLiveKey(...), and if the key is live → replays by loading the table and buildingLoadTableResponse(no re-execute, no stored response body).Config (disabled by default):
polaris.idempotency.enabled(defaultfalse)polaris.idempotency.ttl(defaultPT5M)Comparison vs #4659
IdempotencyStoreimplIdempotencyStore+idempotency_recordtableBenchmark (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:jmhChecklist
CHANGELOG.md(if needed)site/content/in-dev/unreleased(if needed)