Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
aacd60a
[Server] Add SupportedDatabase, the list of test databases
shba24 Oct 16, 2026
97795eb
[Server] Reject an unknown UC_TEST_DATABASE before tests run
shba24 Oct 16, 2026
c402e04
[Server] Check every test SessionFactory connects to the selected dat…
shba24 Oct 16, 2026
ba11274
[Server] Add TestDatabases, a fresh database per test
shba24 Oct 16, 2026
0d6e8e4
[Server] Run each BaseServerTest on its own test database
shba24 Oct 16, 2026
18ef72f
[Server] Give each test a PostgreSQL database copied from a template
shba24 Oct 16, 2026
e9e937f
[Server] Run every server test on the selected database
shba24 Oct 16, 2026
8521c85
[Build] Add testPostgres18 to run all tests on PostgreSQL 18
shba24 Oct 16, 2026
4b0082c
[Spark][Hadoop] Run connector tests on the selected test database
shba24 Oct 16, 2026
5e43f64
[Server] Close each test's configurator with its database; keep the f…
shba24 Oct 16, 2026
15b6f14
[Build] Keep the test-database service files out of the client's test…
shba24 Oct 16, 2026
ea7c275
[Server] Harden test-database cleanup and selection after review
shba24 Oct 16, 2026
7382a3e
[Server] Lock the table row before reading it in commits
shba24 Oct 16, 2026
1d15761
[Server] Test that an unknown UC_TEST_DATABASE stops the test run
shba24 Oct 16, 2026
562206f
[Server] Move the lock-order note out of a @param description
shba24 Oct 16, 2026
f607727
[Server] Make table deletion wait for an in-flight commit
shba24 Oct 16, 2026
0b5139f
[Build] Share the Testcontainers version across test dependencies
shba24 Oct 16, 2026
990949b
[Server] Remove the tests of the test-database harness
shba24 Oct 17, 2026
8a4615b
[Server] Drop the test-database checks and pin PostgreSQL by tag
shba24 Oct 17, 2026
1ba0533
[Server] Drop configurator fields that only fed getSessionFactory()
shba24 Oct 17, 2026
476ea5c
[Server] Make the drop-vs-commit test deterministic and remove duplic…
shba24 Oct 17, 2026
8c0090d
[Server] Test the drop's table lock without threads; map JPA lock exc…
shba24 Oct 17, 2026
93357f7
[Server] Correct the lock-exception comment: only the lock query wraps
shba24 Oct 17, 2026
fcdc357
[Server] Map a deadlock on the table lock to the caller's error code
shba24 Oct 19, 2026
203c257
[Server] Read the locked table row with a locking read
shba24 Oct 20, 2026
0fe64e6
[Server] Return 503 for a drop that times out waiting for the table lock
shba24 Oct 20, 2026
8f58069
[Server] Test on MySQL that a commit that waited for the lock reads t…
shba24 Oct 20, 2026
e06bfeb
[Server] Let each test database start empty without cleanup queries
shba24 Oct 20, 2026
adfdd60
[API] List 429 for a Delta table drop that times out waiting for the …
shba24 Oct 20, 2026
b2797dc
[API] Shorten the 429 description on Delta deleteTable
shba24 Oct 20, 2026
7089636
[Server] Fold the new lock tests into existing test classes
shba24 Oct 20, 2026
a0b5b7e
[Server] Drop the mock not-found lock test; check the name on the rea…
shba24 Oct 22, 2026
85ade1d
[Server] Check the UC REST response for a drop blocked by the table lock
shba24 Oct 22, 2026
673b486
[Build] Use the server's PostgreSQL driver version in the test-databa…
shba24 Oct 22, 2026
6532321
[API] Return 503 on the Delta API for a drop that times out on the ta…
shba24 Oct 23, 2026
ac4a580
[API] List the Delta 503 error after the 500 one in the spec
shba24 Oct 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ Conventions:

