← Back to Pull requests

Fix multi-table commit write skew using conditional entity writes #5961

Open
qlong opened this pull request with 2355 lines diff across 31 files
View on GitHub
qlong qlong commented on Nov 02, 2026 21:13 UTC
Author

Add conditional entity writes to the metastore SPI: a set of entity writes applied atomically, and only if conditions on other entities hold. Until now the only atomic condition a write could express was "the entity being written is still at its version", so a decision based on reading other entities could not be enforced at write time. This adds the general primitive; this change uses it to fix #5807, and later condition and write kinds (for example parent checks, create, drop) can be added without changing the SPI.

Persistence:

  • Add PolarisMetaStoreManager.writeEntitiesIfConditionsHold(ConditionalEntityWrite). Condition.Unchanged checks an entity's version without writing it; Write.Update is the existing compare-and-swap update. If any condition or write fails, nothing is written and the result is TARGET_ENTITY_CONCURRENTLY_MODIFIED.

  • updateEntitiesPropertiesIfNotChanged is now a default method that delegates to it.

  • Implement it on all backends. JDBC checks with SELECT ... FOR UPDATE in the same transaction as the updates, takes row locks in (catalog_id, id) order, and reports deadlocks (40P01) and serialization failures (40001) as conflicts. NoSQL adds a CHECK mutation, evaluated in the same commit and again on retry.
  • Fix (#5807):

  • A multi-table commit can list a table with requirements but no updates, to assert it is unchanged. Such tables were validated when the commit was staged but were not part of the atomic write, so two concurrent commits that each changed one table and asserted the other could both succeed.

  • commitTransaction now adds each requirement-only table as an Unchanged condition, after verifying that its entity still points to the metadata the requirements were validated against. Commits that only assert the same table do not fail each other.
  • Tests: conformance tests on all four backends (including PostgreSQL), with concurrent writers for write skew and crossed updates; a NoSQL test that forces a retry after a failed compare-and-swap; handler tests that inject a concurrent commit at the two points of the race.

    Fixes #5807

    Dev ML: https://lists.apache.org/thread.html/mkkmwfxr77qkzn5yodwdrjcknss7o4xy

    <!--
    📝 Describe what changes you're proposing, especially breaking or user-facing changes.
    📖 See https://github.com/apache/polaris/blob/main/CONTRIBUTING.md for more.
    -->

    Checklist


  • 🛡️ Don't disclose security issues! (contact security@apache.org)

  • 🔗 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)
  • Diff: 2355 lines (+2282 / -73) across 31 files Reviewer: kotwal-itpro Review duration: 45638m
    All Vouch review confidence checks passed
    Residual risk 0.08 = Change Risk (0.79) × (1 − Review Confidence (0.90)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.79 · 2355 lines diff across 31 files
    0.79
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.92 · 5 substantive comment(s)
    0.92
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    89%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    23 items
    qlong qlong commented on Nov 02, 2026 21:15 UTC
    Author

    #5820 also addresses #5807. It adds each requirement-only table to the commit as an update, so the table's entity is rewritten with a new version. This PR instead checks such tables without writing them, atomically with the other tables' updates, so that:

  • commits that only assert the same table don't conflict with each other, and the table's version isn't bumped;

  • the check is bound to the metadata the requirements were validated against, so a commit between loading and resolving the table is detected.
  • orca-review-bot orca-review-bot commented on code on Nov 02, 2026 22:55 UTC
    Code Review
    persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/JdbcBasePersistenceImpl.java:1
    @@ -174,6 +176,100 @@ public void writeEntities(
         }
       }
     
    +  /** SQLState of a deadlock (PostgreSQL). */
    +  private static final String DEADLOCK_SQL_STATE = "40P01";
    +
    +  /** SQLState of a serialization failure (PostgreSQL, CockroachDB). */
    +  private static final String SERIALIZATION_FAILURE_SQL_STATE = "40001";
    +
    +  /** A check or a compare-and-swap update of a {@link #checkAndWriteEntities} batch. */
    +  private record BatchStep(
    +      PolarisEntityCore entity, PolarisBaseEntity updated, PolarisBaseEntity original) {}
    +
    +  @Override
    +  public void checkAndWriteEntities(
    +      @NonNull PolarisCallContext callCtx,
    +      @NonNull List<PolarisEntityCore> unchangedEntities,
    +      @NonNull List<PolarisBaseEntity> entities,
    +      @NonNull List<PolarisBaseEntity> originalEntities) {
    +    List<BatchStep> steps = new ArrayList<>(unchangedEntities.size() + entities.size());
    +    for (PolarisEntityCore unchanged : unchangedEntities) {
    +      steps.add(new BatchStep(unchanged, null, null));
    +    }
    +    for (int i = 0; i < entities.size(); i++) {
    +      steps.add(new BatchStep(entities.get(i), entities.get(i), originalEntities.get(i)));
    +    }
    +    // Take the row locks of all batches in the same order, so that two batches that touch the same
    +    // entities never wait for each other in a cycle, which the database would resolve by failing
    +    // one of them with a deadlock. Any total order works. Within a realm the primary key is
    +    // (realm_id, id), so the id alone would be enough today; the catalog id is kept in the key
    +    // because that is how entities are addressed, and the order stays total if entity ids are ever
    +    // only unique within a catalog, for example with federated catalogs.
    +    steps.sort(
    +        Comparator.comparingLong((BatchStep step) -> step.entity().getCatalogId())
    +            .thenComparingLong(step -> step.entity().getId()));
    +
    +    try {
    +      datasourceOperations.runWithinTransaction(
    +          connection -> {
    +            for (BatchStep step : steps) {
    +              if (step.updated() == null) {
    +                checkEntityUnchanged(connection, step.entity());
    +              } else {
    +                try {
    +                  persistEntity(
    +                      callCtx,
    +                      step.updated(),
    +                      step.original(),
    +                      connection,
    +                      datasourceOperations::execute);
    +                } catch (RetryOnConcurrencyException e) {
    +                  throw new EntityConcurrentlyModifiedException(step.entity(), e, e.getMessage());
    +                }
    +              }
    +            }
    +            return true;
    +          });
    +    } catch (SQLException e) {
    +      if (DEADLOCK_SQL_STATE.equals(e.getSQLState())
    +          || SERIALIZATION_FAILURE_SQL_STATE.equals(e.getSQLState())) {
    +        throw new RetryOnConcurrencyException(
    +            e,
    +            "Entities concurrently modified, the database rejected the batch: %s",
    +            e.getMessage());
    +      }
    +      throw new RuntimeException(
    +          String.format(
    +              "Error executing the transaction for checking and writing entities due to %s",
    +              e.getMessage()),
    +          e);
    +    }
    +  }
    +
    +  /** Locks the entity's row, and fails unless the entity exists with the expected version. */
    +  private void checkEntityUnchanged(Connection connection, PolarisEntityCore expected)
    +      throws SQLException {
    +    AtomicReference<PolarisChangeTrackingVersions> current = new AtomicReference<>();
    +    datasourceOperations.executeSelectOverStream(

    This select runs through withRetries, which retries 40001 on the same connection. Inside runWithinTransaction that connection's transaction is already aborted, so the retry fails with a different SQLState. The 40001/40P01 mapping below doesn't catch that, and the caller gets a 500. It's harmless with the default max-retries=1, and Postgres at READ COMMITTED won't raise 40001 here. But CockroachDB with max-retries=3 (the docs example) would hit it. Can we skip the inner retry when we're already inside the transaction?

    <sub>🤖 AI-generated review comment — agents make mistakes, so please verify before acting on it.</sub>

    orca-review-bot orca-review-bot commented on code on Nov 02, 2026 22:55 UTC
    Code Review
    persistence/nosql/persistence/metastore/src/main/java/org/apache/polaris/persistence/nosql/metastore/NoSqlMetaStore.java:1
    @@ -356,13 +361,79 @@ EntityResult updateEntity(PolarisBaseEntity entity) {
         return createOrUpdateEntity(UPDATE, entity);
       }
     
    -  EntitiesResult updateEntities(List<EntityWithPath> entities) {
    +  /**
    +   * Applies the batch in a single commit of the catalog state: the checks and the updates are
    +   * evaluated against one consistent state, and the commit is retried against the new state if a
    +   * concurrent commit moved the state.
    +   *
    +   * <p>All entities of a batch must be of the same entity type and catalog.
    +   */
    +  ConditionalEntityWriteResult writeEntitiesIfConditionsHold(ConditionalEntityWrite batch) {
    +    var updates = new ArrayList<EntityUpdate>();
    +    for (var condition : batch.conditions()) {
    +      if (!(condition instanceof Condition.Unchanged unchanged)) {
    +        throw new IllegalArgumentException("Unsupported condition " + condition);
    +      }
    +      updates.add(new EntityUpdate(CHECK, identityOf(unchanged.entity())));
    +    }
    +    var checks = updates.size();
    +    for (var write : batch.writes()) {
    +      if (!(write instanceof Write.Update update)) {
    +        throw new IllegalArgumentException("Unsupported write " + write);
    +      }
    +      updates.add(new EntityUpdate(UPDATE, update.entity()));
    +    }
    +    if (updates.isEmpty()) {
    +      return new ConditionalEntityWriteResult(List.of());
    +    }
    +
         LOGGER
             .atDebug()
    -        .addArgument(() -> logEntitiesInfo(entities.stream().map(EntityWithPath::entity).toList()))
    -        .log("update entities: {}");
    +        .addArgument(checks)
    +        .addArgument(updates.size() - checks)
    +        .log("write entity batch: {} checks, {} updates");
    +
    +    var byCatalogAndEntityType =
    +        updates.stream()
    +            .collect(Collectors.groupingBy(u -> updateKeyForCatalogAndEntityType(u.entity())));
    +    checkArgument(
    +        byCatalogAndEntityType.size() == 1,
    +        "Cannot atomically write entities against multiple targets: %s",
    +        byCatalogAndEntityType.keySet());
    +
    +    var results =
    +        performEntityMutations(byCatalogAndEntityType.keySet().iterator().next(), updates);
    +
    +    // Each update yields exactly one result, in order.
    +    var all = results.results();
    +    for (int i = 0; i < all.size(); i++) {
    +      var result = all.get(i);
    +      if (result.getReturnStatus() != BaseResult.ReturnStatus.SUCCESS) {
    +        var status =
    +            result.getReturnStatus() == BaseResult.ReturnStatus.ENTITY_NOT_FOUND

    Only ENTITY_NOT_FOUND is remapped here, so any other failed status passes through as-is. The writeEntitiesIfConditionsHold javadoc says every failed condition or write gives TARGET_ENTITY_CONCURRENTLY_MODIFIED, and the transactional impl always returns that. Can we map every non-success status here, or loosen the javadoc?

    <sub>🤖 AI-generated review comment — agents make mistakes, so please verify before acting on it.</sub>

    orca-review-bot orca-review-bot commented on code on Nov 02, 2026 22:55 UTC
    Code Review
    polaris-core/src/main/java/org/apache/polaris/core/persistence/PolarisMetaStoreManager.java:1
    @@ -296,18 +298,63 @@ default BaseResult bootstrapPolarisService(@NonNull PolarisCallContext callCtx)
           @Nullable List<PolarisEntityCore> catalogPath,
           @NonNull PolarisBaseEntity entity);
     
    +  /**
    +   * Applies entity writes atomically, and only if all of the batch's conditions hold.
    +   *
    +   * <p>The result is the same as if the batch ran alone, at serializable isolation, whatever the
    +   * isolation level of the backend:
    +   *
    +   * <ul>
    +   *   <li>All-or-nothing: either every condition holds and every write is applied, or nothing is
    +   *       written.
    +   *   <li>{@link ConditionalEntityWrite.Condition.Unchanged}: the entity exists with the given
    +   *       entity version at the time the batch is applied. The entity is not written, so a
    +   *       concurrent batch that only checks the same entity does not conflict with this one.
    +   *   <li>{@link ConditionalEntityWrite.Write.Update}: has the semantics of {@link
    +   *       #updateEntityPropertiesIfNotChanged(PolarisCallContext, List, PolarisBaseEntity)}.
    +   * </ul>
    +   *
    +   * <p>A condition or write that fails, including one on an entity that no longer exists, gives
    +   * {@link BaseResult.ReturnStatus#TARGET_ENTITY_CONCURRENTLY_MODIFIED}, with the failing entity
    +   * when it is known. A concurrency failure of the backend, such as a deadlock or a serialization
    +   * failure, is reported the same way and is never thrown, so that callers can treat all of them as
    +   * a conflict to retry.
    +   *
    +   * <p>The {@code catalogPath} of the batch's members is carried but not validated. Each entity may
    +   * be the subject of at most one condition or write.
    +   *
    +   * <p>A backend may restrict which entities can be in one batch, and reject a batch it cannot
    +   * apply atomically with an {@link IllegalArgumentException}: the NoSQL backend requires all
    +   * entities of a batch to be of the same entity type and in the same catalog.
    +   *
    +   * @param callCtx call context
    +   * @param batch the conditions to check and the writes to apply
    +   * @return the written entities in the order of the batch's writes, or a failure
    +   */
    +  @NonNull ConditionalEntityWriteResult writeEntitiesIfConditionsHold(

    New abstract SPI method (plus BasePersistence.checkAndWriteEntities), so out-of-tree backends stop compiling. AGENTS.md asks for that to go through the dev list. Is there a thread we can link, especially since #5820 fixes the same bug without changing the SPI?

    <sub>🤖 AI-generated review comment — agents make mistakes, so please verify before acting on it.</sub>

    orca-review-bot orca-review-bot commented on Nov 02, 2026 22:55 UTC
    Reviewer

    Nice fix. The per-backend checks look right, sorting the JDBC locks is a good call, and the race tests are thorough. Main things: (1) this adds abstract methods to PolarisMetaStoreManager and BasePersistence, so custom backends break. Can we link the dev-list discussion, and settle this vs #5820? (2) There's one JDBC retry path that can still return a 500 on a conflict (inline). (3) NoSQL doesn't always return the failure status the javadoc promises (inline). CHANGELOG and authz look fine.

    <sub>🤖 AI-generated review comment — agents make mistakes, so please verify before acting on it.</sub>

    kotwal-itpro kotwal-itpro commented on Nov 09, 2026 20:35 UTC
    Reviewer

    Thanks for this, @qlong. I read through the SPI, the JDBC and NoSQL implementations and the handler change, but haven't run it locally.

    The handler side looks right to me. Comparing the resolved entity's metadata location with the metadata the requirements were validated against closes the window between loadTable and the resolve, and the atomic Unchanged check covers everything after that. testRequirementOnlyTableCommittedBetweenItsLoadAndItsResolveFailsTheCommit pins the first part.

    One question on the JDBC side. checkEntityUnchanged takes SELECT ... FOR UPDATE on a row it only checks. The result stays correct, but two commits that only check the same table now wait for each other. They don't fail, as testBatchesThatOnlyCheckTheSameEntityDoNotConflict shows, but they run one at a time. When many commits assert the same table, which is the case Yufei raised on the list, they would queue on that one row.

    FOR SHARE would let commits that only check the row run in parallel, and still make a concurrent update of the row wait until the batch commits. The (catalog_id, id) lock order would still rule out deadlocks, since a batch either checks or writes an entity, never both. PostgreSQL supports FOR SHARE. I'm not sure about H2, and I think CockroachDB only takes shared locks under READ COMMITTED by default, so this may need to depend on the database type. Is FOR UPDATE deliberate here, or would FOR SHARE work?

    For context, the multi-table promotion doc in #5740 relies on the multi-table commit being atomic, so I'm glad to see #5807 fixed.

    kotwal-itpro kotwal-itpro commented on Nov 12, 2026 19:42 UTC
    Contributor

    Thanks @qlong, FOR SHARE on PostgreSQL with FOR UPDATE on H2 and CockroachDB looks good to me, and testGenerateCheckEntityQuery_lockClausePerDatabase pins it.

    iprithv iprithv requested changes on Nov 13, 2026 18:07 UTC
    Changes Requested Reviewer

    I think this makes sense, checkEntityUnchanged goes through executeSelectOverStream(connection, …), and that overload still runs withRetries on the same connection.

    We’re already inside runWithinTransaction here. If the SELECT hits 40001 (easy to see on Cockroach with max-retries>1, the docs example uses 3), the transaction is aborted, the retry gets something like 25P02 instead, and the 40001/40P01 mapping below never sees the original conflict. Caller ends up with a 500 instead of a concurrency failure / 409.

    persistEntity’s execute(connection) path doesn’t retry, which is what we want inside a txn. Can we do the same for this select, skip the inner retry when we already own the connection?

    flyrain flyrain commented on code on Nov 14, 2026 00:12 UTC
    Code Review
    polaris-core/src/main/java/org/apache/polaris/core/persistence/AtomicOperationMetaStoreManager.java:1
    @@ -965,39 +967,43 @@ public void deletePrincipalSecrets(
     
       /** {@inheritDoc} */
       @Override
    -  public @NonNull EntitiesResult updateEntitiesPropertiesIfNotChanged(

    Can we deprecate it instead of replacing it with a new method?

    ZephyrYWZhou ZephyrYWZhou commented on Nov 14, 2026 22:34 UTC
    Contributor

    Thanks @qlong this reads well! Reducing the multi-table commit race to one general checkAndWriteEntities is nice. Two inline notes on the sealed types and on duplicates. +1 to @iprithv's point about the retry inside the transaction. FYI the DynamoDB backend gets a stub here; I think TransactWriteItems with a ConditionCheck can implement Unchanged later.

    ZephyrYWZhou ZephyrYWZhou commented on code on Nov 14, 2026 22:36 UTC
    Code Review
    polaris-core/src/main/java/org/apache/polaris/core/persistence/dao/entity/ConditionalEntityWrite.java:1
    @@ -0,0 +1,137 @@
    +/*
    + * 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.polaris.core.persistence.dao.entity;
    +
    +import java.util.ArrayList;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Set;
    +import org.apache.polaris.core.entity.PolarisBaseEntity;
    +import org.apache.polaris.core.entity.PolarisEntityCore;
    +import org.jspecify.annotations.NonNull;
    +import org.jspecify.annotations.Nullable;
    +
    +/**
    + * Entity writes that are applied atomically, and only if all conditions hold. See {@code
    + * PolarisMetaStoreManager#writeEntitiesIfConditionsHold}.
    + *
    + * <p>Each entity may be the subject of at most one condition or write, so a conditional write can
    + * neither check and write the same entity (a write already compares the entity's versions) nor
    + * write it twice.
    + */
    +public record ConditionalEntityWrite(
    +    @NonNull List<Condition> conditions, @NonNull List<Write> writes) {
    +
    +  /**
    +   * A condition that must hold for the writes to be applied. Conditions are evaluated atomically
    +   * with the writes. Backends must handle every kind and must never ignore one.
    +   */
    +  public sealed interface Condition {
    +
    +    /**
    +     * The entity still exists, with the given entity version. The entity is only checked: it is not
    +     * written, and its version, last-update time and properties stay as they are.
    +     *
    +     * <p>Only {@link PolarisEntityCore#getEntityVersion()} is compared. A change of the grant
    +     * records version does not fail the condition, because it does not change the entity itself.
    +     *
    +     * @param catalogPath path to the entity's parent, null if the entity is top-level; carried but
    +     *     not validated
    +     * @param entity identity and expected version of the entity
    +     */
    +    record Unchanged(
    +        @Nullable List<PolarisEntityCore> catalogPath, @NonNull PolarisEntityCore entity)
    +        implements Condition {}
    +  }
    +
    +  /** A write, applied only if all conditions hold. Backends must handle every kind. */
    +  public sealed interface Write {
    +
    +    /**
    +     * Updates an entity, if it is still at the versions of {@code entity}: the entity version and
    +     * the grant records version. This has the same semantics as {@code
    +     * PolarisMetaStoreManager#updateEntityPropertiesIfNotChanged}.
    +     *
    +     * @param catalogPath path to the entity's parent, null if the entity is top-level; carried but
    +     *     not validated
    +     * @param entity the entity to write, at the versions it was read
    +     */
    +    record Update(@Nullable List<PolarisEntityCore> catalogPath, @NonNull PolarisBaseEntity entity)
    +        implements Write {}
    +  }
    +
    +  public ConditionalEntityWrite {
    +    conditions = List.copyOf(conditions);
    +    writes = List.copyOf(writes);
    +
    +    Set<EntityKey> entities = new HashSet<>();
    +    for (Write write : writes) {
    +      if (!(write instanceof Write.Update update)) {
    +        throw new IllegalArgumentException("Unsupported write " + write);

    Since Write and Condition are sealed, could we use a switch over the sealed type in these places (here, AtomicOperationMetaStoreManager, JDBC, NoSQL, transactional)? Adding a new kind would then fail to compile in every backend, rather than throw IllegalArgumentException at run time. WDYT?

    ZephyrYWZhou ZephyrYWZhou commented on code on Nov 14, 2026 22:36 UTC
    Code Review
    polaris-core/src/main/java/org/apache/polaris/core/persistence/dao/entity/ConditionalEntityWrite.java:1
    @@ -0,0 +1,137 @@
    +/*
    + * 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.polaris.core.persistence.dao.entity;
    +
    +import java.util.ArrayList;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Set;
    +import org.apache.polaris.core.entity.PolarisBaseEntity;
    +import org.apache.polaris.core.entity.PolarisEntityCore;
    +import org.jspecify.annotations.NonNull;
    +import org.jspecify.annotations.Nullable;
    +
    +/**
    + * Entity writes that are applied atomically, and only if all conditions hold. See {@code
    + * PolarisMetaStoreManager#writeEntitiesIfConditionsHold}.
    + *
    + * <p>Each entity may be the subject of at most one condition or write, so a conditional write can
    + * neither check and write the same entity (a write already compares the entity's versions) nor
    + * write it twice.
    + */
    +public record ConditionalEntityWrite(
    +    @NonNull List<Condition> conditions, @NonNull List<Write> writes) {
    +
    +  /**
    +   * A condition that must hold for the writes to be applied. Conditions are evaluated atomically
    +   * with the writes. Backends must handle every kind and must never ignore one.
    +   */
    +  public sealed interface Condition {
    +
    +    /**
    +     * The entity still exists, with the given entity version. The entity is only checked: it is not
    +     * written, and its version, last-update time and properties stay as they are.
    +     *
    +     * <p>Only {@link PolarisEntityCore#getEntityVersion()} is compared. A change of the grant
    +     * records version does not fail the condition, because it does not change the entity itself.
    +     *
    +     * @param catalogPath path to the entity's parent, null if the entity is top-level; carried but
    +     *     not validated
    +     * @param entity identity and expected version of the entity
    +     */
    +    record Unchanged(
    +        @Nullable List<PolarisEntityCore> catalogPath, @NonNull PolarisEntityCore entity)
    +        implements Condition {}
    +  }
    +
    +  /** A write, applied only if all conditions hold. Backends must handle every kind. */
    +  public sealed interface Write {
    +
    +    /**
    +     * Updates an entity, if it is still at the versions of {@code entity}: the entity version and
    +     * the grant records version. This has the same semantics as {@code
    +     * PolarisMetaStoreManager#updateEntityPropertiesIfNotChanged}.
    +     *
    +     * @param catalogPath path to the entity's parent, null if the entity is top-level; carried but
    +     *     not validated
    +     * @param entity the entity to write, at the versions it was read
    +     */
    +    record Update(@Nullable List<PolarisEntityCore> catalogPath, @NonNull PolarisBaseEntity entity)
    +        implements Write {}
    +  }
    +
    +  public ConditionalEntityWrite {
    +    conditions = List.copyOf(conditions);
    +    writes = List.copyOf(writes);
    +
    +    Set<EntityKey> entities = new HashSet<>();
    +    for (Write write : writes) {
    +      if (!(write instanceof Write.Update update)) {
    +        throw new IllegalArgumentException("Unsupported write " + write);
    +      }
    +      requireOnce(entities, update.entity());

    If a multi-table commit lists the same table twice, once with updates and once requirement-only, this throws IllegalArgumentException. Does the REST layer reject duplicate identifiers before this point? If not, I think the client sees a 500 instead of a 4xx. Could we add a test for it?

    flyrain flyrain commented on code on Nov 15, 2026 19:26 UTC
    Code Review
    polaris-core/src/main/java/org/apache/polaris/core/persistence/PolarisMetaStoreManager.java:1
    @@ -296,18 +298,63 @@ default BaseResult bootstrapPolarisService(@NonNull PolarisCallContext callCtx)
           @Nullable List<PolarisEntityCore> catalogPath,
           @NonNull PolarisBaseEntity entity);
     
    +  /**
    +   * Applies entity writes atomically, and only if all of the batch's conditions hold.
    +   *
    +   * <p>The result is the same as if the batch ran alone, at serializable isolation, whatever the
    +   * isolation level of the backend:
    +   *
    +   * <ul>
    +   *   <li>All-or-nothing: either every condition holds and every write is applied, or nothing is
    +   *       written.
    +   *   <li>{@link ConditionalEntityWrite.Condition.Unchanged}: the entity exists with the given
    +   *       entity version at the time the batch is applied. The entity is not written, so a
    +   *       concurrent batch that only checks the same entity does not conflict with this one.
    +   *   <li>{@link ConditionalEntityWrite.Write.Update}: has the semantics of {@link
    +   *       #updateEntityPropertiesIfNotChanged(PolarisCallContext, List, PolarisBaseEntity)}.
    +   * </ul>
    +   *
    +   * <p>A condition or write that fails, including one on an entity that no longer exists, gives
    +   * {@link BaseResult.ReturnStatus#TARGET_ENTITY_CONCURRENTLY_MODIFIED}, with the failing entity
    +   * when it is known. A concurrency failure of the backend, such as a deadlock or a serialization
    +   * failure, is reported the same way and is never thrown, so that callers can treat all of them as
    +   * a conflict to retry.
    +   *
    +   * <p>The {@code catalogPath} of the batch's members is carried but not validated. Each entity may
    +   * be the subject of at most one condition or write.
    +   *
    +   * <p>A backend may restrict which entities can be in one batch, and reject a batch it cannot
    +   * apply atomically with an {@link IllegalArgumentException}: the NoSQL backend requires all
    +   * entities of a batch to be of the same entity type and in the same catalog.
    +   *
    +   * @param callCtx call context
    +   * @param batch the conditions to check and the writes to apply
    +   * @return the written entities in the order of the batch's writes, or a failure
    +   */
    +  @NonNull ConditionalEntityWriteResult writeEntitiesIfConditionsHold(
    flyrain flyrain commented on code on Nov 15, 2026 19:34 UTC
    Code Review
    polaris-core/src/main/java/org/apache/polaris/core/persistence/dao/entity/ConditionalEntityWrite.java:1
    @@ -0,0 +1,137 @@
    +/*
    + * 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.polaris.core.persistence.dao.entity;
    +
    +import java.util.ArrayList;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Set;
    +import org.apache.polaris.core.entity.PolarisBaseEntity;
    +import org.apache.polaris.core.entity.PolarisEntityCore;
    +import org.jspecify.annotations.NonNull;
    +import org.jspecify.annotations.Nullable;
    +
    +/**
    + * Entity writes that are applied atomically, and only if all conditions hold. See {@code
    + * PolarisMetaStoreManager#writeEntitiesIfConditionsHold}.
    + *
    + * <p>Each entity may be the subject of at most one condition or write, so a conditional write can
    + * neither check and write the same entity (a write already compares the entity's versions) nor
    + * write it twice.
    + */
    +public record ConditionalEntityWrite(
    +    @NonNull List<Condition> conditions, @NonNull List<Write> writes) {
    +
    +  /**
    +   * A condition that must hold for the writes to be applied. Conditions are evaluated atomically
    +   * with the writes. Backends must handle every kind and must never ignore one.
    +   */
    +  public sealed interface Condition {
    +
    +    /**
    +     * The entity still exists, with the given entity version. The entity is only checked: it is not
    +     * written, and its version, last-update time and properties stay as they are.
    +     *
    +     * <p>Only {@link PolarisEntityCore#getEntityVersion()} is compared. A change of the grant
    +     * records version does not fail the condition, because it does not change the entity itself.
    +     *
    +     * @param catalogPath path to the entity's parent, null if the entity is top-level; carried but
    +     *     not validated
    +     * @param entity identity and expected version of the entity
    +     */
    +    record Unchanged(
    +        @Nullable List<PolarisEntityCore> catalogPath, @NonNull PolarisEntityCore entity)
    +        implements Condition {}
    +  }
    +
    +  /** A write, applied only if all conditions hold. Backends must handle every kind. */
    +  public sealed interface Write {
    +
    +    /**
    +     * Updates an entity, if it is still at the versions of {@code entity}: the entity version and
    +     * the grant records version. This has the same semantics as {@code
    +     * PolarisMetaStoreManager#updateEntityPropertiesIfNotChanged}.
    +     *
    +     * @param catalogPath path to the entity's parent, null if the entity is top-level; carried but
    +     *     not validated
    +     * @param entity the entity to write, at the versions it was read
    +     */
    +    record Update(@Nullable List<PolarisEntityCore> catalogPath, @NonNull PolarisBaseEntity entity)
    +        implements Write {}
    +  }
    +
    +  public ConditionalEntityWrite {
    +    conditions = List.copyOf(conditions);
    +    writes = List.copyOf(writes);
    +
    +    Set<EntityKey> entities = new HashSet<>();
    +    for (Write write : writes) {
    +      if (!(write instanceof Write.Update update)) {
    +        throw new IllegalArgumentException("Unsupported write " + write);
    +      }
    +      requireOnce(entities, update.entity());

    Agreed that it should be a 400 bad request in that case.

    qlong qlong commented on Nov 16, 2026 17:29 UTC
    Author

    I think this makes sense, checkEntityUnchanged goes through executeSelectOverStream(connection, …), and that overload still runs withRetries on the same connection.

    > We’re already inside runWithinTransaction here. If the SELECT hits 40001 (easy to see on Cockroach with max-retries>1, the docs example uses 3), the transaction is aborted, the retry gets something like 25P02 instead, and the 40001/40P01 mapping below never sees the original conflict. Caller ends up with a 500 instead of a concurrency failure / 409.

    > persistEntity’s execute(connection) path doesn’t retry, which is what we want inside a txn. Can we do the same for this select, skip the inner retry when we already own the connection?

    +1. Will remove retry within transaction.

    I left DatasourceOperations.executeSelectOverStream(connection, …) as it is to not extend the scope of this PR, will fix it in follow up.

    qlong qlong commented on code on Nov 16, 2026 17:31 UTC
    Code Review
    polaris-core/src/main/java/org/apache/polaris/core/persistence/AtomicOperationMetaStoreManager.java:1
    @@ -965,39 +967,43 @@ public void deletePrincipalSecrets(
     
       /** {@inheritDoc} */
       @Override
    -  public @NonNull EntitiesResult updateEntitiesPropertiesIfNotChanged(

    will do

    qlong qlong commented on code on Nov 16, 2026 17:44 UTC
    Code Review
    polaris-core/src/main/java/org/apache/polaris/core/persistence/dao/entity/ConditionalEntityWrite.java:1
    @@ -0,0 +1,137 @@
    +/*
    + * 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.polaris.core.persistence.dao.entity;
    +
    +import java.util.ArrayList;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Set;
    +import org.apache.polaris.core.entity.PolarisBaseEntity;
    +import org.apache.polaris.core.entity.PolarisEntityCore;
    +import org.jspecify.annotations.NonNull;
    +import org.jspecify.annotations.Nullable;
    +
    +/**
    + * Entity writes that are applied atomically, and only if all conditions hold. See {@code
    + * PolarisMetaStoreManager#writeEntitiesIfConditionsHold}.
    + *
    + * <p>Each entity may be the subject of at most one condition or write, so a conditional write can
    + * neither check and write the same entity (a write already compares the entity's versions) nor
    + * write it twice.
    + */
    +public record ConditionalEntityWrite(
    +    @NonNull List<Condition> conditions, @NonNull List<Write> writes) {
    +
    +  /**
    +   * A condition that must hold for the writes to be applied. Conditions are evaluated atomically
    +   * with the writes. Backends must handle every kind and must never ignore one.
    +   */
    +  public sealed interface Condition {
    +
    +    /**
    +     * The entity still exists, with the given entity version. The entity is only checked: it is not
    +     * written, and its version, last-update time and properties stay as they are.
    +     *
    +     * <p>Only {@link PolarisEntityCore#getEntityVersion()} is compared. A change of the grant
    +     * records version does not fail the condition, because it does not change the entity itself.
    +     *
    +     * @param catalogPath path to the entity's parent, null if the entity is top-level; carried but
    +     *     not validated
    +     * @param entity identity and expected version of the entity
    +     */
    +    record Unchanged(
    +        @Nullable List<PolarisEntityCore> catalogPath, @NonNull PolarisEntityCore entity)
    +        implements Condition {}
    +  }
    +
    +  /** A write, applied only if all conditions hold. Backends must handle every kind. */
    +  public sealed interface Write {
    +
    +    /**
    +     * Updates an entity, if it is still at the versions of {@code entity}: the entity version and
    +     * the grant records version. This has the same semantics as {@code
    +     * PolarisMetaStoreManager#updateEntityPropertiesIfNotChanged}.
    +     *
    +     * @param catalogPath path to the entity's parent, null if the entity is top-level; carried but
    +     *     not validated
    +     * @param entity the entity to write, at the versions it was read
    +     */
    +    record Update(@Nullable List<PolarisEntityCore> catalogPath, @NonNull PolarisBaseEntity entity)
    +        implements Write {}
    +  }
    +
    +  public ConditionalEntityWrite {
    +    conditions = List.copyOf(conditions);
    +    writes = List.copyOf(writes);
    +
    +    Set<EntityKey> entities = new HashSet<>();
    +    for (Write write : writes) {
    +      if (!(write instanceof Write.Update update)) {
    +        throw new IllegalArgumentException("Unsupported write " + write);

    Good point on error out at build time. polaris-core is jdk-17 so we cannot do exhaustive switch here. I will change jdbc / nosql backend to use switch for now

    qlong qlong commented on code on Nov 16, 2026 17:58 UTC
    Code Review
    polaris-core/src/main/java/org/apache/polaris/core/persistence/dao/entity/ConditionalEntityWrite.java:1
    @@ -0,0 +1,137 @@
    +/*
    + * 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.polaris.core.persistence.dao.entity;
    +
    +import java.util.ArrayList;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Set;
    +import org.apache.polaris.core.entity.PolarisBaseEntity;
    +import org.apache.polaris.core.entity.PolarisEntityCore;
    +import org.jspecify.annotations.NonNull;
    +import org.jspecify.annotations.Nullable;
    +
    +/**
    + * Entity writes that are applied atomically, and only if all conditions hold. See {@code
    + * PolarisMetaStoreManager#writeEntitiesIfConditionsHold}.
    + *
    + * <p>Each entity may be the subject of at most one condition or write, so a conditional write can
    + * neither check and write the same entity (a write already compares the entity's versions) nor
    + * write it twice.
    + */
    +public record ConditionalEntityWrite(
    +    @NonNull List<Condition> conditions, @NonNull List<Write> writes) {
    +
    +  /**
    +   * A condition that must hold for the writes to be applied. Conditions are evaluated atomically
    +   * with the writes. Backends must handle every kind and must never ignore one.
    +   */
    +  public sealed interface Condition {
    +
    +    /**
    +     * The entity still exists, with the given entity version. The entity is only checked: it is not
    +     * written, and its version, last-update time and properties stay as they are.
    +     *
    +     * <p>Only {@link PolarisEntityCore#getEntityVersion()} is compared. A change of the grant
    +     * records version does not fail the condition, because it does not change the entity itself.
    +     *
    +     * @param catalogPath path to the entity's parent, null if the entity is top-level; carried but
    +     *     not validated
    +     * @param entity identity and expected version of the entity
    +     */
    +    record Unchanged(
    +        @Nullable List<PolarisEntityCore> catalogPath, @NonNull PolarisEntityCore entity)
    +        implements Condition {}
    +  }
    +
    +  /** A write, applied only if all conditions hold. Backends must handle every kind. */
    +  public sealed interface Write {
    +
    +    /**
    +     * Updates an entity, if it is still at the versions of {@code entity}: the entity version and
    +     * the grant records version. This has the same semantics as {@code
    +     * PolarisMetaStoreManager#updateEntityPropertiesIfNotChanged}.
    +     *
    +     * @param catalogPath path to the entity's parent, null if the entity is top-level; carried but
    +     *     not validated
    +     * @param entity the entity to write, at the versions it was read
    +     */
    +    record Update(@Nullable List<PolarisEntityCore> catalogPath, @NonNull PolarisBaseEntity entity)
    +        implements Write {}
    +  }
    +
    +  public ConditionalEntityWrite {
    +    conditions = List.copyOf(conditions);
    +    writes = List.copyOf(writes);
    +
    +    Set<EntityKey> entities = new HashSet<>();
    +    for (Write write : writes) {
    +      if (!(write instanceof Write.Update update)) {
    +        throw new IllegalArgumentException("Unsupported write " + write);
    +      }
    +      requireOnce(entities, update.entity());

    commitTransaction group changes by table Id, so this probably won't happen but I think it is a good defensive coding to have. Will change to throw 400 if a condition write cannot be built

    adutra adutra commented on Nov 17, 2026 09:08 UTC
    Contributor

    Heads-up: #5967 has been merged, so CHANGELOG.md is no longer edited directly. Changelog entries now go in a fragment file under changelog.d/, which avoids merge conflicts on CHANGELOG.md. See changelog.d/README.md for the format.

    Could you rebase onto main, revert your changes to CHANGELOG.md, and add a fragment file instead if your change needs a changelog entry? A fragment is only needed for things worth calling out in release notes, such as breaking changes, metastore schema changes, or changes that require manual steps during an upgrade. Thanks!

    qlong qlong commented on Nov 19, 2026 01:48 UTC
    Author

    Heads-up: #5967 has been merged, so CHANGELOG.md is no longer edited directly. Changelog entries now go in a fragment file under changelog.d/, which avoids merge conflicts on CHANGELOG.md. See changelog.d/README.md for the format.

    > Could you rebase onto main, revert your changes to CHANGELOG.md, and add a fragment file instead if your change needs a changelog entry? A fragment is only needed for things worth calling out in release notes, such as breaking changes, metastore schema changes, or changes that require manual steps during an upgrade. Thanks!

    Added a fragment for SPI change.

    qlong qlong commented on Nov 23, 2026 21:10 UTC
    Author

    rebased to resolve conflict

    ShivanshhhG ShivanshhhG commented on Nov 30, 2026 04:20 UTC
    Contributor

    Reviewed the approach here—adding conditional entity writes (writeEntitiesIfConditionsHold with Condition.Unchanged) cleanly resolves the isolation gap on requirement-only tables in multi-table commits (#5807) without introducing false write contention or bumping entity versions. Closed #5820 in favor of this PR. Thanks @qlong and @flyrain!

    Reviewers
    Assignees
    qlong qlong
    Labels
    risk: low confidence: 89.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 78.5% (HIGH) · Higher = larger blast radius
    78.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 89.9% · Lower = rushed or shallow review
    89.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 8.0% · Safe to merge
    8.0%
    Repository