feat(glue): serve AWS Glue's Iceberg REST endpoint (#8472)

AWS Glue serves the Apache Iceberg REST catalog at
glue.<region>.amazonaws.com/iceberg, the catalog Spark, PyIceberg,
Trino and DuckDB attach to read and write Glue's Iceberg tables. Floci
had no such endpoint, so none of them could write an Iceberg table
through it, and DuckDB, which writes Iceberg only through an attached
catalog, could not write one at all.

Floci now serves it at /iceberg, routed by the request's signing
service as other contested REST paths are, with the twelve operations
AWS lists for it. A namespace is a Glue database and a table a Glue
table with table_type ICEBERG. The writer writes data files and
manifests; a commit checks the request's requirements, applies its
updates to the table's metadata JSON, writes the next metadata file
next to the last one and moves the Glue table's metadata_location to
it, refused with CommitFailedException when the Glue table changed
since. A staged create is committed with assert-create, as DuckDB and
Spark create tables. No Iceberg library is involved.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-15 13:48:35 -04:00
1 parent 7872b07c43
commit 5059a3cd40
14 files changed
+2026 -1

No files matched your search

@@ -0,0 +1,167 @@
package io.floci.aws.services.glue.iceberg;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestContext;
import io.floci.aws.services.glue.GlueService;
import io.floci.aws.services.glue.model.Database;
import io.floci.aws.services.glue.model.Table;
import io.floci.aws.services.s3.S3Service;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Answers;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** The catalog's commit paths when Glue refuses the write, and who it answers under IAM enforcement. */
class GlueIcebergCatalogTest {
private static final String CREATE_COMMIT = """
{"requirements":[{"type":"assert-create"}],"updates":[
{"action":"add-schema","schema":{"type":"struct","schema-id":0,"fields":[
{"id":1,"name":"id","required":false,"type":"long"}]}},
{"action":"set-current-schema","schema-id":-1},
{"action":"add-spec","spec":{"spec-id":0,"fields":[]}},{"action":"set-default-spec","spec-id":-1},
{"action":"add-sort-order","sort-order":{"order-id":0,"fields":[]}},
{"action":"set-default-sort-order","sort-order-id":-1},
{"action":"set-location","location":"s3://lake-bucket/lake/events"}]}
""";
private final ObjectMapper mapper = new ObjectMapper();
private GlueService glue;
private S3Service s3;
private EmulatorConfig config;
private RequestContext requestContext;
private GlueIcebergCatalog catalog;
@BeforeEach
void setUp() {
glue = Mockito.mock(GlueService.class);
s3 = Mockito.mock(S3Service.class);
config = Mockito.mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS);
requestContext = Mockito.mock(RequestContext.class);
catalog = new GlueIcebergCatalog(glue, s3, new RegionResolver("us-east-1", "000000000000"), mapper, config,
requestContext, Clock.fixed(Instant.ofEpochMilli(10_000L), ZoneOffset.UTC));
Database database = new Database("lake");
database.setLocationUri("s3://lake-bucket/lake");
when(glue.getDatabase("lake")).thenReturn(database);
}
private void tableMissing() {
when(glue.getTable("lake", "events")).thenThrow(new AwsException("EntityNotFoundException",
"Table not found: lake.events", 400));
}
private void tableExists() {
ObjectNode metadata = IcebergTableMetadata.empty(1_000L);
try {
IcebergTableMetadata.apply(metadata, mapper.readTree(CREATE_COMMIT).path("updates"), 2_000L);
} catch (Exception e) {
throw new IllegalStateException(e);
}
String location = "s3://lake-bucket/lake/events/metadata/00000-a.metadata.json";
Table table = new Table();
table.setName("events");
table.setVersionId("1");
Map<String, String> parameters = new HashMap<>();
parameters.put("table_type", "ICEBERG");
parameters.put("metadata_location", location);
table.setParameters(parameters);
when(glue.getTable("lake", "events")).thenReturn(table);
when(s3.openObjectStream("lake-bucket", "lake/events/metadata/00000-a.metadata.json", null))
.thenAnswer(invocation -> new ByteArrayInputStream(
mapper.writeValueAsString(metadata).getBytes(StandardCharsets.UTF_8)));
}
private String writtenMetadataKey() {
ArgumentCaptor<String> key = ArgumentCaptor.forClass(String.class);
verify(s3).putObject(eq("lake-bucket"), key.capture(), any(), eq("application/json"), isNull());
return key.getValue();
}
@Test
void aCommitGlueRefusesAsConcurrentIsACommitFailureAndItsMetadataFileIsRemoved() throws Exception {
tableExists();
doThrow(new AwsException("ConcurrentModificationException", "concurrent", 400))
.when(glue).updateTable(eq("lake"), any(), eq("1"), eq(false));
IcebergRestException e = assertThrows(IcebergRestException.class, () -> catalog.commitTable(":", "lake",
"events", mapper.readTree(IcebergCommits.snapshotCommit(7, null, 1))));
assertEquals("CommitFailedException", e.type());
String written = writtenMetadataKey();
verify(s3).deleteObject("lake-bucket", written);
}
@Test
void aStagedCreateIsAConflictOnlyWhenTheTableAppearedMeanwhile() throws Exception {
tableMissing();
doThrow(new AwsException("AlreadyExistsException", "Table already exists", 400))
.when(glue).createTable(eq("lake"), any());
IcebergRestException raced = assertThrows(IcebergRestException.class,
() -> catalog.commitTable(":", "lake", "events", mapper.readTree(CREATE_COMMIT)));
assertEquals("CommitFailedException", raced.type());
String written = writtenMetadataKey();
verify(s3).deleteObject("lake-bucket", written);
}
@Test
void aStagedCreateIntoANamespaceThatWentAwayAnswersThatInsteadOfAConflict() throws Exception {
tableMissing();
doThrow(new AwsException("EntityNotFoundException", "Database not found: lake", 400))
.when(glue).createTable(eq("lake"), any());
IcebergRestException gone = assertThrows(IcebergRestException.class,
() -> catalog.commitTable(":", "lake", "events", mapper.readTree(CREATE_COMMIT)));
assertEquals("NoSuchNamespaceException", gone.type());
String written = writtenMetadataKey();
verify(s3).deleteObject("lake-bucket", written);
}
@Test
void underIamEnforcementOnlyRootCredentialsAndFlocisOwnCallersReachTheCatalog() {
when(config.services().iam().enforcementEnabled()).thenReturn(true);
when(requestContext.getAccountId()).thenReturn("000000000000");
when(requestContext.getAccessKeyId()).thenReturn("AKIAEXAMPLEUSER0001");
IcebergRestException refused = assertThrows(IcebergRestException.class, () -> catalog.config(null));
assertEquals(403, refused.code());
assertEquals("ForbiddenException", refused.type());
for (String rootOrInternal : new String[] {"test", "000000000000", null}) {
when(requestContext.getAccessKeyId()).thenReturn(rootOrInternal);
assertEquals("catalogs/:", catalog.config(null).path("overrides").path("prefix").asText());
}
}
@Test
void withoutEnforcementAnyCallerReachesTheCatalog() {
when(config.services().iam().enforcementEnabled()).thenReturn(false);
when(requestContext.getAccessKeyId()).thenReturn("AKIAEXAMPLEUSER0001");
assertEquals("catalogs/:", catalog.config(null).path("overrides").path("prefix").asText());
}
}
@@ -0,0 +1,48 @@
package io.floci.aws.services.glue.iceberg;
import io.floci.aws.testing.SignedIamEnforcementProfile;
import io.floci.aws.testing.SignedIamUsers;
import io.floci.aws.testutil.AwsRequestSigner;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
/**
* Under IAM enforcement, no rule maps the Glue Iceberg REST endpoint's routes to the Glue actions AWS checks for them
* yet, so the endpoint refuses an IAM principal, even one allowed every Glue action, rather than let it through
* unchecked; the account's root credentials still reach it.
*/
@QuarkusTest
@TestProfile(SignedIamEnforcementProfile.class)
class GlueIcebergIamIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@Test
void anIamPrincipalIsRefusedAndRootCredentialsAreAnswered() throws Exception {
String allowEverything = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Action\":\"glue:*\",\"Resource\":\"*\"}]}";
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "glue-iceberg-", "glue", allowEverything)) {
get(user.signer("glue"), "/iceberg/v1/config").then().statusCode(403)
.body("error.type", equalTo("ForbiddenException"));
get(user.signer("glue"), "/iceberg/v1/catalogs/:/namespaces").then().statusCode(403);
}
get(AwsRequestSigner.signedAs("test", "test", "glue"), "/iceberg/v1/config").then().statusCode(200)
.body("overrides.prefix", equalTo("catalogs/:"));
}
private Response get(AwsRequestSigner signer, String path) throws Exception {
URI uri = endpoint.resolve(path);
return given().urlEncodingEnabled(false).headers(signer.headersFor("GET", uri, Map.of(), new byte[0]))
.request("GET", uri);
}
}
@@ -0,0 +1,221 @@
package io.floci.aws.services.glue.iceberg;
import io.floci.aws.services.glue.GlueService;
import io.floci.aws.services.glue.model.Table;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.testutil.AwsRequestSigner;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* AWS Glue's Iceberg REST endpoint as a REST catalog client (Spark, PyIceberg) uses it, signed for {@code glue}: a
* staged create committed with {@code assert-create}, as DuckDB and Spark create tables, then snapshot commits that
* move the Glue table's {@code metadata_location}, one based on a stale snapshot refused.
*/
@QuarkusTest
class GlueIcebergRestIntegrationTest {
private static final String PREFIX = "/iceberg/v1/catalogs/000000000000";
private static final String SCHEMA = """
{"type":"struct","schema-id":0,"fields":[{"id":1,"name":"id","required":false,"type":"long"},
{"id":2,"name":"name","required":false,"type":"string"}]}""";
private final AwsRequestSigner glue = AwsRequestSigner.signedAs("test", "test", "glue");
@TestHTTPResource("/")
URI endpoint;
@Inject
S3Service s3Service;
@Inject
GlueService glueService;
private String bucket;
private String namespace;
@BeforeEach
void createBucket() {
long suffix = System.nanoTime();
bucket = "iceberg-rest-" + suffix;
namespace = "lake_" + suffix;
s3Service.createBucket(bucket, "us-east-1");
}
@AfterEach
void dropNamespace() {
send(glue, "DELETE", PREFIX + "/namespaces/" + namespace + "/tables/events", null);
send(glue, "DELETE", PREFIX + "/namespaces/" + namespace, null);
}
private String tablePath() {
return PREFIX + "/namespaces/" + namespace + "/tables/events";
}
private void createNamespace() {
send(glue, "POST", PREFIX + "/namespaces", "{\"namespace\":[\"" + namespace + "\"],\"properties\":"
+ "{\"location\":\"s3://" + bucket + "/lake\",\"owner\":\"data\"}}").then().statusCode(200)
.body("namespace[0]", equalTo(namespace));
}
private String createTable() {
send(glue, "POST", PREFIX + "/namespaces/" + namespace + "/tables", "{\"stage-create\":true,\"name\":\"events\","
+ "\"schema\":" + SCHEMA + ",\"properties\":{\"format-version\":\"2\"}}").then().statusCode(200)
.body("metadata.location", equalTo("s3://" + bucket + "/lake/events"))
.body("metadata-location", nullValue());
return send(glue, "POST", tablePath(), """
{"requirements":[{"type":"assert-create"}],"updates":[
{"action":"assign-uuid","uuid":"11111111-2222-3333-4444-555555555555"},
{"action":"upgrade-format-version","format-version":2},
{"action":"add-schema","last-column-id":2,"schema":%s},
{"action":"add-spec","spec":{"spec-id":0,"fields":[]}},{"action":"set-default-spec","spec-id":0},
{"action":"add-sort-order","sort-order":{"order-id":0,"fields":[]}},
{"action":"set-default-sort-order","sort-order-id":0},
{"action":"set-location","location":"s3://%s/lake/events"},
{"action":"set-properties","updates":{"format-version":"2"}},
{"action":"set-current-schema","schema-id":0}]}
""".formatted(SCHEMA, bucket)).then().statusCode(200)
.body("metadata-location", endsWith(".metadata.json"))
.extract().path("metadata-location");
}
private static String snapshotCommit(long snapshotId, Long parent) {
return IcebergCommits.snapshotCommit(snapshotId, parent, snapshotId);
}
@Test
void configNamesTheCatalogsPrefixAndTheRoutesItServes() {
send(glue, "GET", "/iceberg/v1/config?warehouse=000000000000", null).then().statusCode(200)
.body("overrides.prefix", equalTo("catalogs/000000000000"))
.body("endpoints", hasItem("POST /v1/{prefix}/namespaces/{namespace}/tables/{table}"));
send(glue, "GET", "/iceberg/v1/config", null).then().statusCode(200)
.body("overrides.prefix", equalTo("catalogs/:"));
send(glue, "GET", "/iceberg/v1/config?warehouse=111122223333", null).then().statusCode(400)
.body("error.type", equalTo("BadRequestException"));
}
@Test
void aStagedCreateIsCommittedAsAGlueIcebergTableWhoseMetadataLocationEachCommitMoves() throws Exception {
createNamespace();
send(glue, "GET", PREFIX + "/namespaces/" + namespace, null).then().statusCode(200)
.body("properties.location", equalTo("s3://" + bucket + "/lake"))
.body("properties.owner", equalTo("data"));
String created = createTable();
Table table = glueService.getTable(namespace, "events");
assertEquals("ICEBERG", table.getParameters().get("table_type"));
assertEquals(created, table.getParameters().get("metadata_location"));
assertEquals(List.of("id:bigint", "name:string"), table.getStorageDescriptor().getColumns().stream()
.map(column -> column.getName() + ":" + column.getType()).toList());
assertTrue(created.contains("/lake/events/metadata/00000-"), created);
String stored = new String(s3Service.openObjectStream(bucket,
created.substring(("s3://" + bucket + "/").length()), null).readAllBytes(), StandardCharsets.UTF_8);
assertTrue(stored.contains("11111111-2222-3333-4444-555555555555"), stored);
String committed = send(glue, "POST", tablePath(), snapshotCommit(7, null)).then().statusCode(200)
.body("metadata.current-snapshot-id", equalTo(7))
.body("metadata.metadata-log[0].metadata-file", equalTo(created))
.extract().path("metadata-location");
assertTrue(committed.contains("/metadata/00001-"), committed);
Table updated = glueService.getTable(namespace, "events");
assertEquals(committed, updated.getParameters().get("metadata_location"));
assertEquals(created, updated.getParameters().get("previous_metadata_location"));
send(glue, "GET", tablePath(), null).then().statusCode(200)
.body("metadata-location", equalTo(committed))
.body("metadata.refs.main.snapshot-id", equalTo(7));
send(glue, "HEAD", tablePath(), null).then().statusCode(204);
send(glue, "GET", PREFIX + "/namespaces/" + namespace + "/tables", null).then().statusCode(200)
.body("identifiers.name", hasItem("events"));
}
@Test
void aCommitBasedOnAStaleSnapshotIsRefusedAndLeavesTheTableAsItWas() {
createNamespace();
createTable();
String first = send(glue, "POST", tablePath(), snapshotCommit(7, null)).then().statusCode(200)
.extract().path("metadata-location");
send(glue, "POST", tablePath(), snapshotCommit(8, null)).then().statusCode(409)
.body("error.type", equalTo("CommitFailedException"));
assertEquals(first, glueService.getTable(namespace, "events").getParameters().get("metadata_location"));
send(glue, "POST", tablePath(), snapshotCommit(8, 7L)).then().statusCode(200)
.body("metadata.current-snapshot-id", equalTo(8));
}
@Test
void missingTablesAndNamespacesAnswerTheIcebergErrors() {
send(glue, "GET", PREFIX + "/namespaces/" + namespace + "/tables/events", null).then().statusCode(404)
.body("error.type", equalTo("NoSuchNamespaceException"));
createNamespace();
send(glue, "GET", tablePath(), null).then().statusCode(404)
.body("error.type", equalTo("NoSuchTableException"));
send(glue, "POST", tablePath(), snapshotCommit(7, null)).then().statusCode(404)
.body("error.type", equalTo("NoSuchTableException"));
createTable();
send(glue, "DELETE", PREFIX + "/namespaces/" + namespace, null).then().statusCode(409)
.body("error.type", equalTo("NamespaceNotEmptyException"));
send(glue, "DELETE", tablePath(), null).then().statusCode(204);
send(glue, "GET", tablePath(), null).then().statusCode(404);
}
@Test
void namespacePropertiesAreUpdatedAndRemovedAsGlueDatabaseFields() {
createNamespace();
send(glue, "POST", PREFIX + "/namespaces/" + namespace + "/properties",
"{\"removals\":[\"owner\",\"missing-key\"],\"updates\":{\"comment\":\"raw events\",\"team\":\"x\"}}")
.then().statusCode(200)
.body("removed", equalTo(List.of("owner")))
.body("missing", equalTo(List.of("missing-key")))
.body("updated", hasItem("comment"));
assertEquals("raw events", glueService.getDatabase(namespace).getDescription());
assertEquals(Map.of("team", "x"), glueService.getDatabase(namespace).getParameters());
}
@Test
void onlyARequestSignedForGlueReachesTheEndpoint() {
AwsRequestSigner s3 = AwsRequestSigner.signedAs("test", "test", "s3");
send(s3, "GET", "/iceberg/v1/config", null).then().statusCode(not(equalTo(200)))
.body(not(containsString("overrides")));
}
private Response send(AwsRequestSigner signer, String method, String path, String body) {
URI uri = endpoint.resolve(path);
byte[] bytes = body == null ? new byte[0] : body.getBytes(StandardCharsets.UTF_8);
try {
RequestSpecification request = given().urlEncodingEnabled(false)
.headers(signer.headersFor(method, uri, Map.of(), bytes));
if (body != null) {
request = request.contentType("application/json").body(bytes);
}
return request.request(method, uri);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
@@ -0,0 +1,24 @@
package io.floci.aws.services.glue.iceberg;
/** The commit bodies the Iceberg catalog tests send, as an Iceberg writer builds them. */
final class IcebergCommits {
private IcebergCommits() {
}
/**
* An append committing snapshot {@code snapshotId} to {@code main}, required to find {@code main} at
* {@code parentSnapshotId} (absent when null), which is also the new snapshot's parent.
*/
static String snapshotCommit(long snapshotId, Long parentSnapshotId, long sequenceNumber) {
String parent = parentSnapshotId == null ? "" : "\"parent-snapshot-id\":" + parentSnapshotId + ",";
return """
{"requirements":[{"type":"assert-ref-snapshot-id","ref":"main","snapshot-id":%s}],"updates":[
{"action":"add-snapshot","snapshot":{"snapshot-id":%d,%s"sequence-number":%d,"timestamp-ms":5000,
"manifest-list":"s3://lake-bucket/lake/events/metadata/snap-%d.avro",
"summary":{"operation":"append"},"schema-id":0}},
{"action":"set-snapshot-ref","ref-name":"main","type":"branch","snapshot-id":%d}]}
""".formatted(parentSnapshotId == null ? "null" : parentSnapshotId, snapshotId, parent, sequenceNumber,
snapshotId, snapshotId);
}
}
@@ -0,0 +1,244 @@
package io.floci.aws.services.glue.iceberg;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class IcebergTableMetadataTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
/** The commit DuckDB 1.5.4 sends after a staged create of {@code (id BIGINT, name VARCHAR)}. */
private static final String DUCKDB_CREATE_COMMIT = """
{"requirements":[{"type":"assert-create"}],"updates":[
{"action":"assign-uuid","uuid":"11111111-2222-3333-4444-555555555555"},
{"action":"upgrade-format-version","format-version":2},
{"action":"add-schema","last-column-id":2,"schema":{"type":"struct","schema-id":0,"fields":[
{"id":1,"name":"id","required":false,"type":"long"},
{"id":2,"name":"name","required":false,"type":"string"}],"identifier-field-ids":[]}},
{"action":"add-spec","spec":{"spec-id":0,"fields":[]}},
{"action":"set-default-spec","spec-id":0},
{"action":"add-sort-order","sort-order":{"order-id":0,"fields":[]}},
{"action":"set-default-sort-order","sort-order-id":0},
{"action":"set-location","location":"s3://lake-bucket/lake/events"},
{"action":"set-properties","updates":{"format-version":"2"}},
{"action":"set-current-schema","schema-id":0}],
"identifier":{"name":"events","namespace":["lake"]}}
""";
private static JsonNode json(String text) throws Exception {
return MAPPER.readTree(text);
}
private static ObjectNode created() throws Exception {
JsonNode commit = json(DUCKDB_CREATE_COMMIT);
IcebergTableMetadata.check(null, commit.path("requirements"));
ObjectNode metadata = IcebergTableMetadata.empty(1_000L);
IcebergTableMetadata.apply(metadata, commit.path("updates"), 2_000L);
return metadata;
}
private static JsonNode snapshotCommit(long snapshotId, Long parentRefId, long sequence) throws Exception {
return json(IcebergCommits.snapshotCommit(snapshotId, parentRefId, sequence));
}
@Test
void duckdbsStagedCreateCommitBuildsTheTablesMetadata() throws Exception {
ObjectNode metadata = created();
assertEquals("11111111-2222-3333-4444-555555555555", metadata.path("table-uuid").asText());
assertEquals(2, metadata.path("format-version").asInt());
assertEquals(0, metadata.path("current-schema-id").asInt());
assertEquals(2, metadata.path("last-column-id").asInt());
assertEquals("long", IcebergTableMetadata.currentSchema(metadata).path("fields").get(0).path("type").asText());
assertEquals(0, metadata.path("default-spec-id").asInt());
assertEquals(999, metadata.path("last-partition-id").asInt());
assertEquals(0, metadata.path("default-sort-order-id").asInt());
assertEquals("s3://lake-bucket/lake/events", metadata.path("location").asText());
assertEquals("2", metadata.path("properties").path("format-version").asText());
assertEquals(2_000L, metadata.path("last-updated-ms").asLong());
}
@Test
void aSnapshotOnMainBecomesTheCurrentSnapshotAndIsLogged() throws Exception {
ObjectNode metadata = created();
JsonNode commit = snapshotCommit(7L, null, 1);
IcebergTableMetadata.check(metadata, commit.path("requirements"));
IcebergTableMetadata.apply(metadata, commit.path("updates"), 6_000L);
assertEquals(7L, metadata.path("current-snapshot-id").asLong());
assertEquals(1L, metadata.path("last-sequence-number").asLong());
assertEquals(7L, metadata.path("refs").path("main").path("snapshot-id").asLong());
assertEquals("branch", metadata.path("refs").path("main").path("type").asText());
assertEquals(1, metadata.path("snapshots").size());
assertEquals(5_000L, metadata.path("snapshot-log").get(0).path("timestamp-ms").asLong());
}
@Test
void aCommitBasedOnAStaleSnapshotOrAnExistingTableFails() throws Exception {
ObjectNode metadata = created();
JsonNode first = snapshotCommit(7L, null, 1);
IcebergTableMetadata.apply(metadata, first.path("updates"), 6_000L);
IcebergRestException concurrentAppend = assertThrows(IcebergRestException.class,
() -> IcebergTableMetadata.check(metadata, snapshotCommit(8L, null, 2).path("requirements")));
IcebergRestException staleParent = assertThrows(IcebergRestException.class,
() -> IcebergTableMetadata.check(metadata, snapshotCommit(9L, 6L, 2).path("requirements")));
IcebergRestException existing = assertThrows(IcebergRestException.class,
() -> IcebergTableMetadata.check(metadata, json(DUCKDB_CREATE_COMMIT).path("requirements")));
assertEquals("CommitFailedException", concurrentAppend.type());
assertEquals(409, staleParent.code());
assertEquals("CommitFailedException", existing.type());
IcebergTableMetadata.check(metadata, snapshotCommit(8L, 7L, 2).path("requirements"));
}
@Test
void propertiesSnapshotsAndRefsCanBeRemoved() throws Exception {
ObjectNode metadata = created();
IcebergTableMetadata.apply(metadata, snapshotCommit(7L, null, 1).path("updates"), 6_000L);
IcebergTableMetadata.apply(metadata, json("""
[{"action":"set-properties","updates":{"write.format.default":"parquet"}},
{"action":"remove-properties","removals":["format-version"]},
{"action":"remove-snapshot-ref","ref-name":"main"},
{"action":"remove-snapshots","snapshot-ids":[7]}]
"""), 7_000L);
assertEquals("parquet", metadata.path("properties").path("write.format.default").asText());
assertTrue(metadata.path("properties").path("format-version").isMissingNode());
assertTrue(metadata.path("refs").path("main").isMissingNode());
assertEquals(0, metadata.path("snapshots").size());
assertEquals(0, metadata.path("snapshot-log").size());
}
@Test
void removingMainOrItsSnapshotLeavesNoCurrentSnapshotAndNoDanglingRef() throws Exception {
ObjectNode metadata = created();
IcebergTableMetadata.apply(metadata, snapshotCommit(7L, null, 1).path("updates"), 6_000L);
IcebergTableMetadata.apply(metadata,
json("[{\"action\":\"set-snapshot-ref\",\"ref-name\":\"audit\",\"type\":\"tag\",\"snapshot-id\":7}]"),
6_500L);
IcebergTableMetadata.apply(metadata, json("[{\"action\":\"remove-snapshots\",\"snapshot-ids\":[7]}]"), 7_000L);
assertEquals(-1L, metadata.path("current-snapshot-id").asLong());
assertTrue(metadata.path("refs").isEmpty(), metadata.path("refs").toString());
ObjectNode other = created();
IcebergTableMetadata.apply(other, snapshotCommit(7L, null, 1).path("updates"), 6_000L);
IcebergTableMetadata.apply(other, json("[{\"action\":\"remove-snapshot-ref\",\"ref-name\":\"main\"}]"), 7_000L);
assertEquals(-1L, other.path("current-snapshot-id").asLong());
}
@Test
void aSchemaSpecOrSortOrderIdTheTableDoesNotHaveIsRefused() throws Exception {
ObjectNode metadata = created();
for (String update : new String[] {"{\"action\":\"set-current-schema\",\"schema-id\":999}",
"{\"action\":\"set-current-schema\",\"schema-id\":-1}",
"{\"action\":\"set-default-spec\",\"spec-id\":5}",
"{\"action\":\"set-default-sort-order\",\"sort-order-id\":-1}"}) {
IcebergRestException e = assertThrows(IcebergRestException.class,
() -> IcebergTableMetadata.apply(metadata, json("[" + update + "]"), 8_000L), update);
assertEquals("BadRequestException", e.type(), update);
}
assertEquals(0, metadata.path("current-schema-id").asInt());
}
@Test
void anAddedSchemaReusesAnIdenticalOneAndNeverRewritesAnExistingId() throws Exception {
ObjectNode metadata = created();
String changed = "[{\"action\":\"add-schema\",\"schema\":{\"type\":\"struct\",\"schema-id\":0,\"fields\":["
+ "{\"id\":1,\"name\":\"id\",\"required\":false,\"type\":\"long\"},"
+ "{\"id\":2,\"name\":\"name\",\"required\":false,\"type\":\"string\"},"
+ "{\"id\":3,\"name\":\"tag\",\"required\":false,\"type\":\"string\"}],\"identifier-field-ids\":[]}},"
+ "{\"action\":\"set-current-schema\",\"schema-id\":-1}]";
IcebergTableMetadata.apply(metadata, json(changed), 8_000L);
IcebergTableMetadata.apply(metadata, json(changed), 9_000L);
assertEquals(2, metadata.path("schemas").size());
assertEquals(2, metadata.path("schemas").get(0).path("fields").size(), "schema 0 is left as it was");
assertEquals(1, metadata.path("current-schema-id").asInt());
assertEquals(3, metadata.path("last-column-id").asInt());
}
@Test
void aSnapshotAfterExpiryStillComesAfterEverySequenceNumberUsed() throws Exception {
ObjectNode metadata = created();
IcebergTableMetadata.apply(metadata, snapshotCommit(7L, null, 1).path("updates"), 6_000L);
IcebergTableMetadata.apply(metadata, snapshotCommit(8L, 7L, 2).path("updates"), 6_100L);
IcebergTableMetadata.apply(metadata, json("[{\"action\":\"remove-snapshots\",\"snapshot-ids\":[7]}]"), 6_200L);
IcebergRestException e = assertThrows(IcebergRestException.class, () -> IcebergTableMetadata.apply(metadata,
snapshotCommit(9L, 8L, 2).path("updates"), 6_300L));
assertEquals("BadRequestException", e.type());
IcebergTableMetadata.apply(metadata, snapshotCommit(9L, 8L, 3).path("updates"), 6_400L);
assertEquals(3L, metadata.path("last-sequence-number").asLong());
}
@Test
void aVersionThreeSnapshotTakesTheNextRowIdsAndAdvancesThem() throws Exception {
ObjectNode metadata = created();
IcebergTableMetadata.apply(metadata, json("[{\"action\":\"upgrade-format-version\",\"format-version\":3}]"),
6_000L);
IcebergTableMetadata.apply(metadata, json("""
[{"action":"add-snapshot","snapshot":{"snapshot-id":7,"sequence-number":1,"timestamp-ms":5000,
"manifest-list":"s3://b/m.avro","summary":{"operation":"append"},"added-rows":10}}]
"""), 7_000L);
assertEquals(0L, metadata.path("snapshots").get(0).path("first-row-id").asLong());
assertEquals(10L, metadata.path("next-row-id").asLong());
}
@Test
void aCreateRequestBecomesTheSameMetadataItsUpdatesWould() throws Exception {
ObjectNode metadata = IcebergTableMetadata.forCreate(json("""
{"name":"events","schema":{"type":"struct","schema-id":0,"fields":[
{"id":1,"name":"id","required":true,"type":"long"},
{"id":2,"name":"tags","required":false,"type":{"type":"list","element-id":3,"element":"string",
"element-required":false}}]},
"partition-spec":{"spec-id":0,"type":"struct","fields":[
{"name":"id_bucket","transform":"bucket[4]","source-id":1,"field-id":1000}]},
"properties":{"format-version":"2","owner":"lake"}}
"""), "s3://lake-bucket/lake/events", 3_000L);
assertEquals(3, metadata.path("last-column-id").asInt());
assertEquals(1000, metadata.path("last-partition-id").asInt());
assertTrue(metadata.path("partition-specs").get(0).path("type").isMissingNode());
assertEquals("lake", metadata.path("properties").path("owner").asText());
assertEquals("s3://lake-bucket/lake/events", metadata.path("location").asText());
}
@Test
void anUpdateTheCatalogDoesNotApplyIsRefused() throws Exception {
ObjectNode metadata = created();
IcebergRestException e = assertThrows(IcebergRestException.class, () -> IcebergTableMetadata.apply(metadata,
json("[{\"action\":\"add-encryption-key\",\"encryption-key\":{}}]"), 1L));
assertEquals("BadRequestException", e.type());
assertEquals(400, e.code());
}
@Test
void hiveTypesSpellOutNestedIcebergTypes() throws Exception {
assertEquals("bigint", IcebergTypes.hiveType(json("\"long\"")));
assertEquals("decimal(10,2)", IcebergTypes.hiveType(json("\"decimal(10, 2)\"")));
assertEquals("struct<a:int,b:array<string>>", IcebergTypes.hiveType(json("""
{"type":"struct","fields":[{"id":1,"name":"a","type":"int"},
{"id":2,"name":"b","type":{"type":"list","element-id":3,"element":"string"}}]}
""")));
assertEquals("map<string,timestamp>", IcebergTypes.hiveType(json("""
{"type":"map","key-id":1,"key":"string","value-id":2,"value":"timestamptz"}
""")));
}
}