- **Read paths pass `readOnly = true`; write paths pass `false`.** A path that needs a specific isolation level passes it explicitly; `TransactionManager` saves and restores the connection's isolation so it does not pollute the pooled connection.
- **DAOs extend `IdentifiableDAO`** (UUID id plus name), are annotated `@Entity @Table(name = "uc_...")`, use Lombok (`@Getter @Setter @SuperBuilder @NoArgsConstructor @AllArgsConstructor`), and expose static `from(XInfo)` and instance `toXInfo()` converters. Keep business logic out of DAOs.
- **Backends:** H2 by default (embedded, file-based). MySQL and PostgreSQL are supported for a persistent deployment, configured in `etc/conf/hibernate.properties` (point at your database and add the JDBC driver); see `docs/server/deployment.md`. Hibernate is configured in `persist/utils/HibernateConfigurator`, and tests exercise MySQL and PostgreSQL via Testcontainers. When adding schema, keep any index or column change safe across a server restart on an existing database, and portable across all three backends.
- **Backends:** H2 by default (embedded, file-based). MySQL and PostgreSQL are supported for a persistent deployment, configured in `etc/conf/hibernate.properties` (point at your database and add the JDBC driver); see `docs/server/deployment.md`. Hibernate is configured in `persist/utils/HibernateConfigurator`. Tests run on H2 by default; `build/sbt -J-Xmx6G testPostgres18` (or `UC_TEST_DATABASE=POSTGRES_18`) runs them on PostgreSQL 18 in Docker, each test on its own database, and fails rather than skips when Docker is not available. `MySQLDeltaCommitsCRUDTest` starts its own MySQL container via Testcontainers. When adding schema, keep any index or column change safe across a server restart on an existing database, and portable across all three backends.
- **Enforce invariants at the database level** (unique constraints) rather than only in code, where duplicate creation or races are possible.

## Error handling
Expand Down
4 changes: 4 additions & 0 deletions api/delta.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,8 @@ paths:
$ref: '#/components/responses/ForbiddenResponse'
'404':
$ref: '#/components/responses/NotFoundResponse'
'503':
$ref: '#/components/responses/ServiceUnavailableResponse'
head:
tags:
- DeltaTables
Expand Down Expand Up @@ -1548,6 +1550,7 @@ components:
- CommitStateUnknownException
- InternalServerErrorException
- NotImplementedException
- ServiceUnavailableException
# Keep enum order aligned with x-enum-descriptions below
x-enum-descriptions:
- 'BadRequestException: (400) Malformed request or invalid action.'
Expand All @@ -1567,6 +1570,7 @@ components:
- 'CommitStateUnknownException: (500) Commit outcome unknown (e.g., network failure after the server received the request). The client should check the table state before retrying.'
- 'InternalServerErrorException: (500) A server-side problem that might not be addressable from the client side.'
- 'NotImplementedException: (501) The requested functionality is not supported by the server.'
- 'ServiceUnavailableException: (503) The server is temporarily unable to serve the request. The client may retry after a delay.'

DeltaErrorModel:
type: object
Expand Down
19 changes: 17 additions & 2 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -484,15 +484,14 @@ lazy val server = (project in file("server"))
"javax.xml.bind" % "jaxb-api" % "2.3.1" % Test,

// Integration testing
"org.testcontainers" % "testcontainers" % testcontainersVersion % Test,
"org.testcontainers" % "postgresql" % testcontainersVersion % Test,
"org.testcontainers" % "mysql" % testcontainersVersion % Test,
"org.testcontainers" % "junit-jupiter" % testcontainersVersion % Test,
"com.mysql" % "mysql-connector-j" % "8.4.0" % Test,

// CLI dependencies
"commons-cli" % "commons-cli" % "1.7.0"
),
libraryDependencies ++= testDatabaseDependencies,
// Iceberg 1.11.0 brings its own Jackson version that conflicts with the project's pinned jackson version.
// Force AWS SDK v2 onto a single release as well (Iceberg and Hadoop otherwise mix 2.24 / 2.27).
dependencyOverrides ++= Seq(
Expand Down Expand Up @@ -660,6 +659,14 @@ lazy val cli = (project in file("examples") / "cli")
Test / javaOptions += s"-Duser.dir=${(ThisBuild / baseDirectory).value.getAbsolutePath}",
)

// What the test-database harness needs to run on PostgreSQL: server, and spark and hadoop, which take
// the harness from server-shaded.
lazy val testDatabaseDependencies = Seq(
"org.testcontainers" % "testcontainers" % testcontainersVersion % Test,
"org.testcontainers" % "postgresql" % testcontainersVersion % Test,
"org.postgresql" % "postgresql" % postgresqlVersion % Test,
)

