This is an automated email from the ASF dual-hosted git repository. github-actions[bot] pushed a commit to branch cherry-pick-8985ffad-to-branch-1.3 in repository https://gitbox.apache.org/repos/asf/gravitino.git
commit 3713eb45c4770ac031f7740ab167a159048c3b2e Author: Qi Yu <[email protected]> AuthorDate: Wed Nov 11 14:37:33 2026 +0800 [#13696] fix(lance): require catalog opt-in to purge external datasets (#14870) ### What changes were proposed in this pull request? Add the catalog-only `lance.allow-external-table-purge` property, defaulting to `false`. Reject external or registered Lance table purges before removing metadata or deleting files, including Lance REST drop and create-overwrite of an existing external table. Table properties cannot enable the policy. ### Why are the changes needed? A caller can own a table registered at another table's location, or created at a parent directory containing other datasets. Table ownership alone does not authorize deleting that data. This provides a default deletion guard; location ownership and storage authorization remain follow-up work in #14788. Refs #13696, #14788. ### Does this PR introduce _any_ user-facing change? Yes. External purge is disabled by default; Lance REST returns HTTP 406. Catalog administrators must explicitly opt in to retain destructive drop/overwrite behavior. The opt-in does not validate location ownership. Metadata-only drop/deregister and managed-table deletion remain unchanged. ### How was this patch tested? - 201 focused unit tests and 48 embedded integration tests passed, covering policy defaults, table-property bypass attempts, legacy registrations, overwrite, provider callbacks, and catalog opt-in. - Two authenticated cross-user HTTP regression cases reproduce #13696. Both fail with HTTP 200 when the guard is removed and pass with HTTP 406 while preserving readable victim datasets when restored. - Scoped Spotless checks and `git diff --check` passed. No Docker or remote object-store tests were run. # Conflicts: # catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogPropertiesMetadata.java # catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/lance/LanceTableOperations.java # catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java # catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestPropertiesMetadata.java # docs/lakehouse-generic-catalog.md # docs/lakehouse-generic-lance-table.md # lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceRESTServiceIT.java # lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceTableAuthorizationIT.java --- .../generic/GenericCatalogPropertiesMetadata.java | 23 ++ .../lakehouse/lance/LanceTableOperations.java | 18 ++ .../generic/TestGenericCatalogOperations.java | 13 +- .../lakehouse/generic/TestPropertiesMetadata.java | 34 +++ .../lakehouse/lance/TestLanceTableOperations.java | 107 ++++++++- .../test/CatalogGenericCatalogLanceIT.java | 2 + docs/lakehouse-generic-catalog.md | 250 +++++++++++++++++++++ docs/lakehouse-generic-lance-table.md | 29 ++- docs/lance-rest-service.md | 15 +- .../lance/common/utils/LanceConstants.java | 3 + .../lance/integration/test/LanceRESTServiceIT.java | 33 ++- .../test/LanceTableAuthorizationIT.java | 76 ++++++- 12 files changed, 590 insertions(+), 13 deletions(-) diff --git a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogPropertiesMetadata.java b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogPropertiesMetadata.java index 7bd6f58605..f3a0fbae98 100644 --- a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogPropertiesMetadata.java +++ b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogPropertiesMetadata.java @@ -19,9 +19,11 @@ package org.apache.gravitino.catalog.lakehouse.generic; +import static org.apache.gravitino.connector.PropertyEntry.booleanPropertyEntry; import static org.apache.gravitino.connector.PropertyEntry.enumPropertyEntry; import static org.apache.gravitino.connector.PropertyEntry.stringOptionalPropertyEntry; import static org.apache.gravitino.connector.PropertyEntry.stringOptionalPropertyPrefixEntry; +import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_ALLOW_EXTERNAL_TABLE_PURGE; import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_SCHEMA_REFRESH_MODE; import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_STORAGE_OPTIONS_PREFIX; @@ -54,6 +56,27 @@ public class GenericCatalogPropertiesMetadata extends BaseCatalogPropertiesMetad null, /* defaultValue */ false /* hidden */, false /* reserved */), +<<<<<<< HEAD +======= + stringOptionalPropertyEntry( + TABLE_LOCATION_PROVIDER, + "The name of the table location provider that provisions and unprovisions the" + + " locations of this catalog's tables. It is fixed when the catalog is" + + " created, because switching it would leave the tables of a single catalog" + + " spread over two different location schemes.", + true /* immutable */, + DefaultTableLocationProvider.NAME, /* defaultValue */ + false /* hidden */), + booleanPropertyEntry( + LANCE_ALLOW_EXTERNAL_TABLE_PURGE, + "Allow physical deletion of external and registered Lance datasets. Table" + + " properties cannot enable this catalog-level policy.", + false /* required */, + false /* immutable */, + false /* defaultValue */, + false /* hidden */, + false /* reserved */), +>>>>>>> 8985ffad6 ([#13696] fix(lance): require catalog opt-in to purge external datasets (#14870)) enumPropertyEntry( LANCE_SCHEMA_REFRESH_MODE, "Controls when Lance table schemas are refreshed from the underlying dataset.", diff --git a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/lance/LanceTableOperations.java b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/lance/LanceTableOperations.java index 30aae6f356..b542c8bb65 100644 --- a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/lance/LanceTableOperations.java +++ b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/lance/LanceTableOperations.java @@ -18,6 +18,7 @@ */ package org.apache.gravitino.catalog.lakehouse.lance; +import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_ALLOW_EXTERNAL_TABLE_PURGE; import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_CREATION_MODE; import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_TABLE_REGISTER; import static org.apache.gravitino.rel.Column.DEFAULT_VALUE_NOT_SET; @@ -280,6 +281,14 @@ public class LanceTableOperations extends ManagedTableOperations { // dataset) for a table that is about to be deleted anyway. Table table = super.loadTable(ident); boolean external = LancePropertiesUtils.isExternalTable(table.properties()); + if (external + && !Boolean.parseBoolean(catalogProperties.get(LANCE_ALLOW_EXTERNAL_TABLE_PURGE))) { + throw new UnsupportedOperationException( + "Purging external Lance tables is disabled. Use dropTable or Lance REST deregister" + + " to remove metadata only. A catalog administrator may enable " + + LANCE_ALLOW_EXTERNAL_TABLE_PURGE + + " to allow physical deletion of external data."); + } // NOTE: the two steps below (metadata removal and dataset deletion) are NOT atomic. // If the process crashes between them, the entity-store record will be gone but the @@ -302,6 +311,15 @@ public class LanceTableOperations extends ManagedTableOperations { } catch (NoSuchTableException e) { return false; +<<<<<<< HEAD +======= + } catch (IllegalArgumentException | UnsupportedOperationException e) { + throw e; + } catch (OptimisticLockException e) { + // The table metadata conflicted with a concurrent writer, e.g. a lock wait timeout, and was + // not changed, so the dataset is kept and the operation can be retried. + throw e; +>>>>>>> 8985ffad6 ([#13696] fix(lance): require catalog opt-in to purge external datasets (#14870)) } catch (Exception e) { throw ExceptionMessages.wrap("Failed to purge Lance dataset for table " + ident, e); } diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java index 8d6c25795a..8776ea3e4d 100644 --- a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java +++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java @@ -41,7 +41,6 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import java.io.File; import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.time.Instant; import java.util.Arrays; @@ -260,13 +259,19 @@ public class TestGenericCatalogOperations { store.put(entity, false); if ("purge".equals(operation)) { +<<<<<<< HEAD Assertions.assertTrue(lanceOps.purgeTable(ident)); +======= + Assertions.assertThrowsExactly( + UnsupportedOperationException.class, () -> opsWithFakeProvider.purgeTable(ident)); +>>>>>>> 8985ffad6 ([#13696] fix(lance): require catalog opt-in to purge external datasets (#14870)) } else if ("cascade".equals(operation)) { Assertions.assertTrue(lanceOps.dropSchema(schemaIdent, true)); } else { Assertions.assertTrue(lanceOps.dropTable(ident)); } +<<<<<<< HEAD Assertions.assertFalse(lanceOps.tableExists(ident)); if ("purge".equals(operation)) { Assertions.assertFalse(Files.exists(lanceDataDir.resolve("legacy/_versions"))); @@ -274,6 +279,12 @@ public class TestGenericCatalogOperations { try (Dataset dataset = Dataset.open().uri(location).build()) { Assertions.assertEquals("id", dataset.getSchema().getFields().get(0).getName()); } +======= + Assertions.assertEquals("purge".equals(operation), opsWithFakeProvider.tableExists(ident)); + Assertions.assertTrue(FakeTableLocationProvider.unprovisioned().isEmpty()); + try (Dataset dataset = Dataset.open().uri(location).build()) { + Assertions.assertEquals("id", dataset.getSchema().getFields().get(0).getName()); +>>>>>>> 8985ffad6 ([#13696] fix(lance): require catalog opt-in to purge external datasets (#14870)) } } diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestPropertiesMetadata.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestPropertiesMetadata.java index a57474be2e..3deae6b303 100644 --- a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestPropertiesMetadata.java +++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestPropertiesMetadata.java @@ -19,6 +19,8 @@ package org.apache.gravitino.catalog.lakehouse.generic; +import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_ALLOW_EXTERNAL_TABLE_PURGE; + import com.google.common.collect.ImmutableMap; import java.util.Map; import org.apache.gravitino.Schema; @@ -38,6 +40,38 @@ public class TestPropertiesMetadata { } @Test +<<<<<<< HEAD +======= + void testTableLocationProviderPropertyIsImmutableWithDefault() { + PropertiesMetadata catalogPropertiesMetadata = genericCatalog.catalogPropertiesMetadata(); + + Assertions.assertTrue( + catalogPropertiesMetadata.containsProperty( + GenericCatalogPropertiesMetadata.TABLE_LOCATION_PROVIDER)); + Assertions.assertEquals( + DefaultTableLocationProvider.NAME, + catalogPropertiesMetadata.getOrDefault( + ImmutableMap.of(), GenericCatalogPropertiesMetadata.TABLE_LOCATION_PROVIDER)); + Assertions.assertTrue( + catalogPropertiesMetadata.isImmutableProperty( + GenericCatalogPropertiesMetadata.TABLE_LOCATION_PROVIDER)); + } + + @Test + void testExternalPurgePolicyDefaultsToDisabledAndCanBeChangedAtCatalogLevel() { + PropertiesMetadata metadata = genericCatalog.catalogPropertiesMetadata(); + Assertions.assertTrue(metadata.containsProperty(LANCE_ALLOW_EXTERNAL_TABLE_PURGE)); + Assertions.assertEquals( + false, metadata.getOrDefault(Map.of(), LANCE_ALLOW_EXTERNAL_TABLE_PURGE)); + Assertions.assertEquals( + true, + metadata.getOrDefault( + Map.of(LANCE_ALLOW_EXTERNAL_TABLE_PURGE, "true"), LANCE_ALLOW_EXTERNAL_TABLE_PURGE)); + Assertions.assertFalse(metadata.isImmutableProperty(LANCE_ALLOW_EXTERNAL_TABLE_PURGE)); + } + + @Test +>>>>>>> 8985ffad6 ([#13696] fix(lance): require catalog opt-in to purge external datasets (#14870)) void testCatalogPropertiesMetadata() { PropertiesMetadata catalogPropertiesMetadata = genericCatalog.catalogPropertiesMetadata(); Assertions.assertNotNull(catalogPropertiesMetadata); diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/TestLanceTableOperations.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/TestLanceTableOperations.java index 1aec39b551..4b9c1b75e0 100644 --- a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/TestLanceTableOperations.java +++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/TestLanceTableOperations.java @@ -18,6 +18,7 @@ */ package org.apache.gravitino.catalog.lakehouse.lance; +import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_ALLOW_EXTERNAL_TABLE_PURGE; import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_CREATION_MODE; import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_SCHEMA_REFRESH_MODE; import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_STORAGE_OPTIONS_PREFIX; @@ -159,7 +160,7 @@ public class TestLanceTableOperations { } } - /** Legacy registration flags also protect drop and overwrite, while purge remains destructive. */ + /** Legacy registrations retain their data unless the catalog explicitly permits purging it. */ @ParameterizedTest @CsvSource( value = { @@ -224,17 +225,111 @@ public class TestLanceTableOperations { new Index[0])); Assertions.assertEquals("true", replaced.properties().get(Table.PROPERTY_EXTERNAL)); } else if ("purge".equals(operation)) { - Assertions.assertTrue(lanceTableOps.purgeTable(ident)); + Assertions.assertThrowsExactly( + UnsupportedOperationException.class, () -> lanceTableOps.purgeTable(ident)); } else { Assertions.assertTrue(lanceTableOps.dropTable(ident)); } - verify(store).delete(ident, Entity.EntityType.TABLE); - if ("purge".equals(operation)) { - Assertions.assertFalse(Files.exists(Paths.get(location, "_versions"))); - } else { + verify(store, Mockito.times("purge".equals(operation) ? 0 : 1)) + .delete(ident, Entity.EntityType.TABLE); + try (Dataset dataset = Dataset.open().uri(location).build()) { + Assertions.assertEquals("id", dataset.getSchema().getFields().get(0).getName()); + } + } + + @ParameterizedTest + @CsvSource( + value = {"true,NULL", "true,false", "true,true", "false,NULL", "false,false", "false,true"}, + nullValues = "NULL") + void testPurgeRequiresCatalogPermissionForExternalData(boolean external, String catalogPermission) + throws Exception { + NameIdentifier ident = NameIdentifier.of("schema", "purge_policy"); + String location = tempDir.resolve("purge_policy").toString(); + try (Dataset ignored = + lanceTableOps.createDataset( + location, new Column[] {Column.of("id", Types.IntegerType.get())}, Map.of())) { + // Purge must preserve both a real dataset and its metadata when the policy rejects it. + } + Map<String, String> properties = + Map.of( + Table.PROPERTY_TABLE_FORMAT, + "lance", + Table.PROPERTY_LOCATION, + location, + Table.PROPERTY_EXTERNAL, + Boolean.toString(external), + LANCE_ALLOW_EXTERNAL_TABLE_PURGE, + "true"); + when(store.get(eq(ident), eq(Entity.EntityType.TABLE), eq(TableEntity.class))) + .thenReturn(tableEntity(ident, List.of(), properties)); + when(store.delete(ident, Entity.EntityType.TABLE)).thenReturn(true); + if (catalogPermission != null) { + lanceTableOps.setCatalogProperties( + Map.of(LANCE_ALLOW_EXTERNAL_TABLE_PURGE, catalogPermission)); + } + + if (external && !Boolean.parseBoolean(catalogPermission)) { + UnsupportedOperationException error = + Assertions.assertThrowsExactly( + UnsupportedOperationException.class, () -> lanceTableOps.purgeTable(ident)); + Assertions.assertTrue(error.getMessage().contains(LANCE_ALLOW_EXTERNAL_TABLE_PURGE)); + verify(store, never()).delete(any(), any()); try (Dataset dataset = Dataset.open().uri(location).build()) { Assertions.assertEquals("id", dataset.getSchema().getFields().get(0).getName()); } + } else { + Assertions.assertTrue(lanceTableOps.purgeTable(ident)); + verify(store).delete(ident, Entity.EntityType.TABLE); + Assertions.assertFalse(Files.exists(Paths.get(location, "_versions"))); + } + } + + @Test + void testOverwriteCannotPurgeExternalDataWithoutCatalogPermission() throws Exception { + NameIdentifier ident = NameIdentifier.of("schema", "protected_table"); + String location = tempDir.resolve("protected_table").toString(); + Column[] columns = {Column.of("id", Types.IntegerType.get())}; + try (Dataset ignored = lanceTableOps.createDataset(location, columns, Map.of())) { + // The existing external dataset is not owned by this overwrite request. + } + when(store.get(eq(ident), eq(Entity.EntityType.TABLE), eq(TableEntity.class))) + .thenReturn( + tableEntity( + ident, + List.of(), + Map.of( + Table.PROPERTY_TABLE_FORMAT, + "lance", + Table.PROPERTY_LOCATION, + location, + Table.PROPERTY_EXTERNAL, + "true"))); + String replacement = tempDir.resolve("replacement").toString(); + Assertions.assertThrowsExactly( + UnsupportedOperationException.class, + () -> + lanceTableOps.createTable( + ident, + columns, + null, + Map.of( + Table.PROPERTY_TABLE_FORMAT, + "lance", + Table.PROPERTY_LOCATION, + replacement, + LANCE_CREATION_MODE, + "OVERWRITE", + LANCE_ALLOW_EXTERNAL_TABLE_PURGE, + "true"), + new Transform[0], + null, + new SortOrder[0], + new Index[0])); + verify(store, never()).delete(any(), any()); + verify(store, never()).put(any(), anyBoolean()); + Assertions.assertFalse(Files.exists(Paths.get(replacement))); + try (Dataset dataset = Dataset.open().uri(location).build()) { + Assertions.assertEquals("id", dataset.getSchema().getFields().get(0).getName()); } } diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/integration/test/CatalogGenericCatalogLanceIT.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/integration/test/CatalogGenericCatalogLanceIT.java index 277ed1ec6b..a7b9e0218a 100644 --- a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/integration/test/CatalogGenericCatalogLanceIT.java +++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/integration/test/CatalogGenericCatalogLanceIT.java @@ -680,6 +680,8 @@ public class CatalogGenericCatalogLanceIT extends BaseIT { protected void createCatalog() { Map<String, String> properties = Maps.newHashMap(); + // This suite exercises explicit data deletion, including purge and create-overwrite. + properties.put("lance.allow-external-table-purge", "true"); metalake.createCatalog(catalogName, Catalog.Type.RELATIONAL, provider, "comment", properties); catalog = metalake.loadCatalog(catalogName); diff --git a/docs/lakehouse-generic-catalog.md b/docs/lakehouse-generic-catalog.md index e5471e9831..ec4dbed87a 100644 --- a/docs/lakehouse-generic-catalog.md +++ b/docs/lakehouse-generic-catalog.md @@ -44,11 +44,261 @@ For detailed information on available operations, see [Manage Relational Metadat ### Catalog Properties +<<<<<<< HEAD | Property | Description | Example | Required | |-----------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------|----------| | `provider` | Catalog provider type | `lakehouse-generic` | Yes | | `location` | Root storage path for all schemas and tables | `s3://bucket/lakehouse` | No | | `lance.schema-refresh-mode` | Lance table schema refresh mode. `DECLARED_AND_EMPTY` (default) refreshes declared tables and tables with empty stored columns. `VERSION_CHECK` additionally refreshes when the Lance dataset version changes. | `DECLARED_AND_EMPTY` | No | +======= +| Property | Description | Example | Required | +|-----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------|----------| +| `provider` | Catalog provider type | `lakehouse-generic` | Yes | +| `location` | Root storage path for all schemas and tables | `s3://bucket/lakehouse` | No | +| `table-location-provider` | Name of the [table location provider](#pluggable-table-location-provider) that provisions and unprovisions the locations of this catalog's tables. Defaults to `default`, which resolves the location from the table, schema and catalog `location` properties as described below. Immutable once the catalog is created. | `default` | No | +| `lance.schema-refresh-mode` | Lance table schema refresh mode. `DECLARED_AND_EMPTY` (default) refreshes declared tables and tables with empty stored columns. `VERSION_CHECK` additionally refreshes when the Lance dataset version changes. | `DECLARED_AND_EMPTY` | No | +| `lance.allow-external-table-purge` | Allow physical deletion of external or registered Lance tables, including Lance REST `DropTable` and create `OVERWRITE`. Catalog-only; table properties cannot enable it. Does not validate ownership of storage locations. | `false` | No | + +#### Pluggable table location provider + +By default the catalog derives a new table's location from the `location` properties, following the +hierarchy described in [Key Property: `location`](#key-property-location). Deployments that allocate +storage through an external service can replace that logic with their own strategy. + +Implement `org.apache.gravitino.catalog.lakehouse.generic.TableLocationProvider`, register it in +`META-INF/services/org.apache.gravitino.catalog.lakehouse.generic.TableLocationProvider`, drop the jar +into `catalogs/lakehouse-generic/libs`, and select it with the `table-location-provider` catalog +property (matched case-insensitively against `TableLocationProvider#name()`). + +The interface is two operations wide -- `provisionTableLocation` and `unprovisionTableLocation` -- +plus `name()`. + +**The catalog reports; the provider decides.** The catalog's part is to hand over an accurate account +of what happened -- what the creation request asked for, where the table ended up, whether the data +under a location is gone -- and the provider's part is to decide what that account means for the +storage it manages. The catalog does not model what an implementation keeps, and an implementation is +never asked to reconstruct what the catalog or the table formats did. There is one exception, and it +is stated here as an exception rather than as the rule: an external table that is **dropped** does not +reach `unprovisionTableLocation` at all, for the reason given below. + +**Responsibilities.** A provider owns the right to use a path; the table format owns the content at +the path. The dividing line is not physical against logical -- a provider may well create real +infrastructure -- but what a thing was created for: anything brought into being so that the path can +be used belongs to the provider, and anything written into the path belongs to the format. A provider +owns its reservation, its registry entry, whatever quota or grant it books, the name itself, and any +container it created to make the path usable; a table format owns the dataset, including deleting it; +the catalog owns neither, storing the location string verbatim and sequencing the two calls. + +**Scope.** What this offers is allocation hooks plus best-effort release notification, with recovery +owned by the provider and the deployment. It is deliberately not a distributed transaction and not a +recovery system: the limitations below are real, and a provider that manages storage has to reconcile +against the catalog independently of these two calls. + +One provider instance is created per catalog, and the property is immutable, so a catalog keeps the +provider it was created with. **There is no lifecycle**: the provider is never initialized and never +closed. A provider needing a remote client should create it lazily on first use and make it safe to +abandon, since a catalog is evicted from the server's catalog cache when idle and the provider it +held is simply discarded. Both callbacks are called concurrently and must be thread-safe. + +Both callbacks receive a `TableLocationContext`, which carries `tableIdentifier()`, +`tableProperties()`, `schema()` -- the parent schema including its properties -- and +`catalogProperties()`. The last is how a provider receives configuration of its own, such as a +service endpoint or a quota group: the same map is handed to every call, so a provider that turns it +into something expensive should build that once and hold it rather than rebuilding it per table. The +`external` flag is available as the `external` entry of `tableProperties()`; read it with +`Boolean.parseBoolean`, which is how the table formats read it. Selection is per catalog, so a provider +that needs different behaviour for different schemas has to read a schema property and dispatch on it +itself. A provider doing that should reject an unrecognized value rather than falling back to another +strategy, and should treat the property as immutable: a table provisioned under one strategy has to be +unprovisioned under the same one. + +A **request that supplies its own `location` reaches the provider too**, with the supplied value +visible as the `location` entry of `context.tableProperties()`. What happens to it is the provider's +decision: return it unchanged to honour it, return something else to place the table elsewhere, or +throw to refuse the creation. A provider enforcing a placement policy exists precisely for this +request, and deciding it in the catalog would leave that provider with nothing to enforce. + +This is not a behaviour change for a catalog on the built-in provider, which returns a supplied +location verbatim as its first branch -- the same branch the catalog used to apply on its behalf. + +An implementation that allocates storage has to handle the case deliberately. In this catalog a +caller usually supplies a location because the data is already there: an external Delta table, or a +Lance registration, both of which point at a dataset that exists. Allocating a fresh path for one of +those and returning it repoints the table at an empty directory and orphans the caller's data, while +the creation still reports success. Returning the supplied value unchanged is the safe default. +Everything else reaches the provider as well, including an external table that carries no +`location`; the table format decides whether that combination is valid at all. + +`provisionTableLocation` runs on the server thread handling the table creation request. The catalog +applies no timeout, so a provider that calls a remote service must bound every call itself and fail +fast when the service is unavailable; a call that blocks holds that request thread until it returns. + +`provisionTableLocation` must return a non-blank location; the catalog rejects the table creation +otherwise. That is the only check: the shape of the path belongs to the provider, nothing downstream +appends to it, and the value is stored verbatim so that a provider unprovisioning it later sees +exactly the string it returned. + +**What the returned location promises, and what it does not.** It promises exactly one thing: that the +location is usable, meaning a table format may create its dataset there and will not be refused for +any reason under the provider's control. Whether an implementation had to reserve, register or create +anything to make that true is its own business, neither required nor forbidden. It does **not** promise +that a directory or prefix exists, that a dataset exists, or that the location is empty -- the last one +deliberately, because in this catalog a caller usually supplies a location precisely when the data is +already there. + +When a table is dropped or purged, the catalog calls `unprovisionTableLocation` so that the provider +can hand the location back. It reads the location to reclaim from `context.tableProperties()` under +the `location` key, which the catalog fills in from the stored table properties read just before the +table was removed. Dropping a schema with cascade unprovisions the location of every table it +contains, one by one, resolving the shared parent schema once for the whole cascade. + +The method has no default implementation, so every provider has to answer for it. A provider that +composes the path from configuration and registers it nowhere -- like the built-in one -- writes an +empty body. + +**What the callback releases, and what it must not touch.** A provider releases what it issued: the +reservation, the registry entry, whatever quota or grant it booked, and the name itself so that it can +be handed out again. It may also remove a container it created itself -- a prefix or a bucket it +brought into being so the path could be used -- but only after establishing that the container holds +nothing except what the provider itself put there, and it must leave the container in place otherwise. +It must **not** delete content at the location: the table format owns the lifecycle of the data and has +already deleted it on every path that reaches the callback, so deleting anything further is at best +redundant and at worst destroys data this catalog promised not to touch. + +Nothing about the location string establishes ownership on its own. The catalog supplies one fact, that +nothing anyone needs is under that location any more; whether the provider holds anything there is a +fact only the provider can establish, from its own records. + +The unprovisioning happens *after* the table metadata, and the data of a managed table, have been +removed, so a provider that fails does not roll the drop back: the table is gone either way. The +failure is logged at WARN naming the table, the provider and the location that was not reclaimed, +and the drop still reports success, because reporting a drop that did happen as unsuccessful would +only invite a retry that cannot undo anything. For the same reason a failed unprovisioning does not +abort a cascading schema drop. + +`unprovisionTableLocation` is called once per dropped table, but it is not guaranteed to be called +at all. A crash between the removal and the call skips it, and so does a failure raised inside the +drop after the metadata is already gone, which takes no crash and leaves the server running +normally. A provider reclaiming real storage needs its own reconciliation to catch both, and must +tolerate being called for a location that is already released. + +**Dropping an external table skips the callback; purging one does not.** On a drop the catalog does +not own the data — the table formats leave the dataset in place — so asking a provider to hand the +location back would invite it to delete exactly the data the catalog just promised not to touch. A +leak is recoverable and a deletion is not, so `unprovisionTableLocation` is not called when a table +whose `external` property is true is dropped. + +For Lance, an external-table purge requires `lance.allow-external-table-purge=true` in the catalog. +Without it, purge fails before removing table metadata or deleting data, and the provider callback is +not invoked. +When allowed, purge deletes the external dataset that drop leaves alone; after successful deletion, +the location is handed back. + +The callback is therefore reached in exactly three situations: a dropped managed table, a purged +managed table, and an external one whose purge was permitted by its table format. There is deliberately +no flag distinguishing them, because +the invariant they share is about the location rather than the table: **nothing anyone needs is under +the location named in the context**. In all three the table format has already deleted the data under +it. The catalog makes the drop-versus-purge and external distinctions rather than passing them on, +because the catalog is where the knowledge lives about which formats leave data in place. + +Even so, `external` is only an approximation of the rule this callback wants, which is "hand back +only what was handed out". An external table created *without* a location does get one provisioned, +because both table formats check the location only after the catalog has filled it in, so skipping +its drop leaks that allocation. + +Telling those apart exactly would need the catalog to record, per table, whether it provisioned the +location, which it does not do today. Both are why a provider reclaiming real storage needs its own +reconciliation, and why it must tolerate a location it does not recognize. + +`ManagedTableOperations.purgeTable` delegates to `dropTable`, so for a format that does not override +it the two paths remove the same things -- but Lance overrides both, and its purge deletes data its +drop does not. A provider must not assume the two are interchangeable. + +##### A worked example: a provider that allocates + +A provider backed by an external path-allocation service is the case this interface exists for, and it +makes the boundary concrete. + +On `provisionTableLocation` the provider asks the service for a path the table is permitted to use. +The service validates the request, creates on demand whatever container the path needs -- shared by +many tables, coarser than one table, and never removed for one -- records an entry in a registry +saying which table holds the path, and returns the path. The provider returns that string and nothing +else happens: no dataset is created, and the catalog stores the value verbatim. + +The table format then creates its dataset at that path, and later, when the table is dropped or +purged, deletes it. Neither step involves the provider. + +On `unprovisionTableLocation` the provider deletes the registry entry, which is also what frees the +name so the path can be issued again. The only storage object it touches is the empty directory marker +it created itself, and only after establishing that nothing else is under the prefix; if anything else +is there it leaves the prefix alone. It never deletes the dataset -- by then the format already has. + +The built-in provider is the same contract with the allocation set empty. It composes a path from +configuration, holds no reservation and no registry entry, and therefore has nothing to hand back, +which is why its `unprovisionTableLocation` body is empty. That is the correct implementation for a +provider of that shape, and it is also exactly what this catalog did before this interface existed. + +**Known limitations.** Six of them, and they all point the same way: a provider that manages real +storage needs its own reconciliation against the catalog, and cannot treat these callbacks as a +complete record of the locations it handed out. + +- `location` is a mutable table property, so `alterTable(setProperty("location", ...))` repoints a + table without the provider being told. The old location is never unprovisioned and the new one + never went through the provider. +- `provisionTableLocation` runs before the table is actually created, so a creation that fails + afterwards -- a table that already exists, or a failure inside the table format itself -- leaves a + location provisioned for a table that does not exist. There is no compensating unprovision, and + that is deliberate: a table format that fails partway through creation may already have written to + the location, and unprovisioning would then tell the provider it may reclaim a path that has data + on it. Leaking an unused path is the safer of the two failures, and doing better would need the + format to report whether it touched storage before failing, which the interface cannot express. + The table format itself compensates where it can: Lance deletes the dataset it just created when + the metadata write then fails. Everything the catalog can check on its own -- the table format is + given, the format is supported -- is checked before the provider is consulted, so the cases that + remain are the ones only the table format can detect. +- A location that is provisioned but then not used is not handed back either. A creation mode such + as Lance's `EXIST_OK` returns the table that already exists, at the location it already has, and + the location provisioned for that call goes nowhere; a client retrying a create is the ordinary + way to reach it. Detecting that from the catalog would mean comparing two location strings and + concluding from the comparison what a provider did internally, which is exactly the inference this + interface leaves to the provider, so an allocating provider reconciles these along with the + failures above. +- A provider deriving a deterministic path from a table's identity hands out the same path again + when a table of the same name is created after the old one is gone, and the built-in provider is + one such provider. If anything survived under that path -- a drop whose data deletion failed, or a + format-internal drop as below -- the next creation of that name fails inside the table format + rather than in the provider, and keeps failing, because every retry derives the same path. + Clearing what was left behind is outside what this interface can see or do. +- A table format that drops a table through its own internals rather than through the catalog does + not trigger the unprovision callback. Lance's `OVERWRITE` creation mode does this: it drops the + existing table and creates a new one, so the old location is never handed back. This is the same + shape as the cascading schema drop, which the catalog does route through its own `dropTable`, but + a format-internal drop is not visible to the catalog at all. +- `alterTable(rename(...))` changes a table's identity without telling the provider, and without + moving any data. A provider deriving the path from the table name is left with a path that no + longer matches the name, which is cosmetic. A provider that books allocations against + `(schema, table)` loses the table altogether: the drop that follows arrives under the new name, + and the allocation booked under the old one is never handed back. Such a provider has to reconcile + renames out of band, or the deployment has to forbid renaming tables in this catalog. + +Two constraints follow from `ServiceLoader` discovery: + +- The implementation needs a public no-argument constructor that is cheap and does not throw. + Selecting a provider means asking each candidate its name, and `name()` is an instance method, so + every provider on the classpath is constructed once, per catalog, before the named one is + selected -- including when the provider being constructed is not the one selected. A constructor + that throws costs that provider the ability to be selected at all. Put clients, connection pools + and other expensive setup out of the constructor and create them lazily on first use, since the + candidates that are not selected are discarded and there is no close callback to release anything + they took. +- `name()` must be unique across the classpath and must not be `default`, which is reserved by the + built-in provider. If two providers share a name, every catalog selecting that name fails to + initialize. A candidate whose constructor or `name()` throws is logged and skipped, so one + misbehaving provider does not stop a catalog that named a different one. A services file naming a + class that cannot be loaded at all is not survivable in the same way: it fails the scan before any + candidate is reached. +>>>>>>> 8985ffad6 ([#13696] fix(lance): require catalog opt-in to purge external datasets (#14870)) #### Key Property: `location` diff --git a/docs/lakehouse-generic-lance-table.md b/docs/lakehouse-generic-lance-table.md index 0b3bbeb3b9..e685af50c8 100644 --- a/docs/lakehouse-generic-lance-table.md +++ b/docs/lakehouse-generic-lance-table.md @@ -105,14 +105,36 @@ Required and optional properties for tables in a Generic Lakehouse Catalog: |-----------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|--------------| | `format` | Table format: `lance`, only `lance` is fully supported. | (none) | Yes | | `location` | Storage path for table metadata and data, Lance supports: S3, GCS, OSS, AZ, File, Memory and file-object-store. | (none) | Conditional* | -| `external` | Whether the data directory is an external location. If it's `true`, dropping a table will only remove metadata in Gravitino and will not delete the data directory, and purge table will delete both. For a non-external table, dropping will drop both. | false | No | +| `external` | Whether the data directory is an external location. If it's `true`, dropping a table will only remove metadata in Gravitino and will not delete the data directory, and purge is rejected unless the catalog enables `lance.allow-external-table-purge`. For a non-external table, dropping will drop both. | false | No | | `lance.creation-mode` | Create mode: for create table, it can be `CREATE`, `EXIST_OK` or `OVERWRITE`. and it should be `CREATE` or `OVERWRITE` for registering tables | `CREATE` | No | | `lance.register` | Whether it is a register table operation. If it's `true`, This API will not create data directory actually and it's the user's responsibility to create and manage the data directory. `false` it will actually create a table. | false | No | | `lance.storage.xxxx` | Any additional storage-specific properties required by Lance format (e.g., S3 credentials, HDFS configs). Replace `xxxx` with actual property names. For example, we can use `lance.storage.aws_access_key_id` to set S3 aws_access_key_id when using a S3 location, for detail, refer to https://lancedb.com/docs/storage/integrations/ | (none) | No | - `CREATE`: Create a new table, fail if the table already exists. - `EXIST_OK`: Create a new table if it does not exist, otherwise do nothing. +<<<<<<< HEAD - `OVERWRITE`: Create a new table, overwrite if the table already exists, it will delete the existing data directory first if the table is not a registered table and then create a new one. +======= +- `OVERWRITE`: For creation (`lance.register=false`), purge the existing table and its dataset before creating a replacement. An existing external table requires the catalog to enable `lance.allow-external-table-purge`; otherwise the original metadata and data are retained. For registration (`lance.register=true`), validate the replacement dataset first and replace only external-table metadata, retaining the old dataset. Registration overwrite of a managed table is rejected; explicitly d [...] + +Registration validation checks dataset existence and readability, not an operator-defined storage scope or authorization to purge external data. + +### Format boundary + +The Generic Catalog is format-agnostic for its general table APIs, but a Lance table operation must +target an entity whose `format` property is `lance` (case-insensitive). Lance REST direct +operations such as describe, drop, deregister, and alter reject a known non-Lance entity with +HTTP `400 INVALID_INPUT`; `tableExists` presents it as absent. These checks preserve the existing +metadata and location. + +For create requests dispatched to the Lance table delegator, an existing non-Lance entity remains +a normal name conflict for `CREATE` (`409`). `EXIST_OK`, create `OVERWRITE`, and register +`OVERWRITE` are rejected with `IllegalArgumentException` by the direct Gravitino API, which is +returned as HTTP `400` by the Lance REST service. In particular, overwrite validation happens +before metadata removal or a Lance dataset delete. Generic Catalog `ListTables` behavior is +unchanged; it continues to list all formats. Format-specific listing is a separate follow-up +concern. +>>>>>>> 8985ffad6 ([#13696] fix(lance): require catalog opt-in to purge external datasets (#14870)) **Location Requirement:** Must be specified at catalog, schema, or table level. See [Location Resolution](./lakehouse-generic-catalog.md#key-property-location). @@ -206,7 +228,10 @@ tableCatalog.createTable( Register existing Lance tables without moving or copying data. A table with `lance.register=true` is always external, including when the request omits `external` or sets it to `false`. Dropping it through the Gravitino table API removes only the metadata. Explicit `purgeTable` and Lance REST -`drop` still delete both the metadata and the dataset; use Lance REST `deregister` to preserve data. +`drop` are rejected by default, preserving metadata and data. A catalog administrator may set +`lance.allow-external-table-purge=true` to allow both to be deleted. This setting is read only from +catalog properties; a table property cannot enable it. Use Lance REST `deregister` to remove +metadata while preserving data. The opt-in does not validate location ownership. Existing registrations with a missing or false stored `external` flag receive the same protection when dropped or deregistered. Their stored properties are not automatically migrated. diff --git a/docs/lance-rest-service.md b/docs/lance-rest-service.md index 75cd2e726d..3338032858 100644 --- a/docs/lance-rest-service.md +++ b/docs/lance-rest-service.md @@ -113,9 +113,22 @@ The `version` field of `CreateTable` response is always null, which stands for t ::: **DropTable vs DeregisterTable**: -- **DropTable**: Permanently deletes metadata and data files from storage +- **DropTable**: Permanently deletes metadata and data files when permitted by the catalog policy - **DeregisterTable**: Removes metadata from Gravitino but preserves Lance data files +The generic catalog rejects purging external or registered Lance tables by default, before removing +table metadata or deleting files. Lance REST reports this as HTTP `406` (`UnsupportedOperation`). Tables +created, declared or registered through Lance REST are external, so this default also applies to them. +Use `DeregisterTable` to remove their metadata while retaining their data. + +A catalog administrator can set `lance.allow-external-table-purge=true` on the `lakehouse-generic` +catalog to permit physical deletion. This catalog-only setting also applies to create `OVERWRITE` +when it replaces an existing external table. A table property or request header cannot enable it. +Existing catalogs must explicitly opt in to retain their previous destructive drop/overwrite behavior. +Enabling it permits deletion at caller-supplied locations; it does not verify storage ownership or +provide isolation between tables. Enable it only when table owners are trusted to delete data at +locations they can register. Underlying storage permissions still apply. + ## Deployment diff --git a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/utils/LanceConstants.java b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/utils/LanceConstants.java index 197388e8d4..4b238a4504 100644 --- a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/utils/LanceConstants.java +++ b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/utils/LanceConstants.java @@ -42,5 +42,8 @@ public class LanceConstants { public static final String LANCE_TABLE_DECLARED = "lance.declared"; public static final String LANCE_SCHEMA_REFRESH_MODE = "lance.schema-refresh-mode"; + /** Catalog-only opt-in for physically deleting external or registered Lance datasets. */ + public static final String LANCE_ALLOW_EXTERNAL_TABLE_PURGE = "lance.allow-external-table-purge"; + public static final String LANCE_TABLE_FORMAT = "lance"; } diff --git a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceRESTServiceIT.java b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceRESTServiceIT.java index db06aedc23..85837ac041 100644 --- a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceRESTServiceIT.java +++ b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceRESTServiceIT.java @@ -47,6 +47,7 @@ import org.apache.arrow.vector.types.pojo.ArrowType; import org.apache.arrow.vector.types.pojo.Field; import org.apache.commons.io.FileUtils; import org.apache.gravitino.Catalog; +import org.apache.gravitino.CatalogChange; import org.apache.gravitino.NameIdentifier; import org.apache.gravitino.Schema; import org.apache.gravitino.client.GravitinoMetalake; @@ -569,6 +570,26 @@ public class LanceRESTServiceIT extends BaseIT { "lance.storage.a", "value_va", "lance.storage.b", "value_vb"); + LanceNamespaceException denied = + Assertions.assertThrows( + LanceNamespaceException.class, + () -> createTable(ids, newLocation, overwriteTableProperties, body, "overwrite")); + Assertions.assertTrue( + denied.getMessage().contains(LanceConstants.LANCE_ALLOW_EXTERNAL_TABLE_PURGE)); + Assertions.assertEquals( + location, + catalog + .asTableCatalog() + .loadTable(NameIdentifier.of(SCHEMA_NAME, ids.get(2))) + .properties() + .get(Table.PROPERTY_LOCATION)); + Assertions.assertTrue(new File(location).exists()); + Assertions.assertFalse(new File(newLocation).exists()); + catalog = + metalake.alterCatalog( + CATALOG_NAME, + CatalogChange.setProperty(LanceConstants.LANCE_ALLOW_EXTERNAL_TABLE_PURGE, "true")); + response = Assertions.assertDoesNotThrow( () -> createTable(ids, newLocation, overwriteTableProperties, body, "overwrite")); @@ -1036,7 +1057,7 @@ public class LanceRESTServiceIT extends BaseIT { @Test void testDropTable() { - catalog = createCatalog(CATALOG_NAME); + catalog = createCatalog(CATALOG_NAME, true); createSchema(); List<String> ids = List.of(CATALOG_NAME, SCHEMA_NAME, "table_to_drop"); @@ -1219,8 +1240,13 @@ public class LanceRESTServiceIT extends BaseIT { } @Test +<<<<<<< HEAD void testDropTableWhenLocationMissingOrNotCreated() { catalog = createCatalog(CATALOG_NAME); +======= + void testDropTableWhenLocationMissingOrNotCreated() throws IOException { + catalog = createCatalog(CATALOG_NAME, true); +>>>>>>> 8985ffad6 ([#13696] fix(lance): require catalog opt-in to purge external datasets (#14870)) createSchema(); // Create table via register with non-existent location @@ -1272,9 +1298,14 @@ public class LanceRESTServiceIT extends BaseIT { } private Catalog createCatalog(String catalogName) { + return createCatalog(catalogName, false); + } + + private Catalog createCatalog(String catalogName, boolean allowExternalPurge) { Map<String, String> catalogProperties = ImmutableMap.<String, String>builder() .putAll(properties) + .put("lance.allow-external-table-purge", Boolean.toString(allowExternalPurge)) .put("lance.storage.endpoint", MINIO_ENDPOINT) .put("lance.storage.allow_http", "true") .put("lance.storage.access_key_id", MINIO_ACCESS_KEY) diff --git a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceTableAuthorizationIT.java b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceTableAuthorizationIT.java index 86b970b5d2..f5cb83caf2 100644 --- a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceTableAuthorizationIT.java +++ b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceTableAuthorizationIT.java @@ -23,6 +23,7 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Base64; @@ -31,6 +32,11 @@ import java.util.List; import org.apache.arrow.vector.types.pojo.ArrowType; import org.apache.arrow.vector.types.pojo.Field; import org.apache.arrow.vector.types.pojo.Schema; +<<<<<<< HEAD +======= +import org.apache.gravitino.Catalog; +import org.apache.gravitino.CatalogChange; +>>>>>>> 8985ffad6 ([#13696] fix(lance): require catalog opt-in to purge external datasets (#14870)) import org.apache.gravitino.Configs; import org.apache.gravitino.MetadataObject; import org.apache.gravitino.MetadataObjects; @@ -49,6 +55,9 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.lance.Dataset; import org.lance.namespace.model.AlterTableDropColumnsRequest; import org.lance.namespace.model.CreateNamespaceRequest; import org.lance.namespace.model.DeclareTableRequest; @@ -348,12 +357,32 @@ public class LanceTableAuthorizationIT extends BaseIT { // The denied requests left the table in place. assertStatus(200, table(ADMIN, VISIBLE_TABLE, "describe")); +<<<<<<< HEAD // Creating assigns ownership, so the creator may use either removal operation. assertStatus( 200, register(PROBER, WRITE_SCHEMA, DEREGISTER_TABLE, null, location(DEREGISTER_TABLE))); assertStatus(200, register(PROBER, WRITE_SCHEMA, DROP_TABLE, null, location(DROP_TABLE))); +======= + // Ownership permits deregistration. Physical deletion also requires catalog permission. + assertStatus(200, registerExistingTable(PROBER, WRITE_SCHEMA, DEREGISTER_TABLE)); + assertStatus(200, registerExistingTable(PROBER, WRITE_SCHEMA, DROP_TABLE)); +>>>>>>> 8985ffad6 ([#13696] fix(lance): require catalog opt-in to purge external datasets (#14870)) assertStatus(200, table(PROBER, WRITE_SCHEMA, DEREGISTER_TABLE, "deregister")); - assertStatus(200, table(PROBER, WRITE_SCHEMA, DROP_TABLE, "drop")); + assertStatus(406, table(PROBER, WRITE_SCHEMA, DROP_TABLE, "drop")); + assertStatus(200, table(PROBER, WRITE_SCHEMA, DROP_TABLE, "describe")); + Assertions.assertTrue(Files.exists(Path.of(location(DROP_TABLE)))); + GravitinoMetalake metalake = client.loadMetalake(getLanceRESTServerMetalakeName()); + metalake.alterCatalog( + CATALOG, + CatalogChange.setProperty(LanceConstants.LANCE_ALLOW_EXTERNAL_TABLE_PURGE, "true")); + try { + assertStatus(200, table(PROBER, WRITE_SCHEMA, DROP_TABLE, "drop")); + Assertions.assertFalse(Files.exists(Path.of(location(DROP_TABLE)))); + } finally { + metalake.alterCatalog( + CATALOG, + CatalogChange.setProperty(LanceConstants.LANCE_ALLOW_EXTERNAL_TABLE_PURGE, "false")); + } assertStatus(404, table(ADMIN, WRITE_SCHEMA, DEREGISTER_TABLE, "describe")); assertStatus(404, table(ADMIN, WRITE_SCHEMA, DROP_TABLE, "describe")); } @@ -362,8 +391,11 @@ public class LanceTableAuthorizationIT extends BaseIT { public void testSchemaOwnershipRemovesTablesTheOwnerDidNotCreate() throws Exception { // SCHEMA_OWNER_WITH_USE_CATALOG: the admin registered this table, so the only thing the caller // has is ownership of the schema holding it, plus USE_CATALOG. - assertStatus(200, table(SCHEMA_OWNER, OWNED_SCHEMA, OWNED_SCHEMA_TABLE, "drop")); + assertStatus(406, table(SCHEMA_OWNER, OWNED_SCHEMA, OWNED_SCHEMA_TABLE, "drop")); + assertStatus(200, table(ADMIN, OWNED_SCHEMA, OWNED_SCHEMA_TABLE, "describe")); + assertStatus(200, table(SCHEMA_OWNER, OWNED_SCHEMA, OWNED_SCHEMA_TABLE, "deregister")); assertStatus(404, table(ADMIN, OWNED_SCHEMA, OWNED_SCHEMA_TABLE, "describe")); + Assertions.assertTrue(Files.exists(Path.of(location(OWNED_SCHEMA_TABLE)))); } @Test @@ -386,6 +418,46 @@ public class LanceTableAuthorizationIT extends BaseIT { assertStatus(404, table(ADMIN, MISSING_TABLE, "deregister")); } + @ParameterizedTest + @ValueSource(strings = {"register", "create"}) + void testTableOwnerCannotPurgeAnotherSchemasData(String operation) throws Exception { + String victim = "purge_victim_" + operation; + String alias = "purge_alias_" + operation; + Path parent = tempDir.resolve("purge_parent_" + operation); + Path victimLocation = parent.resolve("victim"); + LanceDatasetTestUtils.createDataset(victimLocation.toString()); + assertStatus(200, register(ADMIN, SCHEMA, victim, null, victimLocation.toString())); + try { + assertStatus(403, table(PROBER, SCHEMA, victim, "describe")); + if ("register".equals(operation)) { + assertStatus(200, register(PROBER, WRITE_SCHEMA, alias, null, victimLocation.toString())); + } else { + Schema schema = new Schema(List.of(Field.nullable("id", new ArrowType.Int(32, true)))); + HttpRequest create = + request(PROBER, "/v1/table/" + id(CATALOG, WRITE_SCHEMA, alias) + "/create", "") + .setHeader("Content-Type", "application/vnd.apache.arrow.stream") + .setHeader(LanceConstants.LANCE_TABLE_LOCATION_HEADER, parent.toString()) + .POST(HttpRequest.BodyPublishers.ofByteArray(ArrowUtils.generateIpcStream(schema))) + .build(); + assertStatus(200, httpClient.send(create, HttpResponse.BodyHandlers.ofString())); + } + HttpResponse<String> rejected = table(PROBER, WRITE_SCHEMA, alias, "drop"); + assertStatus(406, rejected); + Assertions.assertTrue( + rejected.body().contains(LanceConstants.LANCE_ALLOW_EXTERNAL_TABLE_PURGE)); + assertStatus(200, table(PROBER, WRITE_SCHEMA, alias, "describe")); + assertStatus(200, table(ADMIN, SCHEMA, victim, "describe")); + try (Dataset dataset = Dataset.open().uri(victimLocation.toString()).build()) { + Assertions.assertFalse(dataset.getSchema().getFields().isEmpty()); + } + assertStatus(200, table(PROBER, WRITE_SCHEMA, alias, "deregister")); + Assertions.assertTrue(Files.exists(victimLocation)); + } finally { + table(ADMIN, WRITE_SCHEMA, alias, "deregister"); + table(ADMIN, SCHEMA, victim, "deregister"); + } + } + private HttpResponse<String> dropColumns(String user, String tableName, String column) throws Exception { return dropColumns(user, WRITE_SCHEMA, tableName, column);
