Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#15007] perf(lance): Reuse Lance Session cache when opening datasets in LanceTableOperations (#15173)

PiotrAndrzejewsky4e7800172634
diff --git a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogOperations.java b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogOperations.java
index fa6626aca4..644e435575 100644
--- a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogOperations.java
+++ b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/generic/GenericCatalogOperations.java
@@ -22,18 +22,17 @@ import static org.apache.gravitino.Entity.EntityType.TABLE;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
-import com.google.common.base.Suppliers;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Maps;
+import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
+import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.apache.gravitino.EntityStore;
@@ -78,7 +77,9 @@ public class GenericCatalogOperations implements CatalogOperations, SupportsSche
private final ManagedSchemaOperations schemaOps;
- private final Map<String, Supplier<ManagedTableOperations>> tableOpsCache;
+ private final Map<String, LakehouseTableDelegator> tableDelegators;
+
+ private final Map<String, ManagedTableOperations> tableOpsCache = new ConcurrentHashMap<>();
private volatile TableLocationProvider tableLocationProvider;
@@ -88,6 +89,8 @@ public class GenericCatalogOperations implements CatalogOperations, SupportsSche
private final EntityStore store;
+ private final IdGenerator idGenerator;
+
public GenericCatalogOperations() {
this(GravitinoEnv.getInstance().entityStore(), GravitinoEnv.getInstance().idGenerator());
}
@@ -95,6 +98,7 @@ public class GenericCatalogOperations implements CatalogOperations, SupportsSche
@VisibleForTesting
GenericCatalogOperations(EntityStore store, IdGenerator idGenerator) {
this.store = store;
+ this.idGenerator = idGenerator;
this.schemaOps =
new ManagedSchemaOperations() {
@@ -106,24 +110,14 @@ public class GenericCatalogOperations implements CatalogOperations, SupportsSche
this.tableFormatCache = CacheBuilder.newBuilder().maximumSize(1000).build();
- // Initialize all the table operations for different table formats.
- Map<String, LakehouseTableDelegator> tableDelegators =
+ // Register all table delegators for different table formats; table operations are created
+ // lazily on first access.
+ Map<String, LakehouseTableDelegator> delegators =
LakehouseTableDelegatorFactory.tableDelegators();
- tableOpsCache =
- Collections.unmodifiableMap(
- tableDelegators.entrySet().stream()
- .collect(
- Collectors.toMap(
- Map.Entry::getKey,
- // Lazy initialize the table operations when needed.
- e -> {
- LakehouseTableDelegator delegator = e.getValue();
- return Suppliers.memoize(
- () -> delegator.createTableOps(store, schemaOps, idGenerator));
- })));
- if (tableOpsCache.isEmpty()) {
+ if (delegators.isEmpty()) {
throw new IllegalArgumentException("No table delegators found, this is unexpected.");
}
+ this.tableDelegators = Collections.unmodifiableMap(delegators);
}
@Override
@@ -156,6 +150,21 @@ public class GenericCatalogOperations implements CatalogOperations, SupportsSche
@Override
public void close() {
tableFormatCache.cleanUp();
+ for (ManagedTableOperations ops : tableOpsCache.values()) {
+ if (ops instanceof Closeable closeable) {
+ try {
+ closeable.close();
+ } catch (Exception e) {
+ LOG.warn("Failed to close table operations: {}", ops, e);
+ }
+ }
+ }
+ tableOpsCache.clear();
+ }
+
+ @VisibleForTesting
+ Map<String, ManagedTableOperations> instantiatedTableOps() {
+ return Collections.unmodifiableMap(tableOpsCache);
}
@Override
@@ -237,7 +246,8 @@ public class GenericCatalogOperations implements CatalogOperations, SupportsSche
public NameIdentifier[] listTables(Namespace namespace) throws NoSuchSchemaException {
// We get the table operations from any cached table ops, since listing tables is not
// format-specific.
- ManagedTableOperations tableOps = tableOpsCache.values().iterator().next().get();
+ String defaultFormat = tableDelegators.keySet().iterator().next();
+ ManagedTableOperations tableOps = getOrCreateTableOps(defaultFormat);
return tableOps.listTables(namespace);
}
@@ -273,9 +283,7 @@ public class GenericCatalogOperations implements CatalogOperations, SupportsSche
format = format.toLowerCase(Locale.ROOT);
// Get the table operations for the specified table format.
- Supplier<ManagedTableOperations> tableOpsSupplier = tableOpsCache.get(format);
- Preconditions.checkArgument(tableOpsSupplier != null, "Unsupported table format: %s", format);
- ManagedTableOperations tableOps = configureTableOps(tableOpsSupplier.get());
+ ManagedTableOperations tableOps = configureTableOps(getOrCreateTableOps(format));
// The provider is consulted only once the request is known to be one this catalog can serve.
// A provider that allocates real storage has no compensating callback, so every check that can
@@ -484,8 +492,9 @@ public class GenericCatalogOperations implements CatalogOperations, SupportsSche
*/
private ManagedTableOperations tableOps(
NameIdentifier tableIdent, @Nullable Map<String, String> knownProperties) {
+ String tableFormat;
try {
- String tableFormat =
+ tableFormat =
tableFormatCache.get(
tableIdent,
() -> {
@@ -499,12 +508,6 @@ public class GenericCatalogOperations implements CatalogOperations, SupportsSche
return format.toLowerCase(Locale.ROOT);
});
-
- ManagedTableOperations ops = configureTableOps(tableOpsCache.get(tableFormat).get());
- Preconditions.checkArgument(
- ops != null, "No table operations found for table format %s", tableFormat);
- return ops;
-
} catch (Exception e) {
Throwable t = e.getCause();
@@ -518,6 +521,19 @@ public class GenericCatalogOperations implements CatalogOperations, SupportsSche
throw ExceptionMessages.wrap("Unexpected exception when loading table " + tableIdent, t);
}
}
+
+ return configureTableOps(getOrCreateTableOps(tableFormat));
+ }
+
+ private ManagedTableOperations getOrCreateTableOps(String format) {
+ LakehouseTableDelegator delegator = tableDelegators.get(format);
+ Preconditions.checkArgument(delegator != null, "Unsupported table format: %s", format);
+ ManagedTableOperations ops =
+ tableOpsCache.computeIfAbsent(
+ format, k -> delegator.createTableOps(store, schemaOps, idGenerator));
+ Preconditions.checkArgument(
+ ops != null, "No table operations found for table format %s", format);
+ return ops;
}
private ManagedTableOperations configureTableOps(ManagedTableOperations ops) {
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 b63409edea..f4039aec0f 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
@@ -25,16 +25,21 @@ import static org.apache.gravitino.connector.PropertyEntry.stringOptionalPropert
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_SESSION_INDEX_CACHE_SIZE_BYTES;
+import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_SESSION_METADATA_CACHE_SIZE_BYTES;
import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_STORAGE_OPTIONS_PREFIX;
+import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import java.util.List;
import java.util.Map;
+import org.apache.commons.lang3.StringUtils;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.catalog.lakehouse.lance.LanceTableOperations;
import org.apache.gravitino.connector.BaseCatalogPropertiesMetadata;
import org.apache.gravitino.connector.PropertyEntry;
+import org.lance.Session;
public class GenericCatalogPropertiesMetadata extends BaseCatalogPropertiesMetadata {
@@ -45,6 +50,9 @@ public class GenericCatalogPropertiesMetadata extends BaseCatalogPropertiesMetad
*/
public static final String TABLE_LOCATION_PROVIDER = "table-location-provider";
+ /** Default index cache size in bytes for the catalog-scoped Lance session (128 MiB). */
+ public static final long DEFAULT_LANCE_SESSION_INDEX_CACHE_SIZE_BYTES = 128L * 1024 * 1024;
+
private static final Map<String, PropertyEntry<?>> PROPERTIES_METADATA;
static {
@@ -89,7 +97,19 @@ public class GenericCatalogPropertiesMetadata extends BaseCatalogPropertiesMetad
LanceTableOperations.SchemaRefreshMode.class,
LanceTableOperations.SchemaRefreshMode.DECLARED_AND_EMPTY,
false /* hidden */,
- false /* reserved */));
+ false /* reserved */),
+ nonNegativeLongOptionalPropertyEntry(
+ LANCE_SESSION_METADATA_CACHE_SIZE_BYTES,
+ "The metadata cache size in bytes for the Lance session.",
+ false /* immutable */,
+ Session.DEFAULT_METADATA_CACHE_SIZE_BYTES,
+ false /* hidden */),
+ nonNegativeLongOptionalPropertyEntry(
+ LANCE_SESSION_INDEX_CACHE_SIZE_BYTES,
+ "The index cache size in bytes for the Lance session.",
+ false /* immutable */,
+ DEFAULT_LANCE_SESSION_INDEX_CACHE_SIZE_BYTES,
+ false /* hidden */));
PROPERTIES_METADATA = Maps.uniqueIndex(propertyEntries, PropertyEntry::getName);
}
@@ -98,4 +118,44 @@ public class GenericCatalogPropertiesMetadata extends BaseCatalogPropertiesMetad
protected Map<String, PropertyEntry<?>> specificPropertyEntries() {
return PROPERTIES_METADATA;
}
+
+ /**
+ * Parses a string property value as a non-negative {@code long}.
+ *
+ * @param propertyKey the property name, used in error messages
+ * @param propValue the raw string value
+ * @return the parsed non-negative value
+ * @throws IllegalArgumentException if {@code propValue} is blank, not a valid {@code long}, or
+ * less than 0
+ */
+ public static long parseNonNegativeLong(String propertyKey, String propValue) {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(propValue), "Property %s must not be null or blank", propertyKey);
+ try {
+ long parsed = Long.parseLong(propValue.trim());
+ Preconditions.checkArgument(
+ parsed >= 0,
+ "Property %s must be greater than or equal to 0, got %s",
+ propertyKey,
+ parsed);
+ return parsed;
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(
+ String.format("Invalid long value '%s' for property %s", propValue, propertyKey), e);
+ }
+ }
+
+ private static PropertyEntry<Long> nonNegativeLongOptionalPropertyEntry(
+ String name, String description, boolean immutable, long defaultValue, boolean hidden) {
+ return new PropertyEntry.Builder<Long>()
+ .withName(name)
+ .withDescription(description)
+ .withImmutable(immutable)
+ .withJavaType(Long.class)
+ .withDefaultValue(defaultValue)
+ .withHidden(hidden)
+ .withDecoder(value -> parseNonNegativeLong(name, value))
+ .withEncoder(String::valueOf)
+ .build();
+ }
}
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 dd36f28c19..fd7f97488d 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
@@ -23,9 +23,11 @@ import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_CREAT
import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_TABLE_REGISTER;
import static org.apache.gravitino.rel.Column.DEFAULT_VALUE_NOT_SET;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
+import java.io.Closeable;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
@@ -37,6 +39,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@@ -49,6 +52,7 @@ import org.apache.gravitino.EntityStore;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.catalog.ManagedSchemaOperations;
import org.apache.gravitino.catalog.ManagedTableOperations;
+import org.apache.gravitino.catalog.lakehouse.generic.GenericCatalogPropertiesMetadata;
import org.apache.gravitino.connector.GenericColumn;
import org.apache.gravitino.connector.GenericTable;
import org.apache.gravitino.connector.SupportsSchemas;
@@ -76,6 +80,7 @@ import org.apache.gravitino.utils.ExceptionMessages;
import org.apache.gravitino.utils.PrincipalUtils;
import org.lance.Dataset;
import org.lance.ReadOptions;
+import org.lance.Session;
import org.lance.WriteDatasetBuilder;
import org.lance.WriteParams;
import org.lance.index.DistanceType;
@@ -87,7 +92,7 @@ import org.lance.schema.ColumnAlteration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class LanceTableOperations extends ManagedTableOperations {
+public class LanceTableOperations extends ManagedTableOperations implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(LanceTableOperations.class);
/**
@@ -149,8 +154,16 @@ public class LanceTableOperations extends ManagedTableOperations {
private final IdGenerator idGenerator;
+ private final ReentrantReadWriteLock sessionLock = new ReentrantReadWriteLock();
+
+ private final Object sessionInitLock = new Object();
+
private volatile Map<String, String> catalogProperties = Map.of();
+ private volatile Session lanceSession;
+
+ private volatile boolean isClosed = false;
+
public LanceTableOperations(
EntityStore store, ManagedSchemaOperations schemaOps, IdGenerator idGenerator) {
this.store = store;
@@ -174,7 +187,8 @@ public class LanceTableOperations extends ManagedTableOperations {
}
/**
- * Sets the catalog properties used to resolve Lance storage defaults at runtime.
+ * Sets the catalog properties used to resolve Lance storage defaults and session cache settings
+ * at runtime. Cache size properties take effect upon the initial creation of the Lance session.
*
* @param catalogProperties the catalog properties
*/
@@ -189,6 +203,24 @@ public class LanceTableOperations extends ManagedTableOperations {
: Collections.unmodifiableMap(Maps.newHashMap(catalogProperties));
}
+ /** Closes the Lance session cache and releases associated native memory. */
+ @Override
+ public void close() {
+ sessionLock.writeLock().lock();
+ try {
+ isClosed = true;
+ if (lanceSession != null && !lanceSession.isClosed()) {
+ try {
+ lanceSession.close();
+ } catch (Exception e) {
+ LOG.warn("Failed to close Lance session", e);
+ }
+ }
+ } finally {
+ sessionLock.writeLock().unlock();
+ }
+ }
+
@Override
public Table loadTable(NameIdentifier ident) throws NoSuchTableException {
return loadTableInternal(ident, false);
@@ -1016,10 +1048,52 @@ public class LanceTableOperations extends ManagedTableOperations {
// Do not pass an explicit allocator: OpenDatasetBuilder then sets selfManagedAllocator=true
// so Dataset.close() will release the off-heap memory. Passing new RootAllocator() sets
// selfManagedAllocator=false and leaks the allocator on every call.
- return Dataset.open()
- .uri(location)
- .readOptions(new ReadOptions.Builder().setStorageOptions(storageOptions).build())
- .build();
+ // Hold the read lock across session lookup and Dataset.open() so close() cannot free the
+ // native session handle before Dataset.open() retains its own reference.
+ sessionLock.readLock().lock();
+ try {
+ return Dataset.open()
+ .uri(location)
+ .readOptions(
+ new ReadOptions.Builder()
+ .setSession(getOrCreateSession())
+ .setStorageOptions(storageOptions)
+ .build())
+ .build();
+ } finally {
+ sessionLock.readLock().unlock();
+ }
+ }
+
+ /**
+ * Returns whether this table operations instance has been closed.
+ *
+ * @return true if closed, false otherwise
+ */
+ @VisibleForTesting
+ public boolean isClosed() {
+ return isClosed;
+ }
+
+ /**
+ * Returns the catalog-scoped Lance session, instantiating it lazily if not already present.
+ *
+ * @return the shared {@link Session} instance
+ * @throws IllegalStateException if this table operations instance has been closed
+ */
+ @VisibleForTesting
+ public Session session() {
+ sessionLock.readLock().lock();
+ try {
+ return getOrCreateSession();
+ } finally {
+ sessionLock.readLock().unlock();
+ }
+ }
+
+ @VisibleForTesting
+ Session getLanceSession() {
+ return lanceSession;
}
private IndexParams getIndexParamsByIndexType(IndexType indexType) {
@@ -1096,4 +1170,49 @@ public class LanceTableOperations extends ManagedTableOperations {
throw ExceptionMessages.wrap("Failed to close validated dataset for table " + ident, e);
}
}
+
+ private Session getOrCreateSession() {
+ if (isClosed) {
+ throw new IllegalStateException("LanceTableOperations is closed");
+ }
+ if (lanceSession == null) {
+ synchronized (sessionInitLock) {
+ if (isClosed) {
+ throw new IllegalStateException("LanceTableOperations is closed");
+ }
+ if (lanceSession == null) {
+ lanceSession = createSession();
+ }
+ }
+ }
+ return lanceSession;
+ }
+
+ private Session createSession() {
+ long metadataCacheSizeBytes =
+ parseCacheSizeBytes(
+ LanceConstants.LANCE_SESSION_METADATA_CACHE_SIZE_BYTES,
+ Session.DEFAULT_METADATA_CACHE_SIZE_BYTES);
+ long indexCacheSizeBytes =
+ parseCacheSizeBytes(
+ LanceConstants.LANCE_SESSION_INDEX_CACHE_SIZE_BYTES,
+ GenericCatalogPropertiesMetadata.DEFAULT_LANCE_SESSION_INDEX_CACHE_SIZE_BYTES);
+
+ LOG.info(
+ "Initializing Lance session cache with metadataCacheSizeBytes={}, indexCacheSizeBytes={}",
+ metadataCacheSizeBytes,
+ indexCacheSizeBytes);
+ return Session.builder()
+ .metadataCacheSizeBytes(metadataCacheSizeBytes)
+ .indexCacheSizeBytes(indexCacheSizeBytes)
+ .build();
+ }
+
+ private long parseCacheSizeBytes(String propertyKey, long defaultValue) {
+ String propValue = catalogProperties.get(propertyKey);
+ if (StringUtils.isBlank(propValue)) {
+ return defaultValue;
+ }
+ return GenericCatalogPropertiesMetadata.parseNonNegativeLong(propertyKey, propValue);
+ }
}
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 58f5d5a9c2..0e83085b4e 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
@@ -74,10 +74,12 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.Schema;
import org.apache.gravitino.StringIdentifier;
+import org.apache.gravitino.catalog.lakehouse.lance.LanceTableOperations;
import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.exceptions.NoSuchTableException;
import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;
+import org.apache.gravitino.lance.common.utils.LanceConstants;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.CatalogEntity;
@@ -100,6 +102,7 @@ import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.lance.Dataset;
+import org.lance.Session;
import org.lance.WriteParams;
import org.mockito.Mockito;
@@ -354,6 +357,62 @@ public class TestGenericCatalogOperations {
() -> ops.testConnection(NameIdentifier.of(METALAKE_NAME, CATALOG_NAME)));
}
+ @Test
+ void testCloseCascadesToTableOperations() throws Exception {
+ GenericCatalogOperations catalogOps = new GenericCatalogOperations(store, idGenerator);
+ Assertions.assertTrue(catalogOps.instantiatedTableOps().isEmpty());
+
+ String schemaName = randomSchemaName();
+ NameIdentifier schemaIdent =
+ NameIdentifierUtil.ofSchema(METALAKE_NAME, CATALOG_NAME, schemaName);
+ StringIdentifier stringId = StringIdentifier.fromId(idGenerator.nextId());
+ Map<String, String> schemaProperties = StringIdentifier.newPropertiesWithId(stringId, null);
+ ops.createSchema(schemaIdent, "schema comment", schemaProperties);
+
+ NameIdentifier ident =
+ NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, schemaName, "cascade_table");
+ Map<String, String> properties =
+ Map.of(
+ Table.PROPERTY_TABLE_FORMAT,
+ "lance",
+ Table.PROPERTY_LOCATION,
+ "/tmp/cascade_table_" + UUID.randomUUID(),
+ LanceConstants.LANCE_TABLE_VERSION,
+ "1");
+
+ TableEntity entity =
+ TableEntity.builder()
+ .withId(idGenerator.nextId())
+ .withName(ident.name())
+ .withNamespace(ident.namespace())
+ .withProperties(properties)
+ .withAuditInfo(
+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())
+ .build();
+ store.put(entity, false);
+
+ try {
+ catalogOps.loadTable(ident);
+ } catch (Exception ignored) {
+ // Table doesn't exist on disk, but tableOps delegator resolution is what we test
+ }
+
+ Assertions.assertEquals(1, catalogOps.instantiatedTableOps().size());
+ LanceTableOperations lanceOps =
+ (LanceTableOperations) catalogOps.instantiatedTableOps().get("lance");
+ Assertions.assertNotNull(lanceOps);
+ Assertions.assertFalse(lanceOps.isClosed());
+
+ Session session = lanceOps.session();
+ Assertions.assertNotNull(session);
+ Assertions.assertFalse(session.isClosed());
+
+ catalogOps.close();
+ Assertions.assertTrue(lanceOps.isClosed());
+ Assertions.assertTrue(session.isClosed());
+ Assertions.assertTrue(catalogOps.instantiatedTableOps().isEmpty());
+ }
+
@Test
public void testSchemaOperations() {
String schemaName = randomSchemaName();
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 4f468e1cf1..9e5b983560 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
@@ -20,6 +20,8 @@
package org.apache.gravitino.catalog.lakehouse.generic;
import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_ALLOW_EXTERNAL_TABLE_PURGE;
+import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_SESSION_INDEX_CACHE_SIZE_BYTES;
+import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_SESSION_METADATA_CACHE_SIZE_BYTES;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
@@ -30,6 +32,7 @@ import org.apache.gravitino.rel.Table;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
+import org.lance.Session;
public class TestPropertiesMetadata {
public static GenericCatalog genericCatalog;
@@ -68,6 +71,61 @@ public class TestPropertiesMetadata {
Assertions.assertFalse(metadata.isImmutableProperty(LANCE_ALLOW_EXTERNAL_TABLE_PURGE));
}
+ @Test
+ void testSessionCachePropertiesMetadata() {
+ PropertiesMetadata metadata = genericCatalog.catalogPropertiesMetadata();
+ Assertions.assertTrue(metadata.containsProperty(LANCE_SESSION_METADATA_CACHE_SIZE_BYTES));
+ Assertions.assertTrue(metadata.containsProperty(LANCE_SESSION_INDEX_CACHE_SIZE_BYTES));
+ Assertions.assertEquals(
+ Session.DEFAULT_METADATA_CACHE_SIZE_BYTES,
+ metadata.getOrDefault(Map.of(), LANCE_SESSION_METADATA_CACHE_SIZE_BYTES));
+ Assertions.assertEquals(
+ GenericCatalogPropertiesMetadata.DEFAULT_LANCE_SESSION_INDEX_CACHE_SIZE_BYTES,
+ metadata.getOrDefault(Map.of(), LANCE_SESSION_INDEX_CACHE_SIZE_BYTES));
+ Assertions.assertEquals(
+ 12345L,
+ metadata.getOrDefault(
+ Map.of(LANCE_SESSION_METADATA_CACHE_SIZE_BYTES, "12345"),
+ LANCE_SESSION_METADATA_CACHE_SIZE_BYTES));
+ Assertions.assertEquals(
+ 67890L,
+ metadata.getOrDefault(
+ Map.of(LANCE_SESSION_INDEX_CACHE_SIZE_BYTES, "67890"),
+ LANCE_SESSION_INDEX_CACHE_SIZE_BYTES));
+ Assertions.assertEquals(
+ 0L,
+ metadata.getOrDefault(
+ Map.of(LANCE_SESSION_METADATA_CACHE_SIZE_BYTES, "0"),
+ LANCE_SESSION_METADATA_CACHE_SIZE_BYTES));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ metadata.getOrDefault(
+ Map.of(LANCE_SESSION_METADATA_CACHE_SIZE_BYTES, "-1"),
+ LANCE_SESSION_METADATA_CACHE_SIZE_BYTES));
+ Assertions.assertEquals(
+ 0L,
+ metadata.getOrDefault(
+ Map.of(LANCE_SESSION_INDEX_CACHE_SIZE_BYTES, "0"),
+ LANCE_SESSION_INDEX_CACHE_SIZE_BYTES));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ metadata.getOrDefault(
+ Map.of(LANCE_SESSION_INDEX_CACHE_SIZE_BYTES, "-1"),
+ LANCE_SESSION_INDEX_CACHE_SIZE_BYTES));
+ Assertions.assertFalse(metadata.isImmutableProperty(LANCE_SESSION_METADATA_CACHE_SIZE_BYTES));
+ Assertions.assertFalse(metadata.isImmutableProperty(LANCE_SESSION_INDEX_CACHE_SIZE_BYTES));
+ Assertions.assertEquals(
+ 123L, GenericCatalogPropertiesMetadata.parseNonNegativeLong("prop", " 123 "));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> GenericCatalogPropertiesMetadata.parseNonNegativeLong("prop", " "));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> GenericCatalogPropertiesMetadata.parseNonNegativeLong("prop", null));
+ }
+
@Test
void testCatalogPropertiesMetadata() {
PropertiesMetadata catalogPropertiesMetadata = genericCatalog.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 687a7fd4d8..053438aaca 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
@@ -21,6 +21,8 @@ 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_SESSION_INDEX_CACHE_SIZE_BYTES;
+import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_SESSION_METADATA_CACHE_SIZE_BYTES;
import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_STORAGE_OPTIONS_PREFIX;
import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_TABLE_DECLARED;
import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_TABLE_REGISTER;
@@ -39,18 +41,38 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.common.collect.Maps;
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.time.Instant;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CopyOnWriteArrayList;
+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.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.arrow.memory.RootAllocator;
+import org.apache.arrow.vector.IntVector;
+import org.apache.arrow.vector.VectorSchemaRoot;
+import org.apache.arrow.vector.ipc.ArrowReader;
import org.apache.arrow.vector.types.pojo.ArrowType;
import org.apache.arrow.vector.types.pojo.Field;
import org.apache.arrow.vector.types.pojo.Schema;
@@ -78,6 +100,7 @@ import org.apache.gravitino.rel.types.Types;
import org.apache.gravitino.storage.IdGenerator;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.utils.PrincipalUtils;
+import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -85,9 +108,21 @@ import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
+import org.lance.CacheStats;
import org.lance.Dataset;
+import org.lance.Fragment;
+import org.lance.FragmentMetadata;
+import org.lance.Session;
+import org.lance.SourcedTransaction;
import org.lance.Version;
+import org.lance.WriteParams;
import org.lance.index.IndexOptions;
+import org.lance.index.IndexParams;
+import org.lance.index.IndexType;
+import org.lance.index.scalar.ScalarIndexParams;
+import org.lance.ipc.LanceScanner;
+import org.lance.ipc.ScanOptions;
+import org.lance.operation.Append;
import org.mockito.InOrder;
import org.mockito.Mockito;
@@ -108,6 +143,13 @@ public class TestLanceTableOperations {
lanceTableOps = spy(new LanceTableOperations(store, schemaOps, idGenerator));
}
+ @AfterEach
+ public void tearDown() {
+ if (lanceTableOps != null && !lanceTableOps.isClosed()) {
+ lanceTableOps.close();
+ }
+ }
+
/** Registered tables persist external ownership and retain the existing dataset on drop. */
@ParameterizedTest
@CsvSource(
@@ -2488,4 +2530,618 @@ public class TestLanceTableOperations {
.openDataset(location, Map.of("endpoint", "http://endpoint"));
return ident;
}
+
+ @Test
+ void testLanceSessionCacheHit() throws Exception {
+ String location = tempDir.resolve("cache_hit_table").toString();
+ Column[] columns = {
+ Column.of("id", Types.IntegerType.get()), Column.of("name", Types.StringType.get())
+ };
+ try (Dataset ignored = lanceTableOps.createDataset(location, columns, Map.of())) {}
+
+ // Verify session is lazily created (null before first open)
+ Assertions.assertNull(lanceTableOps.getLanceSession());
+
+ // First open: populates metadata cache
+ try (Dataset dataset1 = lanceTableOps.openDataset(location)) {
+ Assertions.assertEquals(2, dataset1.getSchema().getFields().size());
+ }
+
+ Session session = lanceTableOps.session();
+ Assertions.assertNotNull(session);
+ CacheStats statsAfterFirst = session.metadataCacheStats();
+ Assertions.assertNotNull(statsAfterFirst);
+
+ // Second open: reuses cached metadata (cache hit)
+ try (Dataset dataset2 = lanceTableOps.openDataset(location)) {
+ Assertions.assertEquals(2, dataset2.getSchema().getFields().size());
+ }
+
+ CacheStats statsAfterSecond = session.metadataCacheStats();
+ Assertions.assertTrue(
+ statsAfterSecond.getHits() > 0,
+ "Expected cache hits > 0, but got: " + statsAfterSecond.getHits());
+ Assertions.assertTrue(
+ statsAfterSecond.getSizeBytes() > 0,
+ "Expected cache size > 0 bytes, but got: " + statsAfterSecond.getSizeBytes());
+ }
+
+ @Test
+ void testLanceSessionLifecycleAndClose() throws Exception {
+ String location = tempDir.resolve("lifecycle_table").toString();
+ Column[] columns = {Column.of("id", Types.IntegerType.get())};
+ try (Dataset ignored = lanceTableOps.createDataset(location, columns, Map.of())) {}
+
+ Assertions.assertFalse(lanceTableOps.isClosed());
+ try (Dataset ds = lanceTableOps.openDataset(location)) {
+ Assertions.assertNotNull(ds);
+ }
+
+ Session session = lanceTableOps.session();
+ Assertions.assertFalse(session.isClosed());
+
+ // Close LanceTableOperations
+ lanceTableOps.close();
+ Assertions.assertTrue(lanceTableOps.isClosed());
+ Assertions.assertTrue(session.isClosed());
+
+ // Idempotent close
+ Assertions.assertDoesNotThrow(() -> lanceTableOps.close());
+
+ // Operation after close throws IllegalStateException
+ IllegalStateException ex =
+ Assertions.assertThrows(
+ IllegalStateException.class, () -> lanceTableOps.openDataset(location));
+ Assertions.assertTrue(ex.getMessage().contains("LanceTableOperations is closed"));
+ }
+
+ @Test
+ void testStorageOptionsIsolationWithSession() throws Exception {
+ String location1 = tempDir.resolve("storage_iso_1").toString();
+ String location2 = tempDir.resolve("storage_iso_2").toString();
+ Column[] cols1 = {Column.of("col_a", Types.IntegerType.get())};
+ Column[] cols2 = {Column.of("col_b", Types.StringType.get())};
+ try (Dataset ignored = lanceTableOps.createDataset(location1, cols1, Map.of());
+ Dataset ignored2 = lanceTableOps.createDataset(location2, cols2, Map.of())) {}
+
+ Map<String, String> opts1 = Map.of("test.custom.key", "val1");
+ Map<String, String> opts2 = Map.of("test.custom.key", "val2");
+
+ try (Dataset ds1 = lanceTableOps.openDataset(location1, opts1);
+ Dataset ds2 = lanceTableOps.openDataset(location2, opts2);
+ Dataset ds1Again = lanceTableOps.openDataset(location1, opts1);
+ Dataset ds1WithOpts2 = lanceTableOps.openDataset(location1, opts2)) {
+ Assertions.assertNotNull(ds1);
+ Assertions.assertNotNull(ds2);
+ Assertions.assertNotNull(ds1Again);
+ Assertions.assertNotNull(ds1WithOpts2);
+
+ Assertions.assertEquals(1, ds1.getSchema().getFields().size());
+ Assertions.assertEquals("col_a", ds1.getSchema().getFields().get(0).getName());
+ Assertions.assertEquals(opts1, ds1.getLatestStorageOptions());
+
+ Assertions.assertEquals(1, ds2.getSchema().getFields().size());
+ Assertions.assertEquals("col_b", ds2.getSchema().getFields().get(0).getName());
+ Assertions.assertEquals(opts2, ds2.getLatestStorageOptions());
+
+ Assertions.assertEquals(1, ds1Again.getSchema().getFields().size());
+ Assertions.assertEquals("col_a", ds1Again.getSchema().getFields().get(0).getName());
+ Assertions.assertEquals(opts1, ds1Again.getLatestStorageOptions());
+
+ Assertions.assertEquals(1, ds1WithOpts2.getSchema().getFields().size());
+ Assertions.assertEquals("col_a", ds1WithOpts2.getSchema().getFields().get(0).getName());
+ Assertions.assertEquals(opts2, ds1WithOpts2.getLatestStorageOptions());
+
+ Session session = lanceTableOps.session();
+ Assertions.assertNotNull(session);
+ Assertions.assertFalse(session.isClosed());
+ try (Session s1 = ds1.session();
+ Session s2 = ds2.session();
+ Session s3 = ds1Again.session();
+ Session s4 = ds1WithOpts2.session()) {
+ Assertions.assertTrue(session.isSameAs(s1));
+ Assertions.assertTrue(session.isSameAs(s2));
+ Assertions.assertTrue(session.isSameAs(s3));
+ Assertions.assertTrue(session.isSameAs(s4));
+ }
+ }
+ }
+
+ @Test
+ void testStorageOptionsIsolationAcrossEndpointsAtSameUri() throws Exception {
+ Path dirA = tempDir.resolve("endpoint_a_dataset");
+ Path dirB = tempDir.resolve("endpoint_b_dataset");
+ Column[] colsA = {Column.of("col_a", Types.IntegerType.get())};
+ Column[] colsB = {Column.of("col_b", Types.StringType.get())};
+ try (Dataset ignoredA = lanceTableOps.createDataset(dirA.toString(), colsA, Map.of());
+ Dataset ignoredB = lanceTableOps.createDataset(dirB.toString(), colsB, Map.of())) {}
+
+ String bucket = "test-bucket";
+ String tableKey = "shared_table";
+ String sharedUri = "s3://" + bucket + "/" + tableKey;
+
+ List<String> reqsA = new CopyOnWriteArrayList<>();
+ List<String> reqsB = new CopyOnWriteArrayList<>();
+ HttpServer serverA = startS3EndpointServer(dirA, bucket, tableKey, reqsA);
+ HttpServer serverB = startS3EndpointServer(dirB, bucket, tableKey, reqsB);
+ try {
+ Map<String, String> optsA = s3StorageOptions(serverA.getAddress().getPort());
+ Map<String, String> optsB = s3StorageOptions(serverB.getAddress().getPort());
+
+ try (Dataset dsA = lanceTableOps.openDataset(sharedUri, optsA);
+ Dataset dsB = lanceTableOps.openDataset(sharedUri, optsB);
+ Dataset dsAAgain = lanceTableOps.openDataset(sharedUri, optsA)) {
+ Assertions.assertEquals("col_a", dsA.getSchema().getFields().get(0).getName());
+ Assertions.assertEquals(optsA, dsA.getLatestStorageOptions());
+ Assertions.assertEquals("col_b", dsB.getSchema().getFields().get(0).getName());
+ Assertions.assertEquals(optsB, dsB.getLatestStorageOptions());
+ Assertions.assertEquals("col_a", dsAAgain.getSchema().getFields().get(0).getName());
+ Assertions.assertEquals(optsA, dsAAgain.getLatestStorageOptions());
+
+ Session sharedSession = lanceTableOps.session();
+ try (Session sA = dsA.session();
+ Session sB = dsB.session();
+ Session sAAgain = dsAAgain.session()) {
+ Assertions.assertTrue(sharedSession.isSameAs(sA));
+ Assertions.assertTrue(sharedSession.isSameAs(sB));
+ Assertions.assertTrue(sharedSession.isSameAs(sAAgain));
+ }
+ }
+ Assertions.assertFalse(reqsA.isEmpty(), "Expected requests to endpoint A");
+ Assertions.assertFalse(reqsB.isEmpty(), "Expected requests to endpoint B");
+ } finally {
+ serverA.stop(0);
+ serverB.stop(0);
+ }
+ }
+
+ @Test
+ void testMultiCatalogSessionIsolation() throws Exception {
+ String location = tempDir.resolve("multi_catalog_table").toString();
+ Column[] cols = {Column.of("id", Types.IntegerType.get())};
+ try (Dataset ignored = lanceTableOps.createDataset(location, cols, Map.of())) {}
+
+ LanceTableOperations ops1 = new LanceTableOperations(store, schemaOps, idGenerator);
+ LanceTableOperations ops2 = new LanceTableOperations(store, schemaOps, idGenerator);
+
+ try (Dataset d1 = ops1.openDataset(location);
+ Dataset d2 = ops2.openDataset(location)) {
+ Assertions.assertNotNull(d1);
+ Assertions.assertNotNull(d2);
+ }
+
+ Session s1 = ops1.session();
+ Session s2 = ops2.session();
+ Assertions.assertNotNull(s1);
+ Assertions.assertNotNull(s2);
+ Assertions.assertFalse(s1.isSameAs(s2));
+
+ ops1.close();
+ Assertions.assertTrue(s1.isClosed());
+ Assertions.assertFalse(s2.isClosed());
+ ops2.close();
+ Assertions.assertTrue(s2.isClosed());
+ }
+
+ @Test
+ void testCustomSessionCacheSizeProperties() throws Exception {
+ String location = tempDir.resolve("custom_props_table").toString();
+ createIndexedDataset(location, 32);
+
+ long emptySessionBytes;
+ try (Session emptySession =
+ Session.builder().metadataCacheSizeBytes(0).indexCacheSizeBytes(0).build()) {
+ emptySessionBytes = emptySession.sizeBytes();
+ }
+
+ // Default properties (omitted): both metadata and index caches are active.
+ try (LanceTableOperations opsDefault =
+ new LanceTableOperations(store, schemaOps, idGenerator)) {
+ try (Dataset ds1 = opsDefault.openDataset(location);
+ Dataset ds2 = opsDefault.openDataset(location)) {
+ Assertions.assertNotNull(ds1);
+ Assertions.assertNotNull(ds2);
+ scanIndexedFilter(ds2, "id = 5");
+ }
+ Session defaultSession = opsDefault.session();
+ CacheStats defaultMetaStats = defaultSession.metadataCacheStats();
+ Assertions.assertTrue(defaultMetaStats.getHits() > 0);
+ Assertions.assertTrue(defaultMetaStats.getSizeBytes() > 0);
+ Assertions.assertTrue(
+ defaultSession.sizeBytes() - defaultMetaStats.getSizeBytes() > emptySessionBytes,
+ "Expected default index cache bytes > 0 above baseline " + emptySessionBytes);
+ }
+
+ // Zero metadata & zero index cache: caching is disabled for both.
+ try (LanceTableOperations opsZero = new LanceTableOperations(store, schemaOps, idGenerator)) {
+ opsZero.setCatalogProperties(
+ Map.of(
+ LANCE_SESSION_METADATA_CACHE_SIZE_BYTES, "0",
+ LANCE_SESSION_INDEX_CACHE_SIZE_BYTES, "0"));
+ try (Dataset ds1 = opsZero.openDataset(location);
+ Dataset ds2 = opsZero.openDataset(location)) {
+ Assertions.assertNotNull(ds1);
+ Assertions.assertNotNull(ds2);
+ scanIndexedFilter(ds2, "id = 5");
+ }
+ Session zeroSession = opsZero.session();
+ CacheStats zeroMetaStats = zeroSession.metadataCacheStats();
+ Assertions.assertEquals(0L, zeroMetaStats.getHits());
+ Assertions.assertEquals(0L, zeroMetaStats.getSizeBytes());
+ Assertions.assertEquals(emptySessionBytes, zeroSession.sizeBytes());
+ }
+
+ // Non-zero metadata cache (1 MiB), zero index cache: metadata cache hits on second open while
+ // index cache stays empty during an indexed scan.
+ try (LanceTableOperations opsMetaOnly =
+ new LanceTableOperations(store, schemaOps, idGenerator)) {
+ opsMetaOnly.setCatalogProperties(
+ Map.of(
+ LANCE_SESSION_METADATA_CACHE_SIZE_BYTES, "1048576",
+ LANCE_SESSION_INDEX_CACHE_SIZE_BYTES, "0"));
+ try (Dataset ds1 = opsMetaOnly.openDataset(location);
+ Dataset ds2 = opsMetaOnly.openDataset(location)) {
+ Assertions.assertNotNull(ds1);
+ Assertions.assertNotNull(ds2);
+ scanIndexedFilter(ds2, "id = 5");
+ }
+ Session metaSession = opsMetaOnly.session();
+ CacheStats metaStats = metaSession.metadataCacheStats();
+ Assertions.assertTrue(
+ metaStats.getHits() > 0, "Expected metadata cache hits > 0, got: " + metaStats.getHits());
+ Assertions.assertTrue(
+ metaStats.getSizeBytes() > 0,
+ "Expected metadata cache bytes > 0, got: " + metaStats.getSizeBytes());
+ Assertions.assertEquals(
+ emptySessionBytes, metaSession.sizeBytes() - metaStats.getSizeBytes());
+ }
+
+ // Zero metadata cache, non-zero index cache (10 MiB): index cache holds data after indexed
+ // scan while metadata cache stays at 0 bytes.
+ try (LanceTableOperations opsIndexOnly =
+ new LanceTableOperations(store, schemaOps, idGenerator)) {
+ opsIndexOnly.setCatalogProperties(
+ Map.of(
+ LANCE_SESSION_METADATA_CACHE_SIZE_BYTES, "0",
+ LANCE_SESSION_INDEX_CACHE_SIZE_BYTES, "10485760"));
+ try (Dataset ds1 = opsIndexOnly.openDataset(location)) {
+ scanIndexedFilter(ds1, "id = 5");
+ scanIndexedFilter(ds1, "id = 10");
+ }
+ Session indexSession = opsIndexOnly.session();
+ CacheStats indexOnlyMetaStats = indexSession.metadataCacheStats();
+ Assertions.assertEquals(0L, indexOnlyMetaStats.getHits());
+ Assertions.assertEquals(0L, indexOnlyMetaStats.getSizeBytes());
+ Assertions.assertTrue(
+ indexSession.sizeBytes() > emptySessionBytes,
+ "Expected index cache bytes > emptySessionBytes ("
+ + emptySessionBytes
+ + "), got: "
+ + indexSession.sizeBytes());
+ }
+
+ // Invalid negative value
+ try (LanceTableOperations opsInvalid =
+ new LanceTableOperations(store, schemaOps, idGenerator)) {
+ opsInvalid.setCatalogProperties(Map.of(LANCE_SESSION_METADATA_CACHE_SIZE_BYTES, "-1"));
+ IllegalArgumentException ex =
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> opsInvalid.openDataset(location));
+ Assertions.assertTrue(ex.getMessage().contains("must be greater than or equal to 0"));
+ }
+
+ // Invalid string
+ try (LanceTableOperations opsNan = new LanceTableOperations(store, schemaOps, idGenerator)) {
+ opsNan.setCatalogProperties(Map.of(LANCE_SESSION_INDEX_CACHE_SIZE_BYTES, "not_a_number"));
+ IllegalArgumentException ex2 =
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> opsNan.openDataset(location));
+ Assertions.assertTrue(ex2.getMessage().contains("Invalid long value"));
+ }
+ }
+
+ @Test
+ void testConcurrentOpenWithSharedSession() throws Exception {
+ String location = tempDir.resolve("concurrent_table").toString();
+ Column[] cols = {
+ Column.of("id", Types.IntegerType.get()), Column.of("data", Types.StringType.get())
+ };
+ try (Dataset ignored = lanceTableOps.createDataset(location, cols, Map.of())) {}
+
+ Assertions.assertNotNull(lanceTableOps, "LanceTableOperations must not be null");
+ Assertions.assertFalse(lanceTableOps.isClosed(), "LanceTableOperations must not be closed");
+ Assertions.assertNull(
+ lanceTableOps.getLanceSession(), "Session must not be initialized before opening datasets");
+
+ int threads = 4;
+ int iterationsPerThread = 10;
+ ExecutorService executor = Executors.newFixedThreadPool(threads);
+ try {
+ List<Callable<Void>> tasks = new ArrayList<>();
+ for (int i = 0; i < threads; i++) {
+ tasks.add(
+ () -> {
+ for (int j = 0; j < iterationsPerThread; j++) {
+ try (Dataset ds = lanceTableOps.openDataset(location)) {
+ Assertions.assertNotNull(ds, "Opened dataset must not be null");
+ Assertions.assertNotNull(ds.getSchema(), "Dataset schema must not be null");
+ Assertions.assertEquals(2, ds.getSchema().getFields().size());
+ }
+ }
+ return null;
+ });
+ }
+ List<Future<Void>> futures = executor.invokeAll(tasks, 30, TimeUnit.SECONDS);
+ for (Future<Void> f : futures) {
+ Assertions.assertNotNull(f, "Future task must not be null");
+ f.get();
+ }
+ } finally {
+ executor.shutdownNow();
+ }
+
+ Session session = lanceTableOps.session();
+ Assertions.assertNotNull(session, "Session must be initialized after concurrent opens");
+ Assertions.assertTrue(session.metadataCacheStats().getHits() > 0);
+ }
+
+ @Test
+ void testConcurrentOpenAndCloseWithReadWriteLock() throws Exception {
+ String location = tempDir.resolve("concurrent_open_close").toString();
+ Column[] cols = {Column.of("id", Types.IntegerType.get())};
+ try (Dataset ignored = lanceTableOps.createDataset(location, cols, Map.of())) {}
+
+ int readerThreads = 4;
+ ExecutorService executor = Executors.newFixedThreadPool(readerThreads + 1);
+ try {
+ List<Callable<Void>> tasks = new ArrayList<>();
+ for (int i = 0; i < readerThreads; i++) {
+ tasks.add(
+ () -> {
+ for (int j = 0; j < 20; j++) {
+ try (Dataset ds = lanceTableOps.openDataset(location)) {
+ Assertions.assertEquals(1, ds.getSchema().getFields().size());
+ } catch (IllegalStateException closedEx) {
+ Assertions.assertTrue(
+ closedEx.getMessage().contains("LanceTableOperations is closed"));
+ break;
+ }
+ }
+ return null;
+ });
+ }
+ tasks.add(
+ () -> {
+ Thread.sleep(5);
+ lanceTableOps.close();
+ return null;
+ });
+
+ List<Future<Void>> futures = executor.invokeAll(tasks, 30, TimeUnit.SECONDS);
+ for (Future<Void> f : futures) {
+ f.get();
+ }
+ } finally {
+ executor.shutdownNow();
+ }
+
+ Assertions.assertTrue(lanceTableOps.isClosed());
+ IllegalStateException ex =
+ Assertions.assertThrows(
+ IllegalStateException.class, () -> lanceTableOps.openDataset(location));
+ Assertions.assertTrue(ex.getMessage().contains("LanceTableOperations is closed"));
+ }
+
+ private void createIndexedDataset(String location, int rowCount) throws Exception {
+ Column[] cols = {Column.of("id", Types.IntegerType.get())};
+ try (Dataset emptyDs = lanceTableOps.createDataset(location, cols, Map.of());
+ RootAllocator allocator = new RootAllocator();
+ VectorSchemaRoot root = VectorSchemaRoot.create(emptyDs.getSchema(), allocator)) {
+ IntVector idVector = (IntVector) root.getVector("id");
+ idVector.allocateNew(rowCount);
+ for (int i = 0; i < rowCount; i++) {
+ idVector.setSafe(i, i);
+ }
+ root.setRowCount(rowCount);
+ List<FragmentMetadata> fragments =
+ Fragment.write()
+ .datasetUri(location)
+ .allocator(allocator)
+ .data(root)
+ .writeParams(new WriteParams.Builder().build())
+ .execute();
+ try (SourcedTransaction tx =
+ emptyDs
+ .newTransactionBuilder()
+ .operation(Append.builder().fragments(fragments).build())
+ .build();
+ Dataset committed = tx.commit()) {
+ committed.createIndex(
+ IndexOptions.builder(
+ List.of("id"),
+ IndexType.BTREE,
+ IndexParams.builder()
+ .setScalarIndexParams(ScalarIndexParams.create("btree"))
+ .build())
+ .withIndexName("id_btree_idx")
+ .build());
+ }
+ }
+ }
+
+ private static void scanIndexedFilter(Dataset dataset, String filter) throws Exception {
+ try (LanceScanner scanner =
+ dataset.newScan(new ScanOptions.Builder().filter(filter).useScalarIndex(true).build());
+ ArrowReader reader = scanner.scanBatches()) {
+ int matched = 0;
+ while (reader.loadNextBatch()) {
+ matched += reader.getVectorSchemaRoot().getRowCount();
+ }
+ Assertions.assertEquals(1, matched);
+ }
+ }
+
+ private static Map<String, String> s3StorageOptions(int port) {
+ return Map.of(
+ "endpoint", "http://127.0.0.1:" + port,
+ "allow_http", "true",
+ "access_key_id", "test-access-key",
+ "secret_access_key", "test-secret-key",
+ "region", "us-east-1",
+ "virtual_hosted_style_request", "false");
+ }
+
+ private static HttpServer startS3EndpointServer(
+ Path datasetRoot, String bucket, String tableKey, List<String> requestLog)
+ throws IOException {
+ HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.createContext(
+ "/",
+ exchange -> {
+ requestLog.add(exchange.getRequestMethod() + " " + exchange.getRequestURI());
+ try {
+ handleS3Request(exchange, datasetRoot, bucket, tableKey);
+ } catch (Exception e) {
+ byte[] err = e.toString().getBytes(StandardCharsets.UTF_8);
+ exchange.sendResponseHeaders(500, err.length);
+ try (OutputStream os = exchange.getResponseBody()) {
+ os.write(err);
+ }
+ }
+ });
+ server.start();
+ return server;
+ }
+
+ private static void handleS3Request(
+ HttpExchange exchange, Path datasetRoot, String bucket, String tableKey) throws IOException {
+ String method = exchange.getRequestMethod();
+ String rawPath = exchange.getRequestURI().getPath();
+ String rawQuery = exchange.getRequestURI().getRawQuery();
+ String bucketPrefix = "/" + bucket;
+
+ if ("GET".equals(method) && rawQuery != null && rawQuery.contains("list-type=2")) {
+ String prefix = "";
+ for (String param : rawQuery.split("&")) {
+ int eq = param.indexOf('=');
+ if (eq > 0 && "prefix".equals(param.substring(0, eq))) {
+ prefix = URLDecoder.decode(param.substring(eq + 1), StandardCharsets.UTF_8);
+ }
+ }
+ List<Path> files;
+ try (Stream<Path> walk = Files.walk(datasetRoot)) {
+ files = walk.filter(Files::isRegularFile).sorted().collect(Collectors.toList());
+ }
+ StringBuilder xml = new StringBuilder();
+ xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
+ .append("<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">")
+ .append("<Name>")
+ .append(bucket)
+ .append("</Name>")
+ .append("<Prefix>")
+ .append(prefix)
+ .append("</Prefix>")
+ .append("<MaxKeys>1000</MaxKeys>")
+ .append("<IsTruncated>false</IsTruncated>");
+ int count = 0;
+ for (Path file : files) {
+ String rel = datasetRoot.relativize(file).toString().replace('\\', '/');
+ String key = tableKey + "/" + rel;
+ if (key.startsWith(prefix)) {
+ count++;
+ String etag = md5Hex(Files.readAllBytes(file));
+ xml.append("<Contents>")
+ .append("<Key>")
+ .append(key)
+ .append("</Key>")
+ .append("<LastModified>2026-01-01T00:00:00.000Z</LastModified>")
+ .append("<ETag>\"")
+ .append(etag)
+ .append("\"</ETag>")
+ .append("<Size>")
+ .append(Files.size(file))
+ .append("</Size>")
+ .append("</Contents>");
+ }
+ }
+ xml.append("<KeyCount>").append(count).append("</KeyCount></ListBucketResult>");
+ byte[] body = xml.toString().getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().set("Content-Type", "application/xml");
+ exchange.sendResponseHeaders(200, body.length);
+ try (OutputStream os = exchange.getResponseBody()) {
+ os.write(body);
+ }
+ return;
+ }
+
+ String objectKey =
+ rawPath.startsWith(bucketPrefix + "/")
+ ? rawPath.substring(bucketPrefix.length() + 1)
+ : rawPath.startsWith("/") ? rawPath.substring(1) : rawPath;
+ String keyPrefix = tableKey + "/";
+ if (!objectKey.startsWith(keyPrefix)) {
+ exchange.sendResponseHeaders(404, -1);
+ exchange.close();
+ return;
+ }
+ Path target = datasetRoot.resolve(objectKey.substring(keyPrefix.length())).normalize();
+ if (!target.startsWith(datasetRoot) || !Files.isRegularFile(target)) {
+ exchange.sendResponseHeaders(404, -1);
+ exchange.close();
+ return;
+ }
+
+ byte[] allBytes = Files.readAllBytes(target);
+ exchange.getResponseHeaders().set("Accept-Ranges", "bytes");
+ exchange.getResponseHeaders().set("ETag", "\"" + md5Hex(allBytes) + "\"");
+ if ("HEAD".equals(method)) {
+ exchange.getResponseHeaders().set("Content-Length", String.valueOf(allBytes.length));
+ exchange.sendResponseHeaders(200, -1);
+ exchange.close();
+ return;
+ }
+
+ String rangeHeader = exchange.getRequestHeaders().getFirst("Range");
+ if (rangeHeader != null && rangeHeader.startsWith("bytes=")) {
+ String spec = rangeHeader.substring("bytes=".length()).trim();
+ int dash = spec.indexOf('-');
+ String startStr = spec.substring(0, dash);
+ String endStr = spec.substring(dash + 1);
+ int start =
+ startStr.isEmpty()
+ ? Math.max(0, allBytes.length - Integer.parseInt(endStr))
+ : Integer.parseInt(startStr);
+ int end =
+ startStr.isEmpty() || endStr.isEmpty()
+ ? allBytes.length - 1
+ : Math.min(allBytes.length - 1, Integer.parseInt(endStr));
+ byte[] slice = Arrays.copyOfRange(allBytes, start, end + 1);
+ exchange
+ .getResponseHeaders()
+ .set("Content-Range", String.format("bytes %d-%d/%d", start, end, allBytes.length));
+ exchange.sendResponseHeaders(206, slice.length);
+ try (OutputStream os = exchange.getResponseBody()) {
+ os.write(slice);
+ }
+ return;
+ }
+
+ exchange.sendResponseHeaders(200, allBytes.length);
+ try (OutputStream os = exchange.getResponseBody()) {
+ os.write(allBytes);
+ }
+ }
+
+ private static String md5Hex(byte[] bytes) {
+ try {
+ byte[] digest = MessageDigest.getInstance("MD5").digest(bytes);
+ StringBuilder sb = new StringBuilder(digest.length * 2);
+ for (byte b : digest) {
+ sb.append(String.format("%02x", b));
+ }
+ return sb.toString();
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException(e);
+ }
+ }
}
diff --git a/docs/lakehouse-generic-catalog.md b/docs/lakehouse-generic-catalog.md
index 109ddfc8e4..6ca4594fba 100644
--- a/docs/lakehouse-generic-catalog.md
+++ b/docs/lakehouse-generic-catalog.md
@@ -44,13 +44,19 @@ For detailed information on available operations, see [Manage Relational Metadat
### Catalog Properties
-| 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 |
+| 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 |
+| `lance.session.metadata-cache-size-bytes` | The metadata cache size in bytes for the shared Lance session. Defaults to 1 GiB (`1073741824`). Set to `0` to disable. | `1073741824` | No |
+| `lance.session.index-cache-size-bytes` | The index cache size in bytes for the shared Lance session. Defaults to 128 MiB (`134217728`). Set to `0` to disable. | `134217728` | No |
+
+:::note
+Lance's native `Session` also caches storage handlers in an internal `ObjectStoreRegistry` keyed by storage endpoint, scheme, and options, holding weak references to the store instances. Once a dataset closes, the store itself can be reclaimed, while the registry key can still retain old storage options (such as rotated credentials) until the catalog closes, outside both cache byte limits. Upstream added pruning for these keys in [Lance PR #10385](https://github.com/lance-format/lance/pull/10385); `lance-core` 12.0.0 used by Gravitino predates that fix.
+:::
#### Pluggable table location provider
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 4b238a4504..eef0bf8113 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
@@ -45,5 +45,13 @@ public class LanceConstants {
/** 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";
+ /** Lance session metadata cache size in bytes. */
+ public static final String LANCE_SESSION_METADATA_CACHE_SIZE_BYTES =
+ "lance.session.metadata-cache-size-bytes";
+
+ /** Lance session index cache size in bytes. */
+ public static final String LANCE_SESSION_INDEX_CACHE_SIZE_BYTES =
+ "lance.session.index-cache-size-bytes";
+
public static final String LANCE_TABLE_FORMAT = "lance";
}