/*
* This project is a combination of the server and client projects, shaded into a single JAR.
* It also includes the test classes from the server project.
Expand Down Expand Up @@ -770,6 +777,7 @@ lazy val spark = (project in file("connectors/spark"))
"org.antlr" % "antlr4" % "4.13.1",
),
Test / unmanagedJars += (serverShaded / assembly).value,
libraryDependencies ++= testDatabaseDependencies,
// netty-codec-native-quic uses ${packaging.type} in its POM which Ivy (used by sbt-license-report) cannot resolve.
// Exclude it so Ivy never attempts to fetch it; Coursier (used for normal builds) handles it fine.
excludeDependencies += ExclusionRule("io.netty", "netty-codec-native-quic"),
Expand Down Expand Up @@ -826,6 +834,7 @@ lazy val hadoop = (project in file("connectors/hadoop"))
"com.google.cloud.bigdataoss" % "gcs-connector" % "3.0.2" % Test classifier "shaded",
),
Test / unmanagedJars += (serverShaded / assembly).value,
libraryDependencies ++= testDatabaseDependencies,
)

lazy val integrationTests = (project in file("integration-tests"))
Expand Down Expand Up @@ -883,3 +892,9 @@ def generateClasspathFile(targetDir: File, classpath: Classpath): Unit = {
}

val generate = taskKey[Unit]("generate code from APIs")

// Runs every project's tests on one test database. One alias per SupportedDatabase constant except
// H2 (the default).
def testOnDatabase(database: String): String =
s"""; set every Test / envVars := Map("UC_TEST_DATABASE" -> "$database") ; test"""
addCommandAlias("testPostgres18", testOnDatabase("POSTGRES_18"))
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ public enum ErrorCode {
OUT_OF_RANGE(11, 400, DeltaErrorType.BAD_REQUEST_EXCEPTION),
UNIMPLEMENTED(12, 501, DeltaErrorType.NOT_IMPLEMENTED_EXCEPTION),
INTERNAL(13, 500, DeltaErrorType.INTERNAL_SERVER_ERROR_EXCEPTION),
// Temporarily unable to serve the request, which the client can retry, e.g. a table drop that
// timed out waiting for the table lock.
UNAVAILABLE(14, 503, DeltaErrorType.SERVICE_UNAVAILABLE_EXCEPTION),
DATA_LOSS(15, 500, DeltaErrorType.INTERNAL_SERVER_ERROR_EXCEPTION),
// UC-specific "already exists" error codes for backwards compatibility (all HTTP 400). But new
// Delta API returns 409 as it has no backwards compatibility concern.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import org.apache.iceberg.exceptions.NotFoundException;
import org.apache.iceberg.exceptions.RESTException;
import org.apache.iceberg.exceptions.ServiceFailureException;
import org.apache.iceberg.exceptions.ServiceUnavailableException;
import org.apache.iceberg.exceptions.UnprocessableEntityException;
import org.apache.iceberg.rest.responses.ErrorResponse;

Expand Down Expand Up @@ -103,6 +104,7 @@ private static Class<? extends Exception> icebergExceptionFor(ErrorCode errorCod
// COMMIT_STATE_UNKNOWN is intentionally mapped to ServiceFailureException as it's the Delta's
// semantic, not the Iceberg CommitStateUnknownException.
case INTERNAL, DATA_LOSS, COMMIT_STATE_UNKNOWN -> ServiceFailureException.class;
case UNAVAILABLE -> ServiceUnavailableException.class;
case RESOURCE_EXHAUSTED -> RESTException.class;
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1223,6 +1223,10 @@ TableInfoDAO deleteTable(Session session, UUID schemaId, String tableName) {
if (tableInfoDAO == null) {
throw new BaseException(ErrorCode.TABLE_NOT_FOUND, "Table not found: " + tableName);
}
// A commit rewrites the table's columns under this lock; waiting for it keeps the cascade below
// from deleting column rows the commit is replacing.
RepositoryUtils.lockTableForCommit(
session, tableInfoDAO, tableInfoDAO.getId(), Optional.of(tableName), ErrorCode.UNAVAILABLE);
if (TableType.MANAGED.getValue().equals(tableInfoDAO.getType())) {
repositories
.getStorageCleanupTaskRepository()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,11 @@ public class RepositoryUtils {
private static final Map<String, Class<?>> PROPERTY_TYPE_MAP = new HashMap<>();

/**
* Acquires the table row lock shared by the Delta and Iceberg commit paths, so concurrent commits
* on the same table serialize. A lock-wait timeout or deadlock victim is reported as {@code
* lockContentionError} (rolling back only this transaction) rather than leaking the ORM
* exception; the two commit paths pass different codes because the safe client reaction differs:
* Acquires the table row lock shared by the Delta and Iceberg commit paths and by table deletion,
* so concurrent commits on the same table serialize, and a deletion waits for them. A lock-wait
* timeout or deadlock victim is reported as {@code lockContentionError} (rolling back only this
* transaction) rather than leaking the ORM exception; each caller passes the code whose client
* reaction is safe for it:
*
* <ul>
* <li><b>Delta</b> passes {@code COMMIT_STATE_UNKNOWN} (500). Failing to acquire the lock does
Expand All @@ -47,10 +48,21 @@ public class RepositoryUtils {
* therefore safe and lets the Iceberg client retry transparently, whereas a 500 would
* surface to the user. Iceberg has no server-side deduplication that a resend could
* exploit.
* <li><b>Table deletion</b> passes {@code UNAVAILABLE} (503): the table was not deleted, and
* the request can be retried. The Iceberg REST spec lists 503, not 409, for drop table, and
* the Iceberg client reads a 409 on drop as "already exists".
* </ul>
*
* @param session the Hibernate session running the commit transaction
* @param dao the table row to lock; refreshed under {@code PESSIMISTIC_WRITE}
* <p>The row is locked first and read second. Refreshing the entity under the lock would load its
* columns with an outer join, and on PostgreSQL Hibernate locks such a query in a separate
* statement after the read, so a commit that waited for the lock would continue on the state it
* read before the other commit landed. The re-read is a locking read as well: on MySQL's default
* REPEATABLE READ, a plain read returns the snapshot the transaction took at its first read,
* which can be from before the other commit. A table deleted while this waited for the lock is
* reported as {@link ErrorCode#TABLE_NOT_FOUND}.
*
* @param session the Hibernate session running the commit or deletion transaction
* @param dao the table row to lock; re-read after the lock is held
* @param tableId the table id, used as a fallback in the error message
* @param tableFullNameForLogging the table's full name for the error message, if known
* @param lockContentionError the error code to raise when the lock cannot be acquired
Expand All @@ -61,22 +73,42 @@ public static void lockTableForCommit(
UUID tableId,
Optional<String> tableFullNameForLogging,
ErrorCode lockContentionError) {
String tableName = tableFullNameForLogging.orElseGet(tableId::toString);
try {
TableInfoDAO locked =
session
.createSelectionQuery("from TableInfoDAO where id = :id", TableInfoDAO.class)
.setParameter("id", dao.getId())
.setHibernateLockMode(LockMode.PESSIMISTIC_WRITE)
.getSingleResultOrNull();
if (locked == null) {
throw new BaseException(ErrorCode.TABLE_NOT_FOUND, "Table not found: " + tableName);
}
session.refresh(dao, LockMode.PESSIMISTIC_WRITE);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Fix looks good. You mentioned the two-session MySQL test reproduced it (m0 before, m1 after) but isn't in the PR because the suite runs on H2 and PostgreSQL only. MySQLDeltaCommitsCRUDTest already starts a MySQL container via Testcontainers and runs in CI, so could the repro go in as a small MySQL-only class following that pattern? This regression is invisible on H2 and PostgreSQL, so without it a later refactor of this method can bring it back silently.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added in 10cbce9 as MySQLTableLockTest, following MySQLDeltaCommitsCRUDTest. It first asserts the connection is at REPEATABLE READ, so it can't pass without testing anything. It fails with a plain refresh (the commit sees the old m0) and passes with the locking one. It's single-threaded with a fixed order, and passed 5 runs in a row.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Update: in 48109fa this moved into the existing MySQLDeltaCommitsCRUDTest, as testCommitThatWaitedForTheLockReadsTheOtherCommit, and MySQLTableLockTest is gone.

} catch (RuntimeException e) {
if (!(e instanceof org.hibernate.PessimisticLockException)
&& !(e instanceof org.hibernate.exception.LockAcquisitionException)
&& !(e instanceof org.hibernate.exception.LockTimeoutException)) {
// The lock query wraps Hibernate's lock exception in a JPA one, so check the cause as well.
// A deadlock victim arrives as OptimisticLockException wrapping LockAcquisitionException.
if (!isLockFailure(e) && !isLockFailure(e.getCause())) {
throw e;
}
throw new BaseException(
lockContentionError,
"Concurrent commit in progress on table "
+ tableFullNameForLogging.orElseGet(tableId::toString)
+ "; retry the request.");
"Concurrent modification in progress on table " + tableName + "; retry the request.");
}
}

/**
* Whether {@code failure} reports that a lock was not acquired: a lock-wait failure, a lock
* timeout, or a deadlock victim. {@code LockTimeoutException} is a {@code
* LockAcquisitionException}.
*/
private static boolean isLockFailure(Throwable failure) {
return failure instanceof jakarta.persistence.PessimisticLockException
|| failure instanceof jakarta.persistence.LockTimeoutException
|| failure instanceof org.hibernate.PessimisticLockException
|| failure instanceof org.hibernate.exception.LockAcquisitionException;
}

