Skip to content

Return HTTP 503 on concurrent rename instead of 500 - #4646

Merged
dimas-b merged 1 commit into
apache:mainfrom
vigneshio:fix-rename-concurrent-conflict-409
Jul 23, 2026
Merged

dimas-b merged 1 commit into
apache:mainfrom
vigneshio:fix-rename-concurrent-conflict-409

Conversation

@vigneshio

@vigneshio vigneshio commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

When a concurrent modification occurs during renameTable/renameView, the
operation now returns HTTP 503 (Service Unavailable) instead of HTTP 500
(Internal Server Error), signalling a transient, retryable condition.

Why

renameTableLike in IcebergCatalog previously threw a bare RuntimeException
for both TARGET_ENTITY_CONCURRENTLY_MODIFIED and ENTITY_CANNOT_BE_RESOLVED.
IcebergExceptionMapper maps unknown RuntimeExceptions to 500, so clients
received an opaque server error instead of a retryable signal. The code even
admitted this was temporary: "this is temporary. Should throw a special error
that will be caught and retried"
.

Both statuses are documented in BaseResult.ReturnStatus as retryable
concurrency conditions ("the client should retry"), and the rename
implementation (TransactionalMetaStoreManagerImpl.renameEntityInCurrentTxn)
returns both on real races, so each branch is reachable in practice.

HTTP 409 is intentionally not used here: the Iceberg REST rename endpoint
reserves 409 for "the target identifier to rename to already exists" (which
Polaris already uses via the ENTITY_ALREADY_EXISTS case). Mapping a concurrent
modification to 409 would collide with that meaning, so a spec-compliant client
would surface it as AlreadyExistsException rather than retrying. The rename
endpoint lists 503 for the transient case, so this change uses 503 instead.
(Thanks to @nandorKollar for catching the 409 semantic mismatch in review.)

Changes

  • IcebergCatalog.renameTableLike: replaced the bare RuntimeException with
    ServiceUnavailableException (HTTP 503) for concurrent rename failures
    (TARGET_ENTITY_CONCURRENTLY_MODIFIED, ENTITY_CANNOT_BE_RESOLVED).
  • Added parameterized test testConcurrencyConflictRenameTable covering both
    statuses, verifying they surface as ServiceUnavailableException (503).
  • CHANGELOG.md: added a Fixes entry.

Known follow-up (out of scope)

The same renameTableLike switch still lacks a case for
CATALOG_PATH_CANNOT_BE_RESOLVED (cross-namespace renames where the destination
path can't be resolved). That falls through to default → IllegalStateException → 500, whereas updateTableLike handles it as NotFoundException (404). This
is a pre-existing gap not introduced by this change; tracking separately.

Testing

  • ./gradlew :polaris-runtime-service:compileTestJava — passes
  • ./gradlew :polaris-runtime-service:spotlessCheck :polaris-runtime-service:checkstyleMain :polaris-runtime-service:checkstyleTest — passes
  • ./gradlew :polaris-runtime-service:test --tests "org.apache.polaris.service.catalog.iceberg.IcebergCatalogRelationalTest.testConcurrencyConflictRenameTable" — passes (both parameterized cases)
  • ./gradlew :polaris-runtime-service:test --tests "org.apache.polaris.service.catalog.iceberg.IcebergCatalogRelationalTest.testConcurrencyConflictUpdateTableDuringFinalTransaction" — passes (regression check)

Checklist

  • 🛡️ Don't disclose security issues! (contact [email protected])
  • 🔗 Clearly explained why the changes are needed
  • 🧪 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)

@nandorKollar

Copy link
Copy Markdown
Contributor

Although this change makes sense for me, I think there's a disconnect between Iceberg spec, and our implementation. The spec for POST /v1/{prefix}/tables/rename and POST /v1/{prefix}/views/rename states that 409 return code is Conflict - The target identifier to rename to already exists as a table or view, which is not exactly the same as two conflicting transaction, is it?

@vigneshio
vigneshio force-pushed the fix-rename-concurrent-conflict-409 branch from a20a385 to d329502 Compare June 8, 2026 11:10
@vigneshio vigneshio changed the title Return HTTP 409 Conflict on concurrent rename instead of 500 Return HTTP 503 on concurrent rename instead of 500 Jun 8, 2026
@vigneshio

Copy link
Copy Markdown
Contributor Author

Thanks @nandorKollar , good catch.

