feat(redshift): complete Glue external table lifecycle (#5866)

* feat(redshift): complete Glue external table lifecycle

* fix(test): use existing frame helper in Spectrum bridge test

* fix(redshift): safeguard external catalog lifecycle operations

* fix(redshift): shorten spectrum catalog lock waits and reuse test helper
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-17 13:59:29 -04:00
1 parent ffb3d84bad
commit c33823bd48
14 files changed
+1042 -60

No files matched your search

@@ -21,6 +21,8 @@ import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.postgresql.PGStatement;
import java.nio.charset.StandardCharsets;
@@ -438,6 +440,125 @@ class RedshiftSpectrumIntegrationTest {
}
}
@ParameterizedTest
@ValueSource(strings = {"simple", "extended"})
@Timeout(120)
void externalLifecycleKeepsGlueCatalogAndCachedRowsConsistent(String queryMode) throws Exception {
bucket = "spectrum-lifecycle-" + System.nanoTime();
glueDatabase = "lifecycle_" + System.nanoTime();
clusterId = "lifecycle-" + System.nanoTime();
s3Service.createBucket(bucket, "us-east-1");
s3Service.putObject(bucket, "events/part-1.csv", "1,10\n2,20\n".getBytes(StandardCharsets.UTF_8), "text/csv", null);
s3Service.putObject(bucket, "invalid/part-1.csv", "3,7\n".getBytes(StandardCharsets.UTF_8), "text/csv", null);
Database database = new Database();
database.setName(glueDatabase);
glueService.createDatabase(database);
Cluster cluster = createClusterWithRole(clusterId);
String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort()
+ "/dev?preferQueryMode=" + queryMode + "&socketTimeout=30";
String create = "CREATE EXTERNAL TABLE lake.events (id INTEGER, amount INTEGER) PARTITIONED BY (dt VARCHAR) "
+ "ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE LOCATION 's3://" + bucket + "/root/'";
String firstPartition = "ALTER TABLE lake.events ADD PARTITION (dt='first') LOCATION 's3://" + bucket + "/events/'";
try (Connection connection = DriverManager.getConnection(url, "admin", "Secret123");
Statement statement = connection.createStatement()) {
statement.execute("CREATE EXTERNAL SCHEMA lake FROM DATA CATALOG DATABASE '" + glueDatabase
+ "' IAM_ROLE '" + ROLE_ARN + "'");
statement.execute(create);
statement.execute(create.replace("lake.events", "lake.cold_events"));
statement.execute("CREATE USER lifecycle_reader PASSWORD 'Password123'");
statement.execute("GRANT USAGE ON SCHEMA lake TO lifecycle_reader");
try (Connection reader = DriverManager.getConnection(url, "lifecycle_reader", "Password123");
Statement readOnly = reader.createStatement()) {
for (String deniedSql : List.of(firstPartition.replace("lake.events", "lake.cold_events"),
"DROP TABLE lake.cold_events", "DROP SCHEMA lake RESTRICT")) {
SQLException denied = assertThrows(SQLException.class, () -> readOnly.execute(deniedSql));
assertEquals("42501", denied.getSQLState());
}
}
assertTrue(glueService.getPartitions(glueDatabase, "cold_events").isEmpty());
statement.execute("DROP TABLE lake.cold_events");
assertTotal(statement, 0);
statement.execute(firstPartition);
assertTotal(statement, 30);
assertEquals(List.of("first"), glueService.getPartitions(glueDatabase, "events").getFirst().getValues());
statement.execute(firstPartition.replace("ADD PARTITION", "ADD IF NOT EXISTS PARTITION")
.replace("/events/'", "/invalid/'"));
assertTotal(statement, 30);
SQLException duplicate = assertThrows(SQLException.class, () -> statement.execute(firstPartition));
assertEquals("42710", duplicate.getSQLState());
statement.execute("CREATE VIEW saved_events AS SELECT id FROM lake.events");
statement.execute("GRANT SELECT ON lake.events TO lifecycle_reader");
lifecycleDataStatement("ALTER TABLE lake.events ADD PARTITION (dt='second') LOCATION 's3://"
+ bucket + "/invalid/'");
assertTotal(statement, 37);
try (Connection reader = DriverManager.getConnection(url, "lifecycle_reader", "Password123");
Statement readOnly = reader.createStatement();
ResultSet rows = readOnly.executeQuery("SELECT COUNT(*) FROM lake.events")) {
assertTrue(rows.next());
assertEquals(3, rows.getInt(1));
SQLException denied = assertThrows(SQLException.class, () -> readOnly.execute("DROP TABLE lake.events"));
assertEquals("42501", denied.getSQLState());
}
try (ResultSet rows = statement.executeQuery("SELECT COUNT(*) FROM svv_external_partitions WHERE schemaname='lake'")) {
assertTrue(rows.next());
assertEquals(2, rows.getInt(1));
}
connection.setAutoCommit(false);
SQLException transaction = assertThrows(SQLException.class, () -> statement.execute("DROP TABLE lake.events"));
assertEquals("25001", transaction.getSQLState());
connection.rollback();
connection.setAutoCommit(true);
assertEquals("events", glueService.getTable(glueDatabase, "events").getName());
SQLException dependent = assertThrows(SQLException.class, () -> statement.execute("DROP TABLE lake.events"));
assertEquals("2BP01", dependent.getSQLState());
assertEquals("events", glueService.getTable(glueDatabase, "events").getName());
statement.execute("DROP TABLE lake.events CASCADE");
assertThrows(AwsException.class, () -> glueService.getTable(glueDatabase, "events"));
statement.execute("DROP TABLE IF EXISTS lake.events");
lifecycleDataStatement(create);
lifecycleDataStatement(firstPartition);
assertTotal(statement, 30);
SQLException restrict = assertThrows(SQLException.class, () -> statement.execute("DROP SCHEMA lake RESTRICT"));
assertEquals("2BP01", restrict.getSQLState());
lifecycleDataStatement("DROP SCHEMA lake CASCADE");
assertTrue(externalRegistry.list("000000000000", "000000000000:" + clusterId, "dev").isEmpty());
assertEquals("events", glueService.getTable(glueDatabase, "events").getName());
assertEquals(1, glueService.getPartitions(glueDatabase, "events").size());
assertEquals(2, s3Service.listObjects(bucket, "", null, 100).size());
try (ResultSet rows = statement.executeQuery("SELECT COUNT(*) FROM svv_external_schemas WHERE schemaname='lake'")) {
assertTrue(rows.next());
assertEquals(0, rows.getInt(1));
}
statement.execute("DROP SCHEMA IF EXISTS lake");
statement.execute("CREATE EXTERNAL SCHEMA lake FROM DATA CATALOG DATABASE '" + glueDatabase
+ "' IAM_ROLE '" + ROLE_ARN + "'");
assertTotal(statement, 30);
lifecycleDataStatement("DROP TABLE lake.events");
glueService.deleteDatabase(glueDatabase);
glueDatabase = null;
statement.execute("DROP SCHEMA lake");
}
}
private static void assertTotal(Statement statement, long total) throws SQLException {
try (ResultSet rows = statement.executeQuery("SELECT COALESCE(SUM(amount),0) FROM lake.events")) {
assertTrue(rows.next());
assertEquals(total, rows.getLong(1));
}
}
private void lifecycleDataStatement(String sql) {
RestAssuredJsonUtils.configureAwsContentTypes();
String queryId = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
{"ClusterIdentifier":"%s","Database":"dev","DbUser":"admin","Sql":"%s","WaitTimeSeconds":30}
""".formatted(clusterId, sql.replace("\\", "\\\\").replace("\"", "\\\"")))
.then().statusCode(200).extract().path("Id");
assertEquals("FINISHED", RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
"{\"Id\":\"" + queryId + "\"}").then().statusCode(200).extract().path("Status"));
}
private static Connection waitForConnection(Cluster cluster, String username, String password) throws SQLException {
String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort() + "/dev";
return Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO)
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumInterceptor;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumQueryPreparation;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumSession;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.jboss.logging.Logger;
@@ -355,6 +357,32 @@ class RedshiftInterceptingBridgeTest {
assertEquals('T', fromBridge.read());
}
@Test
@Timeout(20)
void parsingAndDescribingExternalDdlDoesNotExecuteCatalogChanges() throws Exception {
String sql = "ALTER TABLE lake.events ADD PARTITION (dt='today') LOCATION 's3://bucket/today/'";
SpectrumInterceptor interceptor = inlineMock(SpectrumInterceptor.class);
SpectrumQueryPreparation preparation = Mockito.mock(SpectrumQueryPreparation.class);
Mockito.when(interceptor.preparation()).thenReturn(preparation);
Mockito.when(preparation.referencesExternal(Mockito.eq(sql), Mockito.any())).thenReturn(true);
Mockito.when(interceptor.plan(Mockito.eq(sql), Mockito.any())).thenReturn(new SpectrumInterceptor.Plan.ExternalDdl(
sql, new SpectrumSession("000000000000", "000000000000:c", "dev", List.of(), false)));
startBridge(interceptor);
PostgresWireDecoder.ParseMessage parse = new PostgresWireDecoder.ParseMessage("ddl", sql, List.of());
testClientEnd.getOutputStream().write(PostgresWireDecoder.encodeParse(parse, sql));
testClientEnd.getOutputStream().write(frame('D', concat(new byte[]{'S'}, cString("ddl"))));
testClientEnd.getOutputStream().flush();
InputStream response = testClientEnd.getInputStream();
assertEquals('1', response.read());
skipFrameBody(response);
assertEquals('t', response.read());
skipFrameBody(response);
assertEquals('n', response.read());
skipFrameBody(response);
Mockito.verify(preparation, Mockito.never()).prepare(Mockito.anyString(), Mockito.any(), Mockito.any());
Mockito.verify(interceptor, Mockito.never()).execute(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any());
}
private static void skipFrameBody(InputStream in) throws IOException {
int length = ByteBuffer.wrap(in.readNBytes(4)).getInt();
in.readNBytes(length - 4);
@@ -0,0 +1,383 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.glue.GlueService;
import io.github.hectorvent.floci.services.glue.model.Column;
import io.github.hectorvent.floci.services.glue.model.Partition;
import io.github.hectorvent.floci.services.glue.model.StorageDescriptor;
import io.github.hectorvent.floci.services.glue.model.Table;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class ExternalLifecycleTest {
private static final SpectrumSession SESSION = new SpectrumSession("000000000000", "000000000000:c",
"dev", List.of(), false);
private static final ExternalSchemaBinding BINDING = new ExternalSchemaBinding(SESSION.accountId(),
SESSION.clusterKey(), "dev", "lake", "analytics", "arn:aws:iam::000000000000:role/R");
private static final String ADD = "ALTER TABLE lake.sales ADD PARTITION (dt='2026-10-17') LOCATION 's3://bucket/day/'";
private final ExternalCatalogRegistry registry = mock(ExternalCatalogRegistry.class);
private final ExternalTableMaterializer materializer = mock(ExternalTableMaterializer.class);
private final GlueService glue = mock(GlueService.class);
private final BackendSql backend = mock(BackendSql.class);
private final ExternalMetadataWriter metadata = spy(new ExternalMetadataWriter(glue, new ObjectMapper()));
private final ExternalCatalogLocks catalogLocks = new ExternalCatalogLocks();
private final SpectrumQueryPreparation preparation = new SpectrumQueryPreparation(registry, materializer,
new ExternalStatementParser(), glue, metadata, catalogLocks);
private Table table;
@BeforeEach
void setUp() {
when(registry.list(SESSION.accountId(), SESSION.clusterKey(), "dev")).thenReturn(List.of(BINDING));
Column key = new Column();
key.setName("dt");
key.setType("string");
table = new Table();
table.setName("sales");
table.setPartitionKeys(List.of(key));
table.setStorageDescriptor(new StorageDescriptor());
when(glue.getTable("analytics", "sales")).thenReturn(table);
doNothing().when(metadata).refresh(any(), anyString(), any());
}
@Test
void registersPartitionAndInvalidatesMaterializedRows() {
assertTrue(preparation.handlesDdl(ADD, SESSION));
assertTrue(preparation.prepare(ADD, SESSION, backend));
ArgumentCaptor<Partition> captured = ArgumentCaptor.forClass(Partition.class);
verify(glue).createPartition(eq("analytics"), eq("sales"), captured.capture());
assertEquals(List.of("2026-10-17"), captured.getValue().getValues());
assertEquals("s3://bucket/day/", captured.getValue().getStorageDescriptor().getLocation());
verify(materializer).invalidateTable(SESSION.clusterKey(), "dev", "lake", "sales");
verify(metadata).refresh(backend, SESSION.accountId(), BINDING);
}
@Test
void duplicatePartitionIsAnErrorAndIfNotExistsPreservesItsLocation() {
Partition existing = new Partition();
existing.setValues(List.of("2026-10-17"));
when(glue.getPartitions("analytics", "sales")).thenReturn(List.of(existing));
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare(ADD, SESSION, backend));
assertEquals("42710", error.sqlState());
assertTrue(preparation.prepare(ADD.replace("ADD PARTITION", "ADD IF NOT EXISTS PARTITION"), SESSION, backend));
verify(glue, never()).createPartition(anyString(), anyString(), any());
}
@Test
void validatesEveryPartitionBeforeWritingAny() {
String sql = ADD + " PARTITION (wrong='x') LOCATION 's3://bucket/invalid/'";
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare(sql, SESSION, backend));
assertEquals("22023", error.sqlState());
verify(glue, never()).createPartition(anyString(), anyString(), any());
}
@Test
void duplicateWithinTheSameRequestDoesNotPartiallyRegister() {
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare(ADD + " PARTITION (dt='2026-10-17') LOCATION 's3://bucket/other/'", SESSION, backend));
assertEquals("42710", error.sqlState());
verify(glue, never()).createPartition(anyString(), anyString(), any());
}
@Test
void dropTableRemovesGlueDefinitionAndColdOrCachedBackendRelation() {
assertTrue(preparation.handlesDdl("DROP TABLE lake.sales", SESSION));
assertTrue(preparation.prepare("DROP TABLE lake.sales", SESSION, backend));
verify(backend).execute("DROP TABLE IF EXISTS \"lake\".\"sales\" RESTRICT");
verify(glue).deleteTable("analytics", "sales");
verify(materializer).forget(SESSION.clusterKey(), "dev", "lake", "sales");
verify(metadata).refresh(backend, SESSION.accountId(), BINDING);
verify(materializer, never()).ensureCurrent(any(), any(), any(), anyString());
}
@Test
void failedDependencyCheckKeepsGlueTable() {
doThrow(new SpectrumReadException("2BP01", "dependent view")).when(backend).execute(anyString());
assertThrows(SpectrumReadException.class, () -> preparation.prepare("DROP TABLE lake.sales", SESSION, backend));
verify(glue, never()).deleteTable(anyString(), anyString());
verifyNoInteractions(materializer);
}
@Test
void dropMissingTableRequiresIfExistsAndCleansStaleCache() {
when(glue.getTable("analytics", "sales"))
.thenThrow(new AwsException("EntityNotFoundException", "gone", 400));
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare("DROP TABLE lake.sales", SESSION, backend));
assertEquals("42P01", error.sqlState());
verifyNoInteractions(backend);
assertTrue(preparation.prepare("DROP TABLE IF EXISTS lake.sales CASCADE", SESSION, backend));
verify(backend).execute("DROP TABLE IF EXISTS \"lake\".\"sales\" CASCADE");
verify(materializer).forget(SESSION.clusterKey(), "dev", "lake", "sales");
verify(glue, never()).deleteTable(anyString(), anyString());
}
@Test
void restrictChecksGlueTablesThatHaveNeverBeenLoaded() {
when(glue.getTables("analytics")).thenReturn(List.of(table));
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare("DROP SCHEMA lake", SESSION, backend));
assertEquals("2BP01", error.sqlState());
verify(backend, never()).execute(startsWith("DROP SCHEMA"));
verify(registry, never()).unbind(anyString(), anyString(), anyString(), anyString());
}
@Test
void cascadeUnregistersSchemaWithoutDeletingGlueDatabaseOrTables() {
assertTrue(preparation.handlesDdl("DROP SCHEMA lake CASCADE", SESSION));
assertTrue(preparation.prepare("DROP SCHEMA lake CASCADE", SESSION, backend));
verify(backend).execute("DROP SCHEMA \"lake\" CASCADE; SELECT floci_internal.purge_external_schema('lake')");
verify(registry).unbind(SESSION.accountId(), SESSION.clusterKey(), "dev", "lake");
verify(materializer).forgetSchema(SESSION.clusterKey(), "dev", "lake");
verify(glue, never()).deleteDatabase(anyString());
verify(glue, never()).deleteTable(anyString(), anyString());
}
@Test
void failedSchemaDropRetainsBindingAndCache() {
doThrow(new SpectrumReadException("42501", "not owner")).when(backend).execute(anyString());
assertThrows(SpectrumReadException.class, () -> preparation.prepare("DROP SCHEMA lake CASCADE", SESSION, backend));
verify(registry, never()).unbind(anyString(), anyString(), anyString(), anyString());
verifyNoInteractions(materializer);
}
@Test
void rejectsLifecycleInsideTransactionsBeforeMutatingStores() {
SpectrumSession transaction = new SpectrumSession(SESSION.accountId(), SESSION.clusterKey(), "dev", List.of(), true);
for (String sql : List.of(ADD, "DROP TABLE lake.sales", "DROP SCHEMA lake CASCADE")) {
assertTrue(preparation.handlesDdl(sql, transaction));
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare(sql, transaction, backend));
assertEquals("25001", error.sqlState());
}
verifyNoInteractions(glue, backend, materializer);
}
@Test
void leavesInternalLifecycleToPostgres() {
for (String sql : List.of("DROP TABLE public.sales", "DROP SCHEMA public CASCADE",
"ALTER TABLE public.sales ADD COLUMN total INTEGER")) {
assertFalse(preparation.handlesDdl(sql, SESSION));
assertFalse(preparation.prepare(sql, SESSION, backend));
}
verifyNoInteractions(glue, backend, materializer);
}
@Test
void malformedOrRepeatedPartitionKeysNeverReachGlue() {
for (String keys : List.of("dt='x', garbage", "dt='x', dt='y'", "dt='x' garbage")) {
SpectrumSqlException error = assertThrows(SpectrumSqlException.class, () -> preparation.prepare(
"ALTER TABLE lake.sales ADD PARTITION (" + keys + ") LOCATION 's3://bucket/day/'", SESSION, backend));
assertEquals("42601", error.sqlState());
}
verifyNoInteractions(glue, backend, materializer);
}
@Test
void ifExistsDoesNotSuppressAccessDenied() {
when(glue.getTable("analytics", "sales"))
.thenThrow(new AwsException("AccessDeniedException", "denied", 403));
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare("DROP TABLE IF EXISTS lake.sales", SESSION, backend));
assertEquals("42501", error.sqlState());
verifyNoInteractions(backend, materializer);
}
@Test
void quotesSchemaAndTableNamesBeforeSendingBackendDdl() {
ExternalSchemaBinding quoted = new ExternalSchemaBinding(SESSION.accountId(), SESSION.clusterKey(),
"dev", "a\"b", "analytics", BINDING.iamRoleArn());
when(registry.list(SESSION.accountId(), SESSION.clusterKey(), "dev")).thenReturn(List.of(quoted));
assertTrue(preparation.prepare("DROP TABLE IF EXISTS \"a\"\"b\".\"sales\"", SESSION, backend));
verify(backend).execute("DROP TABLE IF EXISTS \"a\"\"b\".\"sales\" RESTRICT");
}
@Test
void backendAuthorizationFailsBeforeAnyCatalogMutation() {
doThrow(new SpectrumReadException("42501", "not owner")).when(backend).execute(anyString());
for (String sql : List.of(ADD, "DROP TABLE lake.sales")) {
SpectrumReadException error = assertThrows(SpectrumReadException.class,
() -> preparation.prepare(sql, SESSION, backend));
assertEquals("42501", error.sqlState());
}
verify(glue, never()).createPartition(anyString(), anyString(), any());
verify(glue, never()).deleteTable(anyString(), anyString());
}
@Test
void rejectsCaseVariantsOfTheSamePartitionKey() {
SpectrumSqlException error = assertThrows(SpectrumSqlException.class, () -> preparation.prepare(
"ALTER TABLE lake.sales ADD PARTITION (\"DT\"='upper', dt='lower') LOCATION 's3://bucket/day/'",
SESSION, backend));
assertEquals("42601", error.sqlState());
verifyNoInteractions(glue, backend, materializer);
}
@Test
void checksSchemaOwnershipBeforeReadingGlueTables() {
doThrow(new SpectrumReadException("42501", "not owner")).when(backend).execute(anyString());
SpectrumReadException error = assertThrows(SpectrumReadException.class,
() -> preparation.prepare("DROP SCHEMA lake RESTRICT", SESSION, backend));
assertEquals("42501", error.sqlState());
verifyNoInteractions(glue);
verify(registry, never()).unbind(anyString(), anyString(), anyString(), anyString());
}
@Test
void dropsLocalSchemaWhenGlueDatabaseIsAlreadyGone() {
when(glue.getTables("analytics")).thenThrow(new AwsException("EntityNotFoundException", "gone", 400));
assertTrue(preparation.prepare("DROP SCHEMA IF EXISTS lake", SESSION, backend));
verify(backend).execute("DROP SCHEMA IF EXISTS \"lake\" RESTRICT; SELECT floci_internal.purge_external_schema('lake')");
verify(registry).unbind(SESSION.accountId(), SESSION.clusterKey(), "dev", "lake");
verify(materializer).forgetSchema(SESSION.clusterKey(), "dev", "lake");
}
@Test
void schemaDropDoesNotSuppressOtherGlueFailures() {
when(glue.getTables("analytics")).thenThrow(new AwsException("AccessDeniedException", "denied", 403));
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare("DROP SCHEMA IF EXISTS lake", SESSION, backend));
assertEquals("42501", error.sqlState());
verify(backend, never()).execute(startsWith("DROP SCHEMA"));
verify(registry, never()).unbind(anyString(), anyString(), anyString(), anyString());
}
@Test
void rollsBackOnlyNewPartitionsWhenLaterWriteFails() {
Partition existing = new Partition();
existing.setValues(List.of("existing"));
when(glue.getPartitions("analytics", "sales")).thenReturn(List.of(existing));
doAnswer(invocation -> {
Partition partition = invocation.getArgument(2);
if (partition.getValues().equals(List.of("fail"))) {
throw new AwsException("InternalServiceException", "write failed", 500);
}
return null;
}).when(glue).createPartition(anyString(), anyString(), any());
String sql = ADD.replace("ADD PARTITION", "ADD IF NOT EXISTS PARTITION")
+ " PARTITION (dt='existing') LOCATION 's3://bucket/old/'"
+ " PARTITION (dt='fail') LOCATION 's3://bucket/fail/'";
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare(sql, SESSION, backend));
assertEquals("write failed", error.getMessage());
verify(glue).deletePartition("analytics", "sales", List.of("2026-10-17"));
verify(glue, never()).deletePartition("analytics", "sales", List.of("existing"));
verify(glue, never()).deletePartition("analytics", "sales", List.of("fail"));
}
@Test
void rollsBackPartitionsWhenMetadataRefreshFailsWithoutMaskingTheFailure() {
SpectrumReadException failure = new SpectrumReadException("58030", "refresh failed");
doThrow(failure).when(metadata).refresh(backend, SESSION.accountId(), BINDING);
doThrow(new AwsException("InternalServiceException", "cleanup failed", 500)).when(glue)
.deletePartition("analytics", "sales", List.of("2026-10-17"));
assertSame(failure, assertThrows(SpectrumReadException.class, () -> preparation.prepare(ADD, SESSION, backend)));
verify(glue).deletePartition("analytics", "sales", List.of("2026-10-17"));
assertEquals(1, failure.getSuppressed().length);
verify(materializer).invalidateTable(SESSION.clusterKey(), "dev", "lake", "sales");
}
@Test
void implicitExtendedTransactionTimesOutWhileCatalogMutationIsWaiting() throws Exception {
when(backend.permitsCachePublication()).thenReturn(false);
ExternalCatalogLocks shortLocks = new ExternalCatalogLocks(Duration.ofMillis(20));
SpectrumQueryPreparation timedPreparation = new SpectrumQueryPreparation(registry, materializer,
new ExternalStatementParser(), glue, metadata, shortLocks);
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
ExternalCatalogLocks.Guard mutation = shortLocks.write(BINDING);
try {
Future<Boolean> read = executor.submit(
() -> timedPreparation.prepare("SELECT * FROM lake.sales", SESSION, backend));
ExecutionException failure = assertThrows(ExecutionException.class,
() -> read.get(5, TimeUnit.SECONDS));
SpectrumReadException timeout = assertInstanceOf(SpectrumReadException.class, failure.getCause());
assertEquals("58030", timeout.sqlState());
verifyNoInteractions(materializer, glue);
} finally {
mutation.close();
}
}
}
@Test
void removesAllNewPartitionsWhenMetadataRefreshFails() {
SpectrumReadException failure = new SpectrumReadException("58030", "refresh failed");
doThrow(failure).when(metadata).refresh(backend, SESSION.accountId(), BINDING);
String sql = ADD + " PARTITION (dt='2026-10-18') LOCATION 's3://bucket/next/'";
assertSame(failure, assertThrows(SpectrumReadException.class,
() -> preparation.prepare(sql, SESSION, backend)));
verify(glue).deletePartition("analytics", "sales", List.of("2026-10-17"));
verify(glue).deletePartition("analytics", "sales", List.of("2026-10-18"));
verify(materializer).invalidateTable(SESSION.clusterKey(), "dev", "lake", "sales");
}
@Test
void concurrentIfNotExistsAddsShareTheGlueTableLock() throws Exception {
List<Partition> stored = new CopyOnWriteArrayList<>();
CountDownLatch checking = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
AtomicInteger checks = new AtomicInteger();
when(glue.getTable("ANALYTICS", "sales")).thenReturn(table);
when(glue.getPartitions(anyString(), eq("sales"))).thenAnswer(invocation -> {
List<Partition> snapshot = List.copyOf(stored);
if (checks.incrementAndGet() == 1) {
checking.countDown();
assertTrue(release.await(10, TimeUnit.SECONDS));
}
return snapshot;
});
doAnswer(invocation -> {
stored.add(invocation.getArgument(2));
return null;
}).when(glue).createPartition(anyString(), anyString(), any());
String sql = ADD.replace("ADD PARTITION", "ADD IF NOT EXISTS PARTITION");
SpectrumSession otherSession = new SpectrumSession(SESSION.accountId(), SESSION.accountId() + ":other",
"dev", List.of(), false);
ExternalSchemaBinding alias = new ExternalSchemaBinding(SESSION.accountId(), otherSession.clusterKey(),
"dev", "alias", "ANALYTICS", BINDING.iamRoleArn());
when(registry.list(SESSION.accountId(), otherSession.clusterKey(), "dev")).thenReturn(List.of(alias));
SpectrumQueryPreparation otherPreparation = new SpectrumQueryPreparation(registry, materializer,
new ExternalStatementParser(), glue, metadata, catalogLocks);
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
Future<Boolean> first = executor.submit(() -> preparation.prepare(sql, SESSION, backend));
try {
assertTrue(checking.await(10, TimeUnit.SECONDS));
AtomicReference<Thread> secondThread = new AtomicReference<>();
Future<Boolean> second = executor.submit(() -> {
secondThread.set(Thread.currentThread());
return otherPreparation.prepare(
sql.replace("lake.sales", "alias.sales"), otherSession, backend);
});
awaitBlockedOrDone(secondThread, second);
assertFalse(second.isDone());
release.countDown();
assertTrue(first.get(10, TimeUnit.SECONDS));
assertTrue(second.get(10, TimeUnit.SECONDS));
assertEquals(1, stored.size());
} finally {
release.countDown();
}
}
}
}
@@ -32,14 +32,18 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
@@ -452,6 +456,20 @@ class ExternalTableMaterializerTest {
assertThat(backend.statements.getLast(), containsString("CREATE TABLE \"analytics\".\"events\""));
}
@Test
void invalidatingDataKeepsTheExistingTableAndItsDependencies() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
materializer.ensureCurrent(backend, session(false), BINDING, "events");
materializer.invalidateTable(BINDING.clusterKey(), "dev", "analytics", "events");
backend.statements.clear();
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
String swap = backend.statements.getLast();
assertThat(swap, containsString("TRUNCATE \"analytics\".\"events\""));
assertThat(swap, not(containsString("DROP TABLE IF EXISTS \"analytics\".\"events\"")));
}
private void forceReload() {
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("events/"), eq(""), eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(
@@ -766,9 +784,13 @@ class ExternalTableMaterializerTest {
Future<ExternalTableMaterializer.Outcome> first = executor.submit(
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThat(loading.await(10, TimeUnit.SECONDS), equalTo(true));
Future<ExternalTableMaterializer.Outcome> second = executor.submit(
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThrows(TimeoutException.class, () -> second.get(300, TimeUnit.MILLISECONDS));
AtomicReference<Thread> secondThread = new AtomicReference<>();
Future<ExternalTableMaterializer.Outcome> second = executor.submit(() -> {
secondThread.set(Thread.currentThread());
return materializer.ensureCurrent(backend, session(false), BINDING, "events");
});
awaitBlockedOrDone(secondThread, second);
assertFalse(second.isDone());
release.countDown();
@@ -780,6 +802,56 @@ class ExternalTableMaterializerTest {
}
}
@Test
void dropWaitsForAnEarlierLoadBeforeDeletingTheMaterializedTable() throws Exception {
AtomicReference<Table> stored = new AtomicReference<>(csvTable());
AtomicInteger lookups = new AtomicInteger();
CountDownLatch reading = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
when(glue.getTable("lake", "events")).thenAnswer(invocation -> {
Table snapshot = stored.get();
if (lookups.incrementAndGet() == 1) {
reading.countDown();
assertTrue(release.await(10, TimeUnit.SECONDS));
}
if (snapshot == null) {
throw new AwsException("EntityNotFoundException", "gone", 400);
}
return snapshot;
});
doAnswer(invocation -> {
stored.set(null);
return null;
}).when(glue).deleteTable("lake", "events");
ExternalCatalogRegistry registry = mock(ExternalCatalogRegistry.class);
when(registry.list(ACCOUNT, BINDING.clusterKey(), "dev")).thenReturn(List.of(BINDING));
SpectrumQueryPreparation preparation = new SpectrumQueryPreparation(registry, materializer,
new ExternalStatementParser(), glue, mock(ExternalMetadataWriter.class), materializer.catalogLocks());
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
Future<ExternalTableMaterializer.Outcome> load = executor.submit(
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
try {
assertTrue(reading.await(10, TimeUnit.SECONDS));
AtomicReference<Thread> dropThread = new AtomicReference<>();
Future<Boolean> drop = executor.submit(() -> {
dropThread.set(Thread.currentThread());
return preparation.prepare("DROP TABLE analytics.events", session(false), backend);
});
awaitBlockedOrDone(dropThread, drop);
assertFalse(drop.isDone());
release.countDown();
assertEquals(ExternalTableMaterializer.Outcome.LOADED, load.get(10, TimeUnit.SECONDS));
assertTrue(drop.get(10, TimeUnit.SECONDS));
assertEquals("DROP TABLE IF EXISTS \"analytics\".\"events\" RESTRICT", backend.statements.getLast());
assertEquals(ExternalTableMaterializer.Outcome.NOT_EXTERNAL,
materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertTrue(materializer.loadedTables(BINDING.clusterKey(), "dev", "analytics").isEmpty());
} finally {
release.countDown();
}
}
}
private Partition partitionAt(String inputFormat, Table table) {
StorageDescriptor descriptor = new StorageDescriptor();
descriptor.setLocation("s3://bucket/events/");
@@ -14,8 +14,8 @@ public final class ThreadStates {
private ThreadStates() {}
/**
* Returns once {@code thread} is blocked entering a monitor, or {@code task} has finished,
* whichever comes first. Code that serializes correctly leaves the second request blocked
* Returns once {@code thread} is blocked entering a monitor or parked on a lock, or {@code task} has
* finished, whichever comes first. Code that serializes correctly leaves the second request blocked
* behind the first; code that does not lets it run to the end, which the caller's assertions
* then catch. Polls every 5 ms and gives up after five seconds rather than hang a broken test.
*/
@@ -25,9 +25,9 @@ public final class ThreadStates {
}
/**
* Returns once {@code thread} is blocked entering a monitor or is no longer alive. Same wait as
* the {@link Future} overload, for a test that owns the {@link Thread} directly; gives up after
* ten seconds and fails, since a thread still running unblocked by then is not overlapping the
* Returns once {@code thread} is blocked entering a monitor, parked on a lock, or is no longer alive.
* Same wait as the {@link Future} overload, for a test that owns the {@link Thread} directly; gives up
* after ten seconds and fails, since a thread still running unblocked by then is not overlapping the
* way the test needs.
*/
public static void awaitBlockedOrDone(Thread thread) throws InterruptedException {
@@ -48,6 +48,10 @@ public final class ThreadStates {
}
private static boolean isBlocked(Thread thread) {
return thread != null && thread.getState() == Thread.State.BLOCKED;
if (thread == null) {
return false;
}
Thread.State state = thread.getState();
return state == Thread.State.BLOCKED || state == Thread.State.WAITING;
}
}