static {
PROPERTY_TYPE_MAP.put(Constants.FUNCTION, String.class);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

import io.unitycatalog.server.persist.model.Privileges;
import io.unitycatalog.server.persist.utils.HibernateConfigurator;
import io.unitycatalog.server.testdatabase.TestDatabase;
import io.unitycatalog.server.testdatabase.TestDatabases;
import io.unitycatalog.server.utils.ServerProperties;
import io.unitycatalog.server.utils.ServerProperties.Property;
import java.time.Duration;
Expand All @@ -30,20 +32,23 @@ public class JCasbinAuthorizerMultiInstanceTest {
private static final String TEST_REFRESH_INTERVAL = "PT0.05S";

private HibernateConfigurator hibernateConfigurator;
private TestDatabase testDatabase;
private final List<JCasbinAuthorizer> replicas = new ArrayList<>();

@BeforeEach
void setUp() {
Properties properties = new Properties();
properties.setProperty(Property.SERVER_ENV.getKey(), "test");
hibernateConfigurator = new HibernateConfigurator(new ServerProperties(properties));
testDatabase = TestDatabases.newDatabase();
hibernateConfigurator =
testDatabase.openHibernateConfigurator(new ServerProperties(properties));
}

@AfterEach
void tearDown() {
replicas.forEach(JCasbinAuthorizer::close);
replicas.clear();
hibernateConfigurator.close();
testDatabase.close();
}

private ServerProperties properties(boolean refreshEnabled, String interval) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

import io.unitycatalog.server.persist.model.Privileges;
import io.unitycatalog.server.persist.utils.HibernateConfigurator;
import io.unitycatalog.server.testdatabase.TestDatabase;
import io.unitycatalog.server.testdatabase.TestDatabases;
import io.unitycatalog.server.utils.ServerProperties;
import io.unitycatalog.server.utils.ServerProperties.Property;
import java.sql.Connection;
Expand All @@ -19,6 +21,7 @@
public class JCasbinAuthorizerTest {
private UnityCatalogAuthorizer authenticator;
private HibernateConfigurator hibernateConfigurator;
private TestDatabase testDatabase;

@BeforeEach
void setUp() throws Exception {
Expand All @@ -27,7 +30,8 @@ void setUp() throws Exception {
// Single-instance tests do not need background polling.
properties.setProperty(Property.POLICY_REFRESH_ENABLED.getKey(), "false");
ServerProperties serverProperties = new ServerProperties(properties);
hibernateConfigurator = new HibernateConfigurator(serverProperties);
testDatabase = TestDatabases.newDatabase();
hibernateConfigurator = testDatabase.openHibernateConfigurator(serverProperties);
authenticator = new JCasbinAuthorizer(hibernateConfigurator, serverProperties);
}

Expand All @@ -40,7 +44,7 @@ void tearDown() {
throw new RuntimeException(e);
}
}
hibernateConfigurator.close();
testDatabase.close();
}

@Test
Expand Down
Loading
Loading