The rename endpoints define 409 as "the target identifier to rename to already exists", and we already use 409 for that case (ENTITY_ALREADY_EXISTS → AlreadyExistsException). Mapping a concurrent-modification failure to 409 overloads that meaning, so a spec-compliant client would read it as "already exists" rather than a transient condition. (And my "consistency with updateTableLike" reasoning doesn't really apply, since 409 means a commit conflict on the update endpoint but "already exists" on rename.)

I've updated the PR to map the concurrency statuses (TARGET_ENTITY_CONCURRENTLY_MODIFIED, ENTITY_CANNOT_BE_RESOLVED) to 503 ServiceUnavailable, which the rename spec lists for the transient case, keeping 409 strictly for "already exists".

(If Team prefer server-side retry for rename as the original TODO - that'd be a larger change; happy to do it as a follow-up.)

@nandorKollar

Copy link
Copy Markdown
Contributor

Thanks @nandorKollar , good catch.

The rename endpoints define 409 as "the target identifier to rename to already exists", and we already use 409 for that case (ENTITY_ALREADY_EXISTS → AlreadyExistsException). Mapping a concurrent-modification failure to 409 overloads that meaning, so a spec-compliant client would read it as "already exists" rather than a transient condition. (And my "consistency with updateTableLike" reasoning doesn't really apply, since 409 means a commit conflict on the update endpoint but "already exists" on rename.)

I've updated the PR to map the concurrency statuses (TARGET_ENTITY_CONCURRENTLY_MODIFIED, ENTITY_CANNOT_BE_RESOLVED) to 503 ServiceUnavailable, which the rename spec lists for the transient case, keeping 409 strictly for "already exists".

(If Team prefer server-side retry for rename as the original TODO - that'd be a larger change; happy to do it as a follow-up.)

Thanks, 503 sounds better, but still not the best response code IMHO. I think it is intended to indicate the client to slow down. It seems to me, that Iceberg spec doesn't have a clear response code for rename operations, which indicate that there was a conflict, the client should retry the operation.

@nandorKollar

Copy link
Copy Markdown
Contributor

@vigneshio

Copy link
Copy Markdown
Contributor Author

Opened a discussion on the dev list: https://lists.apache.org/thread/tr8zh8121t2jb41s0q2yd9s73y2tp2tq

I'll hold off finalizing until the dev list discussion wraps up, then update this - splitting ENTITY_CANNOT_BE_RESOLVED to 404 and aligning the rest with whatever we decide. Thanks for taking it to the list.

@nandorKollar

Copy link
Copy Markdown
Contributor

@vigneshio it seems there is a consensus on the mailing list that 503 is the best choice among the available options for signaling a conflict error. We should probably open a follow-up issue to implement server-side retries for conflicting rename operations. However, ENTITY_CANNOT_BE_RESOLVED should return a 404 instead. cc. @flyrain @adutra @dimas-b @rmannibucau

@rmannibucau

Copy link
Copy Markdown
Contributor

I'll just write it for the record since you kind of converge but I still think this lead to a wrong behavior on the client side:

  • 503 is used to notify the client the server is down or overloaded, this means this is cacheable per client/application (understand not per entity) on the client side, this is totally wrong there
  • 429 has some underlying semantic of retries (using headers or a default - often an exp backoff)
  • I understand the issue you point with 409 but from a client perspective it is not an issue at all IMHO
  • 412 can be a work around breaking less the client and gateways IMHO if really an issue (but think iceberg can be pinged to refine the 409, there is no valid reason it is not used there)

Another thing to consider I think is that if the management of the mutations is implemented as a queue internally (potentially distributed but let's stick to the design) then you never have this ambiguity and plain iceberg status are fine (409, 404 mainly there), so maybe the question is not which status but more how to implement it right - think polaris can just delay the response to the previous execution "end" somehow.

The overall concern is using a semantic the client and gateways/proxies know and associate it another meaning leading to a wrong behavior (the 503 global cache - think circuit breakers - is a good example of that).

@vigneshio

vigneshio commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @dimas-b @nandorKollar @adutra . Based on the discussion on the dev list, I've updated the PR:

  • TARGET_ENTITY_CONCURRENTLY_MODIFIED → 503 (temporary error, can be retried)
  • ENTITY_CANNOT_BE_RESOLVED and CATALOG_PATH_CANNOT_BE_RESOLVED → 404 NoSuchNamespaceException, grouped together as suggested by @adutra.

I have also opened follow-up issue #4729 for server-side retries on rename conflicts. I agree with @rmannibucau that server-side retry is the better long-term solution, and that work can be handled separately.

@vigneshio
vigneshio force-pushed the fix-rename-concurrent-conflict-409 branch from 15da8eb to 51bea3d Compare June 12, 2026 14:26
adutra
adutra previously approved these changes Jun 12, 2026

@adutra adutra 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 @vigneshio for this PR!

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

dimas-b commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

Re: 412 - I think it is closely related to If-Unmodified-Since / If-Match in the request headers, so I'm not sure it's a perfect match for this case either 🤷

dimas-b
dimas-b previously approved these changes Jun 12, 2026
@rmannibucau

Copy link
Copy Markdown
Contributor

@dimas-b agree but 412 doesnt have the semantic issues of 503 and 429 in middleware (it is poorly used today AFAIK) so "least worse" from my window ;) - the real issue is trying to use a spec for assets for an API, this always had been wrong by design and this is where *RPC style solutions are way more relevant - hopefully iceberg get a JSON-RPC catalog a day ;)

@dimas-b

dimas-b commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

None of the options are ideal 😅 We're effectively trying to work around an IRC spec problem, while allowing reasonable clients to recover from this kind of failure without having to make any Polaris-specific assumptions.

As I commented on dev, from my POV 503 is the easiest to handle on the client side because it does not carry any implications about the state of the catalog. The server merely could not handle the request (from the client perspective).

With 503, the RFC is pretty lenient towards servers. I do not think clients can assume any service-wide outage on receiving a 503 response from one particular request.

As Polaris will not provide a Retry-After response header in this case, the client is free to retry at any time.

nandorKollar
nandorKollar previously approved these changes Jun 12, 2026
@rmannibucau

Copy link
Copy Markdown
Contributor

The 503 (Service Unavailable) status code indicates that the server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay.

So - as 504 is - is literally global/for the server so often resilience4j, mp fault tolérance and friends use an impl opening the circuit breaker after a few occurrences - and it is not insane and is quite common on load balancers as behavior.

@vigneshio
vigneshio dismissed stale reviews from dimas-b and adutra via cc19caf June 16, 2026 16:42
@vigneshio
vigneshio force-pushed the fix-rename-concurrent-conflict-409 branch from 51bea3d to cc19caf Compare June 16, 2026 16:42
dimas-b
dimas-b previously approved these changes Jun 16, 2026
@vigneshio
vigneshio force-pushed the fix-rename-concurrent-conflict-409 branch from cc19caf to a931554 Compare June 16, 2026 18:15
@dimas-b

dimas-b commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

@vigneshio : Did you rebase? Zizmor CI errors usually mean the PR is behind the "approved" set of GH actions 🤔

@vigneshio

Copy link
Copy Markdown
Contributor Author

@vigneshio : Did you rebase? Zizmor CI errors usually mean the PR is behind the "approved" set of GH actions 🤔

Yes, I rebased onto latest main. The conflict is resolved. The Zizmor failure appears to be from pre-existing workflow-file warnings, not from this PR changes. Could you please confirm? @dimas-b

@vigneshio
vigneshio force-pushed the fix-rename-concurrent-conflict-409 branch from a931554 to 955a8ea Compare June 16, 2026 20:52
@dimas-b

dimas-b commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

The zizmor problem should be fixed by #4797.

Please fix another conflict with CHANGELOG.md 😅

@vigneshio
vigneshio force-pushed the fix-rename-concurrent-conflict-409 branch from 955a8ea to 908b6fa Compare June 16, 2026 22:25
dimas-b
dimas-b previously approved these changes Jun 16, 2026
Concurrent modification during renameTable/renameView now returns 503 (retriable transient conflict) instead of a bare 500. Source/target paths that cannot be resolved (ENTITY_CANNOT_BE_RESOLVED, CATALOG_PATH_CANNOT_BE_RESOLVED) now return 404 NoSuchNamespaceException rather than 500, since a concurrently dropped path is not retriable.
@vigneshio
vigneshio force-pushed the fix-rename-concurrent-conflict-409 branch from 908b6fa to a78a23b Compare June 17, 2026 17:31
@dimas-b

dimas-b commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

@dimas-b
dimas-b merged commit e8ea9bc into apache:main Jul 23, 2026
24 checks passed
@github-project-automation github-project-automation Bot moved this from Ready to merge to Done in Basic Kanban Board Jul 23, 2026
@nandorKollar

Copy link
Copy Markdown
Contributor

Vote results (success): https://lists.apache.org/thread/5borfwcw6d54r2z4zf3y7s1nz9jqzz6f

@dimas-b I think there's still a missing piece from this PR: Retry-After header. According to my understanding that's an important piece to signal retry to the client, shouldn't we also add this header?

@dimas-b

dimas-b commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

@nandorKollar : good point about Retry-After - I totally forgot 🤦 I'll make a PR for this presently.

@nandorKollar

Copy link
Copy Markdown
Contributor

@nandorKollar : good point about Retry-After - I totally forgot 🤦 I'll make a PR for this presently.

I quickly put together a change. However, I could only find a way to set Retry-After globally for all ServiceUnavailableExceptions (in IcebergExceptionMapper). I'm not sure how to cleanly restrict it to this particular endpoint. Should I open a PR for that?

@nandorKollar

Copy link
Copy Markdown
Contributor

@nandorKollar : good point about Retry-After - I totally forgot 🤦 I'll make a PR for this presently.

I quickly put together a change. However, I could only find a way to set Retry-After globally for all ServiceUnavailableExceptions (in IcebergExceptionMapper). I'm not sure how to cleanly restrict it to this particular endpoint. Should I open a PR for that?

We can maybe extend Iceberg's ServiceUnavailableException with an extra retryAfter property, maybe that could be an option?

@dimas-b

dimas-b commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Follow-up PR: #5144

yili-db pushed a commit to unitycatalog/unitycatalog that referenced this pull request Oct 24, 2026
## 🥞 Stacked PR
Use this
[link](https://github.com/unitycatalog/unitycatalog/pull/2008/files) to
review incremental changes.
-
[**stack/uc-one-suite**](#2008)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2008/files)]
← _this PR_
-
[stack/uc-one-suite-ci](#2009)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2009/files/ac4a580b797df2634ebe449d60bb5308ed0dc32f..2b724ef4188544b5a6ec18cce0f18f174e62a94b)]

---------
**PR Checklist**

- [x] A description of the changes is added to the description of this
PR.
- [ ] If there is a related issue, make sure it is linked to this PR.
- [x] If you've fixed a bug or added code that should be tested, add
tests!
- [ ] If you've added or modified a feature, documentation in `docs` is
updated

**Description of changes**

**Every test can now run on PostgreSQL 18, not just H2.**
`UC_TEST_DATABASE=POSTGRES_18 build/sbt test`, or `build/sbt
testPostgres18`, runs the server, cli, spark and hadoop tests on
`postgres:18-alpine` (it needs Docker, fails rather than skips without
it, and needs `-J-Xmx6G`). Without the variable, tests run on H2 as
before, with no Docker needed. Each test gets a fresh database, and a
schema statement that fails now fails the test instead of logging a
warning. Exceptions: `MySQLDeltaCommitsCRUDTest` runs on its own MySQL
container; `HibernateConfiguratorTest` and `PopulateTestDatabase` build
their own database; `UserRepositoryTest` and
`TransactionManagerTest.IsolationLevelWithRealDatabaseTest` share one
database per class.

Running the suite on PostgreSQL found three bugs in how writers of a
table take its lock. This PR fixes them:

- **Concurrent Iceberg commits on PostgreSQL returned 500 instead of
409.** A commit read the table before it held the lock.
`lockTableForCommit` now locks the row first, then re-reads it.
- **Dropping a table during a commit could deadlock, or fail the commit
with 500.** `deleteTable` now takes the same lock. A commit whose table
was dropped while it waited returns 404. A drop that times out waiting
for the lock returns 503 (`UNAVAILABLE`) on every API, with a new Delta
error type `ServiceUnavailableException`. The Iceberg REST spec lists
503 for drop table, and both the Iceberg and UC clients retry it.
- **Lock failures from the new lock query returned 500.** The query
reports them as JPA exceptions, and a deadlock arrives as
`OptimisticLockException`. They now map to the caller's error code (409
for Iceberg, `COMMIT_STATE_UNKNOWN` for Delta, `UNAVAILABLE` (503) for a
drop).

Everything else is test code and `build.sbt`. #2009 runs the PostgreSQL
suite in CI.

**Tests**

- Full suite on H2: 0 failures. #2009's CI runs the full suite on
PostgreSQL 18.
-
`IcebergRestCatalogTest.testConcurrentCommitsSerializeWithCompareAndSwap`
failed 3 of 3 runs on PostgreSQL before the fix.
- `ManagedTableCleanupTaskTest.dropBlockedByCommitLockIsUnavailable` and
`forceSchemaDeleteBlockedByCommitLockDeletesNothing` (new): the lock
holder replaces the table's columns, as a commit does, so a drop that
deleted columns before taking the lock fails them on both databases. The
drop test also checks what clients get: 503 on UC REST, and
`ServiceUnavailableException` (503) on the Iceberg and Delta APIs.
-
`ManagedTableCleanupTaskTest.commitOnATableDroppedAfterItWasReadIsNotFound`
(new): a commit on a table dropped after it was read gets
`TABLE_NOT_FOUND`, on the real database.
-
`MySQLDeltaCommitsCRUDTest.testCommitThatWaitedForTheLockReadsTheOtherCommit`
(new): fails on MySQL with a plain re-read after the lock (it sees the
old metadata location), passes with the locking re-read.
- `RepositoryUtilsTest` builds its lock failures with Hibernate's own
exception converter. Against the old catch, its deadlock case fails.

<details>
<summary>🔒 Commit races: what failed and why</summary>

**Race 1: a commit read the table before it held the lock (PostgreSQL
only).** The lock was `session.refresh(dao, PESSIMISTIC_WRITE)`. A
refresh also loads the table's columns with a `LEFT JOIN`, and
`PostgreSQLDialect.supportsOuterJoinForUpdate()` is `false`, so
Hibernate reads first and locks in separate statements afterwards
(warning `HHH000444`). H2 locks the join in one statement.

```
     commit A                               commit B
t1   read: location v1
t2   lock ✓                                 read: location v1   (stale soon)
t3   check v1 ✓; replace columns; set v2    lock … waits for A
t4   commit → 200                           lock ✓
t5                                          check v1 ✓  (should have seen v2 → 409)
t6                                          delete old columns → 0 rows → 500
```

Fix: lock with `from TableInfoDAO where id = :id` (no join; PostgreSQL
runs `for no key update`), then re-read it with `refresh(dao,
PESSIMISTIC_WRITE)`. The re-read sees A's commit, so B gets 409. It
stays a locking read because on MySQL's default REPEATABLE READ a plain
read returns the transaction's first snapshot, from before A's commit.

**Race 2: a drop deleted column rows without the lock (PostgreSQL and
H2).** The three commit paths take the table lock, but `deleteTable` did
not:

```
     commit C (holds the table lock)        drop D (no lock)
t1   lock ✓; read columns
t2                                          delete columns
t3                                          delete table → waits for C
t4   delete columns → waits for D           → deadlock; one request gets 500
```

Fix: `deleteTable` takes the same lock first. A drop that can't get it
within the lock timeout returns `UNAVAILABLE` (503). Not 409: the
Iceberg REST spec lists 503, not 409, for drop table, and the Iceberg
client maps a 409 on drop to `AlreadyExistsException` and does not retry
it. Apache Polaris returns 503 for the same reason
([apache/polaris#4646](apache/polaris#4646)).
The Delta API gets a new `ServiceUnavailableException` (503) error type
for it, listed on the Delta `deleteTable` in `api/delta.yaml` and in the
protocol spec, so all three APIs answer 503.

**Lock exceptions.** The new lock query passes Hibernate's lock
exception through its exception converter: a lock-wait failure or
timeout becomes `PessimisticLockException` or `LockTimeoutException`,
and a deadlock becomes `OptimisticLockException`, each wrapping
Hibernate's exception. `lockTableForCommit` checks the exception and its
cause.

</details>

<details>
<summary>📐 Design notes & details</summary>

- **A template database per test**, not one schema emptied between
tests. Every test still starts on an empty database, and background
threads from the previous test can't write into it, because its database
is dropped (`WITH (FORCE)`). On PostgreSQL 18 a copy takes about 46 ms
and a drop 55 ms.
- **`halt_on_error`** is safe on H2 and PostgreSQL, where nothing
harmless fails on a fresh database. MySQL's drop step does fail
harmlessly (no `DROP FOREIGN KEY IF EXISTS`), so only the MySQL classes
set `halt_on_error=false`, themselves. MySQL isn't a selectable database
yet.
- **`PostgresDeltaCommitsCRUDTest`** stays here so CI keeps PostgreSQL
coverage; #2009 removes it.
- **Local runs:** `testPostgres18` sets `Test / envVars` for the sbt
session, so in an interactive shell a later `test` keeps using
PostgreSQL until `reload`. The full run needs `-J-Xmx6G`.

</details>

This pull request and its description were written by Isaac.

---------

Signed-off-by: Shubham Bansal <[email protected]>
Co-authored-by: Isaac <[email protected]>
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