diff --git a/fe/fe-connector/fe-connector-lance/pom.xml b/fe/fe-connector/fe-connector-lance/pom.xml index ced00c7e486f7a..c9387a820e0a68 100644 --- a/fe/fe-connector/fe-connector-lance/pom.xml +++ b/fe/fe-connector/fe-connector-lance/pom.xml @@ -110,6 +110,28 @@ under the License. commons-lang3 + + + com.github.ben-manes.caffeine + caffeine + 2.9.3 + + + + org.checkerframework + checker-qual + + + com.google.errorprone + error_prone_annotations + + + + org.apache.logging.log4j log4j-api diff --git a/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceCatalogClient.java b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceCatalogClient.java index 54408ae5d938ff..6103acc047b373 100644 --- a/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceCatalogClient.java +++ b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceCatalogClient.java @@ -17,17 +17,22 @@ package org.apache.doris.connector.lance; +import org.apache.doris.connector.lance.LanceMetadataMetrics.Operation; +import org.apache.doris.connector.lance.LanceMetadataMetrics.Stage; import org.apache.doris.connector.spi.DorisConnectorException; import org.apache.doris.filesystem.properties.StorageProperties; +import com.github.benmanes.caffeine.cache.Ticker; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; +import org.apache.arrow.vector.types.pojo.Schema; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.lance.Dataset; import org.lance.Fragment; import org.lance.ReadOptions; +import org.lance.Session; import org.lance.namespace.LanceNamespace; import org.lance.namespace.errors.TableVersionNotFoundException; import org.lance.namespace.model.ListNamespacesRequest; @@ -46,61 +51,80 @@ /** * One catalog's namespace access, snapshot reads and native resource lifetime. * - *

The namespace and its Arrow allocator are opened on first use, never while the connector is built: - * an FE replaying the edit log builds every catalog, and loading the JNI library or reaching storage there - * could stop it from starting. Every call pins the plugin's classloader as the thread context classloader, - * because the engine does not pin it for metadata calls and lance-core resolves classes by name. + *

The native resources form a generation: the namespace, the Arrow allocator the reads draw on, the Lance + * {@link Session} every dataset FE opens shares, and the namespace client with its cache of described table + * access. A generation is opened on first use, never while the connector is built: an FE replaying the edit log + * builds every catalog, and loading the JNI library or reaching storage there could stop it from starting. Every + * call runs on one generation from start to end, and pins the plugin's classloader as the thread context + * classloader, because the engine does not pin it for metadata calls and lance-core resolves classes by name. * - *

Closing retires the client at once; the last call still in flight releases the native resources. - * The engine reclaims a replaced or dropped catalog's connector on a background thread without waiting - * for its statements, and closing the namespace or the allocator under a running JNI call is not safe. + *

The Session caches the manifests and the fragment, file and index metadata of the versions FE reads, so a + * later statement planning a version already read reads it from memory. {@link #refresh} (REFRESH CATALOG) + * retires the generation, and the next call opens a new one, whose cold Session reads afresh a dataset replaced at + * the same URI. Closing retires it too and refuses new calls. A retired generation is released by its last call + * in flight: the engine reclaims a replaced or dropped catalog's connector on a background thread without waiting + * for its statements, and closing the namespace, the Session or the allocator under a running JNI call is not + * safe. */ final class LanceCatalogClient implements AutoCloseable { private static final Logger LOG = LogManager.getLogger(LanceCatalogClient.class); /** - * Metadata cache of each dataset FE opens. FE plans from manifests; describing indexes reads index - * metadata, not index pages, so no index cache is kept. + * The capacities of each generation's Session, held in native memory outside the Arrow limit: manifests and + * fragment and file metadata, and the index metadata that planning index segments reads. They belong to the + * Session, not to each dataset opened with it. */ - private static final long METADATA_CACHE_SIZE_BYTES = 64L * 1024 * 1024; + static final long SESSION_METADATA_CACHE_BYTES = 64L * 1024 * 1024; + static final long SESSION_INDEX_CACHE_BYTES = 128L * 1024 * 1024; private final LanceCatalogProperties properties; private final Supplier> storageProperties; private final LongSupplier arrowMemoryLimitBytes; + private final ResourceFactory resources; + private final Ticker ticker; /** The catalog's secrets to strip from provider errors: its REST credentials and credential headers. */ private final List catalogSecrets; - private BufferAllocator allocator; - private LanceNamespace namespace; - private LanceNamespaceClient namespaceClient; - private Map namespaceStorageOptions = Collections.emptyMap(); - private int callsInFlight; + /** The generation new calls run on; none before the first call and after a refresh. */ + private Generation current; private boolean closed; /** * @param storageProperties the catalog's storage keys bound by the engine; read on first use, like the * memory limit, so that building the connector stays free of anything that can fail - * @param arrowMemoryLimitBytes the Arrow memory this catalog's metadata reads may use + * @param arrowMemoryLimitBytes the Arrow memory each generation's metadata reads may use */ LanceCatalogClient(LanceCatalogProperties properties, Supplier> storageProperties, LongSupplier arrowMemoryLimitBytes) { + this(properties, storageProperties, arrowMemoryLimitBytes, new LanceResourceFactory(), + Ticker.systemTicker()); + } + + /** + * @param resources where each generation's allocator, namespace and Session come from + * @param ticker the clock of the table-access cache + */ + LanceCatalogClient(LanceCatalogProperties properties, Supplier> storageProperties, + LongSupplier arrowMemoryLimitBytes, ResourceFactory resources, Ticker ticker) { this.properties = properties; this.storageProperties = storageProperties; this.arrowMemoryLimitBytes = arrowMemoryLimitBytes; + this.resources = resources; + this.ticker = ticker; this.catalogSecrets = properties.secretValues(); } List listDatabaseNames() { - return call(namespaceClient -> namespaceClient.listDatabaseNames(), "list Lance namespaces"); + return call(generation -> generation.namespaceClient.listDatabaseNames(), "list Lance namespaces"); } List listTableNames(String dbName) { - return call(namespaceClient -> namespaceClient.listTableNames(dbName), + return call(generation -> generation.namespaceClient.listTableNames(dbName), "list the tables of Lance database " + dbName); } boolean tableExists(String dbName, String tableName) { - return call(namespaceClient -> namespaceClient.tableExists(dbName, tableName), + return call(generation -> generation.namespaceClient.tableExists(dbName, tableName), "check Lance table " + dbName + "." + tableName); } @@ -110,10 +134,10 @@ boolean tableExists(String dbName, String tableName) { * credentials. */ void testConnection() { - call(namespaceClient -> { + call(generation -> { List parent = properties.getParentNamespace(); - namespace.listTables(new ListTablesRequest().id(new ArrayList<>(parent)).limit(1)); - namespace.listNamespaces(new ListNamespacesRequest().id(new ArrayList<>(parent)).limit(1)); + generation.namespace.listTables(new ListTablesRequest().id(new ArrayList<>(parent)).limit(1)); + generation.namespace.listNamespaces(new ListNamespacesRequest().id(new ArrayList<>(parent)).limit(1)); return null; }, "connect"); } @@ -121,11 +145,14 @@ void testConnection() { /** * Reads the planning metadata of one table at {@code version}, or at the newest version in storage * when it is empty. Every dataset is read by its URI and a version, as the BE reads it. + * + * @param metrics the statement's totals of the table, which the read is timed into */ - LanceTableMetadata loadTableMetadata(String dbName, String tableName, OptionalLong version) { - return readTable(dbName, tableName, version, (access, readAllocator) -> { - try (Dataset dataset = openDataset(readAllocator, access, version)) { - return readMetadata(dataset, access); + LanceTableMetadata loadTableMetadata(String dbName, String tableName, OptionalLong version, + LanceMetadataMetrics metrics) { + return readTable(dbName, tableName, version, metrics, (generation, access, readAllocator, timer) -> { + try (Dataset dataset = openDataset(generation, readAllocator, access, version, timer)) { + return readMetadata(dataset, access, timer); } }); } @@ -134,11 +161,12 @@ LanceTableMetadata loadTableMetadata(String dbName, String tableName, OptionalLo * Reads the field ids and the user indexes of one table at the fixed {@code version}, for planning ranges * over index segments. */ - LanceIndexMetadata loadIndexMetadata(String dbName, String tableName, long version) { + LanceIndexMetadata loadIndexMetadata(String dbName, String tableName, long version, + LanceMetadataMetrics metrics) { OptionalLong pinned = OptionalLong.of(version); - return readTable(dbName, tableName, pinned, (access, readAllocator) -> { - try (Dataset dataset = openDataset(readAllocator, access, pinned)) { - return LanceIndexMetadata.read(dataset); + return readTable(dbName, tableName, pinned, metrics, (generation, access, readAllocator, timer) -> { + try (Dataset dataset = openDataset(generation, readAllocator, access, pinned, timer)) { + return LanceIndexMetadata.read(dataset, timer); } }); } @@ -148,40 +176,69 @@ LanceIndexMetadata loadIndexMetadata(String dbName, String tableName, long versi * the commit times the manifests record; see {@link LanceSnapshotResolver#versionAtOrBefore}. */ LanceTableMetadata loadTableMetadataAtOrBefore(String dbName, String tableName, long timestampMillis, - String requestedText) { + String requestedText, LanceMetadataMetrics metrics) { String what = dbName + "." + tableName; - return readTable(dbName, tableName, OptionalLong.empty(), (access, readAllocator) -> { - long version; - try (Dataset latest = openDataset(readAllocator, access, OptionalLong.empty())) { - try { - version = LanceSnapshotResolver.versionAtOrBefore(latest.listVersions(), timestampMillis, - requestedText); - } catch (LanceSnapshotResolver.NoVersionAtOrBeforeException e) { - throw new UserFacingException("Lance table " + what + " has no version at or before '" - + requestedText + "'"); - } catch (LanceSnapshotResolver.HistoryRemovedException e) { - throw new UserFacingException("Lance cannot resolve FOR TIME AS OF '" + requestedText - + "' on " + what + ": version " + e.getVersion() - + ", which may hold the state at that time, no longer exists"); - } - } - LOG.debug("Resolved Lance FOR TIME AS OF '{}' to version {} from manifest commit times", - requestedText, version); - try (Dataset dataset = openDataset(readAllocator, access, OptionalLong.of(version))) { - return readMetadata(dataset, access); - } - }); + return readTable(dbName, tableName, OptionalLong.empty(), metrics, + (generation, access, readAllocator, timer) -> { + long version; + try (Dataset latest = openDataset(generation, readAllocator, access, OptionalLong.empty(), + timer)) { + version = timer.measure(Stage.VERSION_RESOLVE, + () -> versionAtOrBefore(latest, timestampMillis, requestedText, what)); + } + LOG.debug("Resolved Lance FOR TIME AS OF '{}' to version {} from manifest commit times", + requestedText, version); + try (Dataset dataset = openDataset(generation, readAllocator, access, OptionalLong.of(version), + timer)) { + return readMetadata(dataset, access, timer); + } + }); + } + + /** + * REFRESH CATALOG: retires the current generation, so that the next call opens a new namespace, allocator and + * Session. Opens nothing and waits for nothing: calls in flight finish on the retired generation, and the + * last of them releases it. + */ + void refresh() { + Generation idle = retireCurrent(); + if (idle != null) { + idle.closeResources(); + } + } + + /** + * REFRESH TABLE / DATABASE: the next read describes its table again; the Session and its cached metadata + * stay, as {@link LanceConnector#invalidateDb} explains. Opens nothing: before the first call nothing is + * cached. + */ + void invalidateTableAccess() { + Generation generation; + synchronized (this) { + generation = current; + } + if (generation != null) { + generation.namespaceClient.invalidateTableAccessCache(); + } } /** Resolves the table's access, then reads it with a child allocator that this one read owns. */ - private T readTable(String dbName, String tableName, OptionalLong version, TableRead read) { + private T readTable(String dbName, String tableName, OptionalLong version, LanceMetadataMetrics metrics, + TableRead read) { String what = dbName + "." + tableName; - return call(namespaceClient -> { + return call(generation -> { LanceTableAccess access = null; - try (BufferAllocator readAllocator = allocator.newChildAllocator( - "lance-metadata-read", 0, allocator.getLimit())) { - access = namespaceClient.resolveTableAccess(dbName, tableName); - return read.read(access, readAllocator); + try (LanceMetadataMetrics.Timer timer = metrics.start(Operation.METADATA_READ)) { + T result; + try (BufferAllocator readAllocator = generation.allocator.newChildAllocator( + "lance-metadata-read", 0, generation.allocator.getLimit())) { + access = timer.measure(Stage.TABLE_ACCESS, + () -> generation.namespaceClient.resolveTableAccess(dbName, tableName)); + result = read.read(generation, access, readAllocator, timer); + } + // Successful only once the read's datasets and allocator are released. + timer.succeeded(); + return result; } catch (UserFacingException e) { throw new DorisConnectorException(e.getMessage()); } catch (DorisConnectorException e) { @@ -190,7 +247,7 @@ private T readTable(String dbName, String tableName, OptionalLong version, T throw e; } catch (Exception e) { String uri = access == null ? null : access.getDatasetUri(); - Map options = access == null ? namespaceStorageOptions : access.getStorageOptions(); + Map options = access == null ? generation.storageOptions : access.getStorageOptions(); if (version.isPresent() && isVersionNotFound(e)) { throw new DorisConnectorException("Lance version " + version.getAsLong() + " of " + what + " was not found", @@ -202,26 +259,48 @@ private T readTable(String dbName, String tableName, OptionalLong version, T }, "load Lance table metadata for " + what); } - private static LanceTableMetadata readMetadata(Dataset dataset, LanceTableAccess access) { - List fragments = new ArrayList<>(); - for (Fragment fragment : dataset.getFragments()) { - fragments.add(new LanceFragmentInfo(Integer.toUnsignedLong(fragment.getId()), - fragment.metadata().getNumRows(), fragment.metadata().getPhysicalRows())); + private static LanceTableMetadata readMetadata(Dataset dataset, LanceTableAccess access, + LanceMetadataMetrics.Timer timer) { + Schema schema = timer.measure(Stage.SCHEMA, dataset::getSchema); + List fragments = timer.measure(Stage.FRAGMENTS, () -> { + List infos = new ArrayList<>(); + for (Fragment fragment : dataset.getFragments()) { + infos.add(new LanceFragmentInfo(Integer.toUnsignedLong(fragment.getId()), + fragment.metadata().getNumRows(), fragment.metadata().getPhysicalRows())); + } + return infos; + }); + return new LanceTableMetadata(access, dataset.version(), schema, fragments); + } + + private static long versionAtOrBefore(Dataset latest, long timestampMillis, String requestedText, + String what) { + try { + return LanceSnapshotResolver.versionAtOrBefore(latest.listVersions(), timestampMillis, requestedText); + } catch (LanceSnapshotResolver.NoVersionAtOrBeforeException e) { + throw new UserFacingException("Lance table " + what + " has no version at or before '" + + requestedText + "'"); + } catch (LanceSnapshotResolver.HistoryRemovedException e) { + throw new UserFacingException("Lance cannot resolve FOR TIME AS OF '" + requestedText + + "' on " + what + ": version " + e.getVersion() + + ", which may hold the state at that time, no longer exists"); } - return new LanceTableMetadata(access, dataset.version(), dataset.getSchema(), fragments); } - private static Dataset openDataset(BufferAllocator readAllocator, LanceTableAccess access, - OptionalLong version) { + /** + * Opens the dataset with the generation's Session: its caches, not the dataset, decide how much metadata is + * kept, and the next open of the same version reads it from them. + */ + private static Dataset openDataset(Generation generation, BufferAllocator readAllocator, + LanceTableAccess access, OptionalLong version, LanceMetadataMetrics.Timer timer) { ReadOptions.Builder options = new ReadOptions.Builder() .setStorageOptions(access.getStorageOptions()) - .setIndexCacheSizeBytes(0) - .setMetadataCacheSizeBytes(METADATA_CACHE_SIZE_BYTES); + .setSession(generation.session); if (version.isPresent()) { options.setVersion(version.getAsLong()); } - return Dataset.open().allocator(readAllocator).uri(access.getDatasetUri()) - .readOptions(options.build()).build(); + return timer.measure(Stage.DATASET_OPEN, () -> Dataset.open().allocator(readAllocator) + .uri(access.getDatasetUri()).readOptions(options.build()).build()); } /** @@ -244,19 +323,19 @@ private static boolean isVersionNotFound(Throwable throwable) { } /** - * Runs one operation against the namespace: counts it in, opening the namespace on first use, pins the - * plugin classloader, and turns a provider failure into a sanitized connector error. + * Runs one operation on the current generation, opening it on first use: pins the plugin classloader for + * it, and turns a provider failure into a sanitized connector error. */ - private T call(NamespaceCall body, String operation) { - LanceNamespaceClient client = enter(); + private T call(GenerationCall body, String operation) { + Generation generation = enter(); ClassLoader previous = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(LanceCatalogClient.class.getClassLoader()); - return body.call(client); + return body.call(generation); } catch (DorisConnectorException e) { throw e; } catch (Exception e) { - throw LanceErrorMessages.failure("Failed to " + operation, e, null, namespaceStorageOptions, + throw LanceErrorMessages.failure("Failed to " + operation, e, null, generation.storageOptions, catalogSecrets); } catch (LinkageError e) { // Reading a schema goes through Arrow's C Data interface, whose own JNI library loads on first @@ -265,25 +344,27 @@ private T call(NamespaceCall body, String operation) { + " could not be loaded: " + e, e); } finally { Thread.currentThread().setContextClassLoader(previous); - leave(); + leave(generation); } } - /** Counts the calling thread in, opening the namespace on first use. */ - private synchronized LanceNamespaceClient enter() { + /** Counts the calling thread in on the current generation, opening one when there is none. */ + private synchronized Generation enter() { if (closed) { throw new DorisConnectorException("Lance catalog resources have been closed"); } - if (namespaceClient == null) { - openNamespace(); + if (current == null) { + current = openGeneration(); } - callsInFlight++; - return namespaceClient; + current.callsInFlight++; + return current; } - private void openNamespace() { + private Generation openGeneration() { ClassLoader previous = Thread.currentThread().getContextClassLoader(); - BufferAllocator newAllocator = null; + BufferAllocator allocator = null; + LanceNamespace namespace = null; + Session session = null; Map storageOptions = Collections.emptyMap(); try { Thread.currentThread().setContextClassLoader(LanceCatalogClient.class.getClassLoader()); @@ -305,18 +386,23 @@ private void openNamespace() { namespaceProperties.put("root", warehouse); storageOptions.forEach((key, value) -> namespaceProperties.put("storage." + key, value)); } - newAllocator = new RootAllocator(limit); - namespace = LanceNamespace.connect(implementation, namespaceProperties, newAllocator); - allocator = newAllocator; - namespaceStorageOptions = storageOptions; - namespaceClient = new LanceNamespaceClient(namespace, properties.isRest(), properties.getRootDatabase(), - properties.getParentNamespace(), storage); + allocator = resources.newAllocator(limit); + namespace = resources.connect(implementation, namespaceProperties, allocator); + session = resources.newSession(); + LanceNamespaceClient namespaceClient = new LanceNamespaceClient(namespace, properties.isRest(), + properties.getRootDatabase(), properties.getParentNamespace(), storage, + properties.getTableAccessCacheTtlSeconds(), ticker); + return new Generation(allocator, namespace, session, namespaceClient, storageOptions); } catch (LinkageError e) { - closeResource(newAllocator); + closeResource(namespace); + closeResource(session); + closeResource(allocator); throw new DorisConnectorException("Failed to load the Lance JNI library. FE loads it from" + " lance-core in plugins/connector/lance/lib: " + e, e); } catch (RuntimeException e) { - closeResource(newAllocator); + closeResource(namespace); + closeResource(session); + closeResource(allocator); // The options this attempt built, which the namespace may echo back in its error. throw LanceErrorMessages.failure("Failed to initialize Lance " + properties.getCatalogType() + " catalog", e, null, storageOptions, catalogSecrets); @@ -325,37 +411,42 @@ private void openNamespace() { } } - /** Counts the calling thread out; the last call to leave a closed client releases the resources. */ - private void leave() { + /** Counts the calling thread out; the last call to leave a retired generation releases it. */ + private void leave(Generation generation) { synchronized (this) { - callsInFlight--; - if (!closed || callsInFlight > 0) { + generation.callsInFlight--; + if (!generation.retired || generation.callsInFlight > 0) { return; } } - closeResources(); + generation.closeResources(); + } + + /** Retires the current generation; returns it when no call runs on it, for the caller to release. */ + private synchronized Generation retireCurrent() { + Generation retiring = current; + current = null; + if (retiring == null) { + return null; + } + retiring.retired = true; + return retiring.callsInFlight == 0 ? retiring : null; } /** Retires the client at once; its last call in flight, or this call when there is none, cleans up. */ @Override public void close() { + Generation idle; synchronized (this) { if (closed) { return; } closed = true; - if (callsInFlight > 0) { - return; - } + idle = retireCurrent(); + } + if (idle != null) { + idle.closeResources(); } - closeResources(); - } - - private void closeResources() { - closeResource(namespace); - closeResource(allocator); - namespace = null; - allocator = null; } private static void closeResource(Object resource) { @@ -369,14 +460,71 @@ private static void closeResource(Object resource) { } } + /** Creates the resources of each generation; the production factory uses Arrow's and lance-core's. */ + interface ResourceFactory { + BufferAllocator newAllocator(long limit); + + LanceNamespace connect(String implementation, Map properties, BufferAllocator allocator); + + Session newSession(); + } + + private static final class LanceResourceFactory implements ResourceFactory { + @Override + public BufferAllocator newAllocator(long limit) { + return new RootAllocator(limit); + } + + @Override + public LanceNamespace connect(String implementation, Map properties, + BufferAllocator allocator) { + return LanceNamespace.connect(implementation, properties, allocator); + } + + @Override + public Session newSession() { + return Session.builder().metadataCacheSizeBytes(SESSION_METADATA_CACHE_BYTES) + .indexCacheSizeBytes(SESSION_INDEX_CACHE_BYTES).build(); + } + } + + /** One generation's native resources, and the calls running on it; the counters are guarded by the client. */ + private static final class Generation { + private final BufferAllocator allocator; + private final LanceNamespace namespace; + private final Session session; + private final LanceNamespaceClient namespaceClient; + /** The options a filesystem namespace reads storage with; what a failure before a describe may echo. */ + private final Map storageOptions; + private int callsInFlight; + private boolean retired; + + private Generation(BufferAllocator allocator, LanceNamespace namespace, Session session, + LanceNamespaceClient namespaceClient, Map storageOptions) { + this.allocator = allocator; + this.namespace = namespace; + this.session = session; + this.namespaceClient = namespaceClient; + this.storageOptions = storageOptions; + } + + /** Closes the namespace, then the Session, then the allocator; a failure closing one skips none. */ + private void closeResources() { + closeResource(namespace); + closeResource(session); + closeResource(allocator); + } + } + @FunctionalInterface - private interface NamespaceCall { - T call(LanceNamespaceClient namespaceClient) throws Exception; + private interface GenerationCall { + T call(Generation generation) throws Exception; } @FunctionalInterface private interface TableRead { - T read(LanceTableAccess access, BufferAllocator readAllocator) throws Exception; + T read(Generation generation, LanceTableAccess access, BufferAllocator readAllocator, + LanceMetadataMetrics.Timer timer) throws Exception; } /** A failure whose message is already what the user should read; it is neither wrapped nor sanitized. */ diff --git a/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceCatalogProperties.java b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceCatalogProperties.java index cfdac453a22d7e..4b443c2f1a19cb 100644 --- a/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceCatalogProperties.java +++ b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceCatalogProperties.java @@ -39,8 +39,9 @@ /** * Everything a user writes in {@code CREATE CATALOG} for a Lance catalog, bound and checked. * - *

The keys and their rules are the ones Lance catalogs have had since 4.1, unchanged: images written by - * those versions persist the raw property map, and this class must accept it as it is. Settings that are + *

The keys and their rules are the ones Lance catalogs have had since 4.1 (the table-access cache TTL since + * 4.2), unchanged: images written by those versions persist the raw property map, and this class must accept it + * as it is. Settings that are * one-per-FE rather than one-per-catalog live in the plugin's {@code lance.conf} ({@link LanceConf}). * *

{@link #of(Map)} touches neither storage nor any {@code org.lance.*} type: it runs at CREATE, again on @@ -62,6 +63,12 @@ public final class LanceCatalogProperties { public static final String ROOT_DATABASE = "lance.namespace.root_database"; public static final String DEFAULT_DELIMITER = "$"; public static final String DEFAULT_ROOT_DATABASE = "default"; + /** + * How long a table's dataset URI and storage options, as the namespace describes them, are reused before the + * table is described again; 0 describes it on every read. See {@link LanceNamespaceClient}. + */ + public static final String TABLE_ACCESS_CACHE_TTL_SECONDS = "lance.table_access_cache_ttl_seconds"; + public static final int DEFAULT_TABLE_ACCESS_CACHE_TTL_SECONDS = 60; /** Every REST-only key starts with this; a filesystem catalog rejects all of them. */ public static final String REST_PREFIX = "lance.rest."; @@ -116,6 +123,11 @@ public final class LanceCatalogProperties { description = "The Doris database name representing the catalog's root namespace. Default: default.") private String rootDatabase = DEFAULT_ROOT_DATABASE; + @ConnectorProperty(names = {TABLE_ACCESS_CACHE_TTL_SECONDS}, required = false, + description = "Maximum lifetime of cached table URIs and access options in seconds. " + + "Default: 60. Set to 0 to describe the table on every read.") + private int tableAccessCacheTtlSeconds = DEFAULT_TABLE_ACCESS_CACHE_TTL_SECONDS; + @ConnectorProperty(names = {REST_URI}, required = false, description = "The HTTP or HTTPS endpoint of the Lance REST namespace service.") private String restUri; @@ -171,6 +183,10 @@ public static LanceCatalogProperties of(Map properties) { } private void validateCommonProperties() { + if (tableAccessCacheTtlSeconds < 0) { + throw new IllegalArgumentException("Property '" + TABLE_ACCESS_CACHE_TTL_SECONDS + + "' must be non-negative"); + } if (namespaceDelimiter.isEmpty() || namespaceDelimiter.indexOf('\\') >= 0) { throw new IllegalArgumentException("Property '" + NAMESPACE_DELIMITER + "' cannot be empty or contain the escape character '\\'"); @@ -398,6 +414,11 @@ public List getParentNamespace() { return parentNamespace; } + /** See {@link #TABLE_ACCESS_CACHE_TTL_SECONDS}; never negative. */ + public int getTableAccessCacheTtlSeconds() { + return tableAccessCacheTtlSeconds; + } + /** * The catalog's properties as written, unmodifiable. It contains credentials: pass it only to code * that keeps it internal. diff --git a/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceConf.java b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceConf.java index 234b8798112ad7..64569d07521632 100644 --- a/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceConf.java +++ b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceConf.java @@ -33,7 +33,9 @@ public final class LanceConf { /** * Java Arrow memory, in bytes, that one catalog may use while it reads dataset metadata. Must be - * positive. + * positive. It bounds each generation of the catalog's resources ({@link LanceCatalogClient}); after a + * REFRESH CATALOG, each older generation still serving a read keeps its own limit in use until its last read + * ends. The Lance Sessions' caches are native memory and not counted. */ public static final String CONF_ARROW_MEMORY_LIMIT_BYTES = "lance_catalog_arrow_memory_limit_bytes"; diff --git a/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceConnector.java b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceConnector.java index 6d79a2a98404f2..72d9a140978940 100644 --- a/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceConnector.java +++ b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceConnector.java @@ -58,10 +58,20 @@ public final class LanceConnector implements Connector { private final LanceCatalogClient client; public LanceConnector(Map properties, ConnectorContext context) { - this.props = LanceCatalogProperties.of(properties); + this(LanceCatalogProperties.of(properties), context); + } + + private LanceConnector(LanceCatalogProperties props, ConnectorContext context) { + this(props, context, new LanceCatalogClient(props, + () -> context.getStorageContext().getStorageProperties(), + () -> LanceConf.arrowMemoryLimitBytes(context))); + } + + /** Over a catalog client built by the caller, which tests give recording resources. */ + LanceConnector(LanceCatalogProperties props, ConnectorContext context, LanceCatalogClient client) { + this.props = props; this.context = context; - this.client = new LanceCatalogClient(props, () -> context.getStorageContext().getStorageProperties(), - () -> LanceConf.arrowMemoryLimitBytes(context)); + this.client = client; } @Override @@ -106,6 +116,34 @@ public ConnectorTestResult testConnection(ConnectorSession session) { } } + /** + * REFRESH CATALOG: the next call opens a new namespace and a cold Lance Session, which reads afresh a + * dataset replaced at the same URI. The engine also lands here on replay when it cannot name the database. + */ + @Override + public void invalidateAll() { + client.refresh(); + } + + /** + * REFRESH DATABASE: every table is described again on its next read, and the Session keeps its cached + * metadata. That is safe while a dataset lives: a committed version never changes, and a read of the newest + * version still finds the newest one. A dataset deleted and written again at the same URI starts its + * versions over, though, and for one with V1 manifest names Lance keys a version's index list by the version + * alone, so the Session can serve the deleted dataset's indexes for the new one: that case needs REFRESH + * CATALOG ({@link #invalidateAll}). + */ + @Override + public void invalidateDb(String dbName) { + client.invalidateTableAccess(); + } + + /** REFRESH TABLE: as {@link #invalidateDb}, for every table, since a described table access is cheap. */ + @Override + public void invalidateTable(String dbName, String tableName) { + client.invalidateTableAccess(); + } + @Override public void close() { client.close(); diff --git a/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceConnectorMetadata.java b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceConnectorMetadata.java index 287683fc9bd292..7524cf1d68537c 100644 --- a/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceConnectorMetadata.java +++ b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceConnectorMetadata.java @@ -219,8 +219,12 @@ public ConnectorTableHandle applySnapshot(ConnectorSession session, ConnectorTab // ========= internals ========= private LanceTableMetadata metadata(ConnectorSession session, LanceTableHandle handle) { + // Looked up before the memo's loader runs: a loader may not use the statement scope itself. + LanceMetadataMetrics metrics = LanceMetadataMetrics.forTable(session, handle.getDbName(), + handle.getTableName()); return LanceStatementScope.sharedMetadata(session, handle, - () -> client.loadTableMetadata(handle.getDbName(), handle.getTableName(), handle.getVersion())); + () -> client.loadTableMetadata(handle.getDbName(), handle.getTableName(), handle.getVersion(), + metrics)); } private LanceTableMetadata metadataAtOrBefore(ConnectorSession session, LanceTableHandle handle, @@ -232,7 +236,8 @@ private LanceTableMetadata metadataAtOrBefore(ConnectorSession session, LanceTab + "', expected " + LanceSnapshotResolver.TIMESTAMP_FORMATS); } LanceTableMetadata metadata = client.loadTableMetadataAtOrBefore(handle.getDbName(), - handle.getTableName(), timestamp.getAsLong(), requestedText); + handle.getTableName(), timestamp.getAsLong(), requestedText, + LanceMetadataMetrics.forTable(session, handle.getDbName(), handle.getTableName())); // Remembered under the version it resolved to, which is what the pinned reads that follow ask for. return LanceStatementScope.sharedMetadata(session, handle.withVersion(metadata.getVersion()), () -> metadata); diff --git a/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceIndexMetadata.java b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceIndexMetadata.java index 87e236babf5d11..8ed673256a14b7 100644 --- a/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceIndexMetadata.java +++ b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceIndexMetadata.java @@ -17,6 +17,8 @@ package org.apache.doris.connector.lance; +import org.apache.doris.connector.lance.LanceMetadataMetrics.Stage; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.lance.Dataset; @@ -32,6 +34,7 @@ import java.util.List; import java.util.Map; import java.util.OptionalInt; +import java.util.function.Supplier; /** * The top-level field ids and the user indexes of one fixed dataset version. @@ -63,11 +66,23 @@ static LanceIndexMetadata withUnavailableFieldIds(List in return new LanceIndexMetadata(false, Collections.emptyMap(), indexSegments); } - /** Reads the field ids and the index segments of the caller's open snapshot. */ - static LanceIndexMetadata read(Dataset dataset) { - Map lanceFieldIds = loadTopLevelFieldIds(dataset); + /** Reads the field ids and the index segments of the caller's open snapshot, timing each into {@code timer}. */ + static LanceIndexMetadata read(Dataset dataset, LanceMetadataMetrics.Timer timer) { + return read(dataset::getLanceSchema, () -> LanceDatasetIndexDiscovery.describeUserIndexes(dataset), + dataset.version(), timer); + } + + /** + * {@link #read(Dataset, LanceMetadataMetrics.Timer)} over the two SDK reads it makes: the Lance schema, and the + * validated user indexes. + */ + static LanceIndexMetadata read(Supplier lanceSchema, Supplier> userIndexes, + long version, LanceMetadataMetrics.Timer timer) { + Map lanceFieldIds = timer.measure(Stage.FIELD_IDS, + () -> loadTopLevelFieldIds(lanceSchema, version)); // Keep index validation even when the known schema conversion error disables field-ID mapping. - List indexSegments = loadIndexSegments(dataset); + List indexSegments = timer.measure(Stage.INDEXES, + () -> loadIndexSegments(userIndexes.get())); return lanceFieldIds == null ? withUnavailableFieldIds(indexSegments) : new LanceIndexMetadata(lanceFieldIds, indexSegments); @@ -87,10 +102,10 @@ OptionalInt getLanceFieldId(String fieldName) { return fieldId == null ? OptionalInt.empty() : OptionalInt.of(fieldId); } - private static Map loadTopLevelFieldIds(Dataset dataset) { + private static Map loadTopLevelFieldIds(Supplier lanceSchema, long version) { LanceSchema schema; try { - schema = dataset.getLanceSchema(); + schema = lanceSchema.get(); } catch (IllegalArgumentException e) { if (!"ArrowSchema conversion error".equals(e.getMessage())) { throw e; @@ -101,7 +116,7 @@ private static Map loadTopLevelFieldIds(Dataset dataset) { // the SDK call: invalid ids and duplicate names below must remain errors. LOG.warn("Lance SDK schema conversion failed at dataset version {}; " + "disabling FE scalar index segment planning for this snapshot: {}", - dataset.version(), e.getMessage()); + version, e.getMessage()); return null; } Map result = new LinkedHashMap<>(); @@ -118,9 +133,9 @@ private static Map loadTopLevelFieldIds(Dataset dataset) { return result; } - private static List loadIndexSegments(Dataset dataset) { + private static List loadIndexSegments(List userIndexes) { List result = new ArrayList<>(); - for (IndexDescription description : LanceDatasetIndexDiscovery.describeUserIndexes(dataset)) { + for (IndexDescription description : userIndexes) { for (Index segment : description.getSegments()) { if (segment.indexType() == null) { continue; diff --git a/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceMetadataMetrics.java b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceMetadataMetrics.java new file mode 100644 index 00000000000000..73273e09f6e1e7 --- /dev/null +++ b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceMetadataMetrics.java @@ -0,0 +1,266 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.doris.connector.lance; + +import org.apache.doris.connector.spi.ConnectorSession; +import org.apache.doris.connector.spi.ConnectorStatementScopes; +import org.apache.doris.connector.spi.scan.ConnectorScanProfile; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; + +/** + * The FE time one statement spends on one Lance table's metadata, published with each scan of the table as the + * {@value #GROUP_NAME} group of the query profile. + * + *

Two operations are timed: a metadata read (describe the table, open the dataset at a version, read what the + * statement asks of it) and the split planning of a scan. A read's time is also broken into disjoint stages, so + * that a slow namespace, a slow store and a large manifest can be told apart. Failed attempts count in the time + * and in the calls. No query identifier, dataset URI, credential or Session-wide cache statistic is recorded. + * + *

The totals are kept per table in the statement scope, because the reads happen in the statement's metadata + * calls and the planning in its scans: {@link #publishScan} hands the table's totals so far to the scan being + * planned and starts them over, and the engine collects that scan's profile right after planning it + * ({@link #collectScanProfiles}). Outside a live statement every lookup returns fresh totals that nothing + * publishes, so a read there is timed for nothing and otherwise behaves the same. + */ +final class LanceMetadataMetrics { + /** The query-profile group; user-visible. */ + static final String GROUP_NAME = "Lance Metadata Metrics"; + /** Statement-scope namespace of the per-table totals; guarded by {@code LanceStatementScopeTest}. */ + static final String TABLE_METRICS_NAMESPACE = "lance.metadata_metrics"; + /** + * Statement-scope key prefix of the profiles planned scans leave for the engine to collect, followed by the + * catalog and query ids, as other connectors key their per-statement profiles; guarded by + * {@code LanceStatementScopeTest}. + */ + static final String SCAN_PROFILES_KEY_PREFIX = "lance.scan_profiles"; + + /** Disjoint parts of a metadata read. */ + enum Stage { + /** Describing the table: namespace request, credential vending and storage options. */ + TABLE_ACCESS("TableAccessResolve"), + /** Every Dataset.open, the newest-version open that FOR TIME AS OF needs included. */ + DATASET_OPEN("DatasetOpen"), + /** Listing the versions and choosing the one at or before a time. */ + VERSION_RESOLVE("VersionResolve"), + /** Reading the Arrow schema. */ + SCHEMA("SchemaRead"), + /** Reading the fragments and their row counts. */ + FRAGMENTS("FragmentMetadataRead"), + /** Reading the Lance field ids, the known schema-conversion fallback included. */ + FIELD_IDS("FieldIdsRead"), + /** Discovering the user indexes and their segments. */ + INDEXES("IndexMetadataRead"); + + private final String prefix; + + Stage(String prefix) { + this.prefix = prefix; + } + } + + enum Operation { + METADATA_READ("MetadataRead"), + SPLIT_PLANNING("SplitPlanning"); + + private final String prefix; + + Operation(String prefix) { + this.prefix = prefix; + } + } + + private final long[] operationNanos = new long[Operation.values().length]; + private final long[] operationCalls = new long[Operation.values().length]; + private final long[] operationFailures = new long[Operation.values().length]; + private final long[] stageNanos = new long[Stage.values().length]; + private final long[] stageCalls = new long[Stage.values().length]; + + /** + * The totals of {@code dbName.tableName} in the session's statement. A statement-scope lookup itself, so never + * call it from a loader of that scope: the engine's scope throws "Recursive update" on such a re-entry. + */ + static LanceMetadataMetrics forTable(ConnectorSession session, String dbName, String tableName) { + return ConnectorStatementScopes.resolveInStatement(session, TABLE_METRICS_NAMESPACE, dbName, tableName, + LanceMetadataMetrics::new); + } + + /** + * Queues the table's totals so far as the profile of the scan of {@code dbName.tableName} just planned, for + * {@link #collectScanProfiles}, and starts the totals over: a later scan of the same table in the statement + * reports only what came after. + */ + static void publishScan(ConnectorSession session, String dbName, String tableName, + LanceMetadataMetrics metrics) { + pendingProfiles(session).add(new ConnectorScanProfile(GROUP_NAME, + "Table Scan (" + dbName + "." + tableName + ")", metrics.drain())); + } + + /** The profiles queued in the session's statement since the last collection. */ + static List collectScanProfiles(ConnectorSession session) { + Queue pending = pendingProfiles(session); + List profiles = new ArrayList<>(); + for (ConnectorScanProfile profile = pending.poll(); profile != null; profile = pending.poll()) { + profiles.add(profile); + } + return profiles; + } + + private static Queue pendingProfiles(ConnectorSession session) { + String key = SCAN_PROFILES_KEY_PREFIX + ":" + session.getCatalogId() + ":" + session.getQueryId(); + return session.getStatementScope().computeIfAbsent(key, ConcurrentLinkedQueue::new); + } + + /** Starts timing one operation; the returned scope adds itself to these totals when closed. */ + Timer start(Operation operation) { + return new Timer(operation); + } + + /** + * The totals as profile values, then cleared: each operation that ran with its time, calls and failures, then + * each stage that ran with its time and calls. Times are summed in nanoseconds before rendering, so many short + * reads are not rounded away one by one. + */ + synchronized Map drain() { + Map values = new LinkedHashMap<>(); + for (Operation operation : Operation.values()) { + int index = operation.ordinal(); + if (operationCalls[index] > 0) { + values.put(operation.prefix + "Time", prettyNanos(operationNanos[index])); + values.put(operation.prefix + "Calls", String.valueOf(operationCalls[index])); + values.put(operation.prefix + "Failures", String.valueOf(operationFailures[index])); + } + } + for (Stage stage : Stage.values()) { + int index = stage.ordinal(); + if (stageCalls[index] > 0) { + values.put(stage.prefix + "Time", prettyNanos(stageNanos[index])); + values.put(stage.prefix + "Calls", String.valueOf(stageCalls[index])); + } + } + clear(operationNanos, operationCalls, operationFailures, stageNanos, stageCalls); + return values; + } + + private synchronized void add(Timer timer, long elapsedNanos) { + int index = timer.operation.ordinal(); + operationNanos[index] += elapsedNanos; + operationCalls[index]++; + if (!timer.successful) { + operationFailures[index]++; + } + for (int stage = 0; stage < stageCalls.length; stage++) { + stageNanos[stage] += timer.stageNanos[stage]; + stageCalls[stage] += timer.stageCalls[stage]; + } + } + + private static void clear(long[]... counters) { + for (long[] counter : counters) { + Arrays.fill(counter, 0); + } + } + + /** + * A duration as the query profile renders its nanosecond timers: from one second up as fe-core's + * {@code DebugUtil.printTimeMs} does (hours and minutes drop the smaller units), else milliseconds or + * microseconds with three decimals, else nanoseconds. + */ + static String prettyNanos(long nanos) { + if (nanos >= TimeUnit.SECONDS.toNanos(1)) { + long remaining = TimeUnit.NANOSECONDS.toMillis(nanos); + StringBuilder builder = new StringBuilder(); + boolean hour = false; + boolean minute = false; + if (remaining >= TimeUnit.HOURS.toMillis(1)) { + builder.append(remaining / TimeUnit.HOURS.toMillis(1)).append("hour"); + remaining %= TimeUnit.HOURS.toMillis(1); + hour = true; + } + if (remaining >= TimeUnit.MINUTES.toMillis(1)) { + builder.append(remaining / TimeUnit.MINUTES.toMillis(1)).append("min"); + remaining %= TimeUnit.MINUTES.toMillis(1); + minute = true; + } + if (!hour && remaining >= TimeUnit.SECONDS.toMillis(1)) { + builder.append(remaining / TimeUnit.SECONDS.toMillis(1)).append("sec"); + remaining %= TimeUnit.SECONDS.toMillis(1); + } + if (!hour && !minute) { + builder.append(remaining).append("ms"); + } + return builder.toString(); + } + if (nanos >= TimeUnit.MILLISECONDS.toNanos(1)) { + long micros = TimeUnit.NANOSECONDS.toMicros(nanos); + return String.format(Locale.ROOT, "%d.%03dms", micros / 1000, micros % 1000); + } + if (nanos >= TimeUnit.MICROSECONDS.toNanos(1)) { + return String.format(Locale.ROOT, "%d.%03dus", nanos / 1000, nanos % 1000); + } + return nanos + "ns"; + } + + /** The timing of one operation; the stages measured in it count toward it, and it counts on close. */ + final class Timer implements AutoCloseable { + private final Operation operation; + private final long startedNanos = System.nanoTime(); + private final long[] stageNanos = new long[Stage.values().length]; + private final long[] stageCalls = new long[Stage.values().length]; + private boolean successful; + private boolean closed; + + private Timer(Operation operation) { + this.operation = operation; + } + + /** Runs {@code action} as one call of {@code stage}; a failed call counts too, and its error propagates. */ + T measure(Stage stage, Supplier action) { + long start = System.nanoTime(); + try { + return action.get(); + } finally { + stageNanos[stage.ordinal()] += System.nanoTime() - start; + stageCalls[stage.ordinal()]++; + } + } + + /** Marks the operation successful: call it once everything it opened has been released. */ + void succeeded() { + successful = true; + } + + @Override + public void close() { + if (closed) { + return; + } + closed = true; + add(this, System.nanoTime() - startedNanos); + } + } +} diff --git a/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceNamespaceClient.java b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceNamespaceClient.java index 223a453180fda4..b3eb1a536e12a0 100644 --- a/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceNamespaceClient.java +++ b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceNamespaceClient.java @@ -20,6 +20,10 @@ import org.apache.doris.connector.spi.DorisConnectorException; import org.apache.doris.filesystem.properties.StorageProperties; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.github.benmanes.caffeine.cache.Expiry; +import com.github.benmanes.caffeine.cache.Ticker; import org.apache.commons.lang3.StringUtils; import org.lance.namespace.LanceNamespace; import org.lance.namespace.errors.NamespaceNotFoundException; @@ -32,23 +36,35 @@ import org.lance.namespace.model.ListTablesResponse; import org.lance.namespace.model.TableExistsRequest; +import java.net.URI; +import java.net.URISyntaxException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Queue; import java.util.Set; +import java.util.concurrent.TimeUnit; /** * Namespace requests and table access resolution. The catalog client owns the native resources and holds * a lease throughout each call to this client. + * + *

Every metadata read starts from the table's access: the dataset URI and the storage options the namespace + * describes. Those rarely change, while describing costs a REST request or a directory listing per read, so a + * described access is reused for {@code lance.table_access_cache_ttl_seconds}, counted from the describe: a hit + * never extends it. A table whose options carry vended credentials, or whose URI may carry credentials, is + * described on every read: the BE cannot renew credentials during a scan of any length, and no fixed margin + * covers every query. */ final class LanceNamespaceClient { /** Joins the components of a nested namespace into one Doris database name. */ private static final String DATABASE_NAMESPACE_DELIMITER = "."; private static final int PAGE_SIZE = 1000; + private static final int TABLE_ACCESS_CACHE_MAX_ENTRIES = 10_000; private final LanceNamespace namespace; /** Whether to ask the namespace for each table's storage credentials, as a REST namespace can vend them. */ @@ -63,14 +79,26 @@ final class LanceNamespaceClient { * catalog. */ private final Object namespaceLock = new Object(); + private final long tableAccessTtlNanos; + private final Ticker ticker; + /** Replaced, never cleared, on invalidation; see {@link #invalidateTableAccessCache()}. */ + private volatile Cache, CachedTableAccess> tableAccessCache; + /** + * @param tableAccessTtlSeconds how long a described access is reused; 0 describes the table on every read + * @param ticker the clock the TTL is measured with + */ LanceNamespaceClient(LanceNamespace namespace, boolean vendCredentials, String rootDatabase, - List parentNamespace, List storageProperties) { + List parentNamespace, List storageProperties, long tableAccessTtlSeconds, + Ticker ticker) { this.namespace = namespace; this.vendCredentials = vendCredentials; this.rootDatabase = rootDatabase; this.parentNamespace = Collections.unmodifiableList(new ArrayList<>(parentNamespace)); this.storageProperties = Collections.unmodifiableList(new ArrayList<>(storageProperties)); + this.tableAccessTtlNanos = TimeUnit.SECONDS.toNanos(tableAccessTtlSeconds); + this.ticker = ticker; + this.tableAccessCache = newTableAccessCache(); } List listDatabaseNames() { @@ -179,9 +207,31 @@ boolean tableExists(String dbName, String tblName) { } } - /** Describes the table and builds the URI and options both the FE and the BE open it with. */ + /** + * The URI and options both the FE and the BE open the table with: a cached access while its TTL lasts, + * otherwise a new describe. Concurrent misses of one table share one describe; a failed describe is not + * cached. + */ LanceTableAccess resolveTableAccess(String dbName, String tableName) { - List tableId = buildTableId(dbName, tableName); + List tableId = Collections.unmodifiableList(buildTableId(dbName, tableName)); + if (tableAccessTtlNanos == 0) { + return describeTableAccess(tableId, dbName, tableName).access; + } + // A hit takes neither the namespace lock nor any filesystem or REST I/O. + return tableAccessCache.get(tableId, id -> describeTableAccess(id, dbName, tableName)).access; + } + + /** + * Drops every cached access, catalog-wide, for REFRESH TABLE as for REFRESH DATABASE: describing a table again + * is cheap. The cache is swapped rather than cleared, so that this waits for nothing, and a describe already in + * flight, which still answers its own caller, cannot repopulate the cache that reads admitted after the refresh + * use. + */ + void invalidateTableAccessCache() { + tableAccessCache = newTableAccessCache(); + } + + private CachedTableAccess describeTableAccess(List tableId, String dbName, String tableName) { DescribeTableResponse table = namespace.describeTable( new DescribeTableRequest().id(tableId).withTableUri(true).vendCredentials(vendCredentials)); if (Boolean.TRUE.equals(table.getIsOnlyDeclared())) { @@ -189,7 +239,7 @@ LanceTableAccess resolveTableAccess(String dbName, String tableName) { } // The namespace, not the dataset's _versions/ directory, decides which versions of such a table exist. // Opening it by URI reads the newest manifest in storage, which the namespace may not have published, - // and is all this connector can do yet. + // and is all this connector can do yet. Refused on every read: a refusal is never cached. if (Boolean.TRUE.equals(table.getManagedVersioning())) { throw new DorisConnectorException("Lance table " + dbName + "." + tableName + " has its versions" + " managed by the namespace (managed_versioning), which is not supported yet"); @@ -201,8 +251,65 @@ LanceTableAccess resolveTableAccess(String dbName, String tableName) { // One option map serves both readers: the FE opens the dataset through the Lance Java SDK and the // BE through lance-c, so neither can end up with credentials the other lacks. The dataset URL picks // the option vocabulary, the same way Lance picks a provider from it. - return new LanceTableAccess(datasetUri, LanceStorageOptions.fromDorisAndVendedStorageOptions( + LanceTableAccess access = new LanceTableAccess(datasetUri, LanceStorageOptions.fromDorisAndVendedStorageOptions( datasetUri, storageProperties, table.getStorageOptions())); + return new CachedTableAccess(access, cacheTtlNanos(datasetUri, table.getStorageOptions())); + } + + /** How long a described access may be reused: 0 when it may carry credentials. */ + private long cacheTtlNanos(String datasetUri, Map vendedOptions) { + // The BE cannot renew credentials during a scan. A fixed expiry margin cannot cover arbitrary query + // durations, so vended options are described again for every read, even with a reported deadline. + if (vendedOptions != null && !vendedOptions.isEmpty()) { + return 0; + } + try { + URI uri = new URI(datasetUri.trim()); + // Presigned or SAS credentials may live in the URI even when the storage options are empty. A + // registry-based authority holds user info that URI.getRawUserInfo() does not report. + if (uri.isOpaque() || uri.getRawUserInfo() != null || uri.getRawQuery() != null + || uri.getRawFragment() != null + || (uri.getRawAuthority() != null && uri.getRawAuthority().contains("@"))) { + return 0; + } + return tableAccessTtlNanos; + } catch (URISyntaxException e) { + // A locator that cannot be classified stays usable, but is not assumed credential-free. + return 0; + } + } + + private Cache, CachedTableAccess> newTableAccessCache() { + return Caffeine.newBuilder().maximumSize(TABLE_ACCESS_CACHE_MAX_ENTRIES).ticker(ticker) + .expireAfter(new Expiry, CachedTableAccess>() { + @Override + public long expireAfterCreate(List key, CachedTableAccess value, long currentTime) { + return value.ttlNanos; + } + + @Override + public long expireAfterUpdate(List key, CachedTableAccess value, long currentTime, + long currentDuration) { + return value.ttlNanos; + } + + @Override + public long expireAfterRead(List key, CachedTableAccess value, long currentTime, + long currentDuration) { + return currentDuration; + } + }).build(); + } + + /** A described access and how long it may be reused; a TTL of 0 expires it at once. */ + private static final class CachedTableAccess { + private final LanceTableAccess access; + private final long ttlNanos; + + private CachedTableAccess(LanceTableAccess access, long ttlNanos) { + this.access = access; + this.ttlNanos = ttlNanos; + } } private List buildNamespaceId(String dbName) { diff --git a/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceScanPlanProvider.java b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceScanPlanProvider.java index 261a6d659b37a1..e8d1f0c2607c78 100644 --- a/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceScanPlanProvider.java +++ b/fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceScanPlanProvider.java @@ -17,6 +17,7 @@ package org.apache.doris.connector.lance; +import org.apache.doris.connector.lance.LanceMetadataMetrics.Operation; import org.apache.doris.connector.spi.ConnectorSession; import org.apache.doris.connector.spi.DorisConnectorException; import org.apache.doris.connector.spi.handle.ConnectorColumnHandle; @@ -24,6 +25,7 @@ import org.apache.doris.connector.spi.handle.NamedColumnHandle; import org.apache.doris.connector.spi.pushdown.ConnectorExpression; import org.apache.doris.connector.spi.scan.ConnectorScanPlanProvider; +import org.apache.doris.connector.spi.scan.ConnectorScanProfile; import org.apache.doris.connector.spi.scan.ConnectorScanRange; import org.apache.doris.connector.spi.scan.ConnectorScanRequest; import org.apache.doris.connector.spi.scan.ScanNodePropertiesResult; @@ -99,10 +101,34 @@ final class LanceScanPlanProvider implements ConnectorScanPlanProvider { this.backendStorageProperties = backendStorageProperties; } + /** + * Plans the ranges, timed as the scan's split planning. The scan's metadata metrics are queued for + * {@link #collectScanProfiles} even when planning fails: the engine collects a failed scan's profile too. + */ @Override public List planScan(ConnectorSession session, ConnectorScanRequest request) { LanceTableHandle handle = lanceHandle(request.getTableHandle()); - LanceTableMetadata metadata = metadata(session, handle); + LanceMetadataMetrics metrics = tableMetrics(session, handle); + try { + LanceTableMetadata metadata = metadata(session, handle); + try (LanceMetadataMetrics.Timer timer = metrics.start(Operation.SPLIT_PLANNING)) { + List ranges = planRanges(session, request, handle, metadata); + timer.succeeded(); + return ranges; + } + } finally { + LanceMetadataMetrics.publishScan(session, handle.getDbName(), handle.getTableName(), metrics); + } + } + + /** The {@value LanceMetadataMetrics#GROUP_NAME} of the scan {@link #planScan} just planned. */ + @Override + public List collectScanProfiles(ConnectorSession session) { + return LanceMetadataMetrics.collectScanProfiles(session); + } + + private List planRanges(ConnectorSession session, ConnectorScanRequest request, + LanceTableHandle handle, LanceTableMetadata metadata) { List conjuncts = LancePredicateConverter.conjuncts(request.getFilter()); // Any filter, pushed or not, makes the version's row count larger than the result. if (request.isCountPushdown() && conjuncts.isEmpty()) { @@ -195,10 +221,11 @@ public void appendExplainInfo(StringBuilder output, String prefix, Map LanceStatementScope.sharedIndexMetadata(session, handle, metadata, () -> client.loadIndexMetadata(handle.getDbName(), handle.getTableName(), - metadata.getVersion()))); + metadata.getVersion(), metrics))); } private static int fragmentsPerSplit(ConnectorSession session) { @@ -227,8 +254,19 @@ private static boolean projectsCurrentReaderType(LanceTableMetadata metadata, } private LanceTableMetadata metadata(ConnectorSession session, LanceTableHandle handle) { + LanceMetadataMetrics metrics = tableMetrics(session, handle); return LanceStatementScope.sharedMetadata(session, handle, - () -> client.loadTableMetadata(handle.getDbName(), handle.getTableName(), handle.getVersion())); + () -> client.loadTableMetadata(handle.getDbName(), handle.getTableName(), handle.getVersion(), + metrics)); + } + + /** + * The statement's metrics of the table. Look them up before a statement-scope loader runs, never inside one: + * a loader may not use the scope, whose ConcurrentHashMap throws "Recursive update" when the two keys share a + * bin. + */ + private static LanceMetadataMetrics tableMetrics(ConnectorSession session, LanceTableHandle handle) { + return LanceMetadataMetrics.forTable(session, handle.getDbName(), handle.getTableName()); } private static LanceTableHandle lanceHandle(ConnectorTableHandle handle) { diff --git a/fe/fe-connector/fe-connector-lance/src/main/resources/lance.conf.template b/fe/fe-connector/fe-connector-lance/src/main/resources/lance.conf.template index 644760032a0113..eeddb42ec31f61 100644 --- a/fe/fe-connector/fe-connector-lance/src/main/resources/lance.conf.template +++ b/fe/fe-connector/fe-connector-lance/src/main/resources/lance.conf.template @@ -10,7 +10,11 @@ # and a value set there no longer takes effect -- move it here. # Java Arrow memory, in bytes, that one Lance catalog may use while it reads dataset metadata -# (namespace listings, schemas, fragment lists). Must be positive. BE reads the data itself, so this -# does not bound query execution. +# (namespace listings, schemas, fragment lists). Must be positive. REFRESH CATALOG gives the catalog new +# resources while the reads already running finish on the old ones, which keep their own limit in use +# until the last of those reads ends; repeated refreshes during slow reads can keep several in use. +# Each set of resources also holds a Lance Session, whose caches (up to 64 MiB of metadata and 128 MiB of +# index metadata, outside the Java heap) are not counted. BE reads the data itself, so this does not bound +# query execution. # Default: 268435456 (256 MiB) # lance_catalog_arrow_memory_limit_bytes=268435456 diff --git a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/FakeLanceNamespace.java b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/FakeLanceNamespace.java new file mode 100644 index 00000000000000..20fa57be5b9f7f --- /dev/null +++ b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/FakeLanceNamespace.java @@ -0,0 +1,94 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.doris.connector.lance; + +import org.apache.arrow.memory.BufferAllocator; +import org.lance.namespace.LanceNamespace; +import org.lance.namespace.model.DescribeTableRequest; +import org.lance.namespace.model.DescribeTableResponse; +import org.lance.namespace.model.ListNamespacesRequest; +import org.lance.namespace.model.ListNamespacesResponse; +import org.lance.namespace.model.TableExistsRequest; +import org.lance.namespace.model.TableExistsResponse; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +import java.util.function.Function; + +/** + * A namespace that records the requests it is sent and answers them as the test scripts: every describe by + * default as a plain filesystem table, every table as existing, every listing as empty. A script may block, to + * hold a call in flight. Closing it is recorded, and can be made to fail. + */ +final class FakeLanceNamespace implements LanceNamespace, AutoCloseable { + final List describes = new CopyOnWriteArrayList<>(); + final List existenceChecks = new CopyOnWriteArrayList<>(); + final List namespaceListings = new CopyOnWriteArrayList<>(); + final AtomicInteger closes = new AtomicInteger(); + volatile Function describe = + request -> new DescribeTableResponse().tableUri("file:///warehouse/items.lance"); + volatile Consumer tableExists = request -> { }; + volatile Function listNamespaces = + request -> new ListNamespacesResponse(); + volatile RuntimeException closeFailure; + + /** Answers every describe with {@code response}. */ + FakeLanceNamespace describing(DescribeTableResponse response) { + describe = request -> response; + return this; + } + + @Override + public void initialize(Map properties, BufferAllocator allocator) { + } + + @Override + public String namespaceId() { + return "fake"; + } + + @Override + public DescribeTableResponse describeTable(DescribeTableRequest request) { + describes.add(request); + return describe.apply(request); + } + + @Override + public TableExistsResponse tableExists(TableExistsRequest request) { + existenceChecks.add(request); + tableExists.accept(request); + return new TableExistsResponse(); + } + + @Override + public ListNamespacesResponse listNamespaces(ListNamespacesRequest request) { + namespaceListings.add(request); + return listNamespaces.apply(request); + } + + @Override + public void close() { + closes.incrementAndGet(); + if (closeFailure != null) { + throw closeFailure; + } + } +} diff --git a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/FakeResourceFactory.java b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/FakeResourceFactory.java new file mode 100644 index 00000000000000..d64fa4179b98e4 --- /dev/null +++ b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/FakeResourceFactory.java @@ -0,0 +1,94 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.doris.connector.lance; + +import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.memory.RootAllocator; +import org.lance.Session; +import org.lance.namespace.LanceNamespace; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.function.Supplier; + +/** + * The resources of each generation: a recording allocator and a {@link FakeLanceNamespace}, and the Session a + * test supplies. Tests whose calls never open a dataset supply none, since only an opened dataset uses it; native + * tests supply real ones and keep them to inspect. + */ +final class FakeResourceFactory implements LanceCatalogClient.ResourceFactory { + final List allocators = new CopyOnWriteArrayList<>(); + final List namespaces = new CopyOnWriteArrayList<>(); + final List sessions = new CopyOnWriteArrayList<>(); + /** The namespace the next generation connects to. */ + volatile Supplier nextNamespace = FakeLanceNamespace::new; + /** The Session of the next generation; none by default. */ + volatile Supplier nextSession = () -> null; + /** Counted down after every child allocator a read takes. */ + volatile CountDownLatch childAllocators = new CountDownLatch(0); + + @Override + public BufferAllocator newAllocator(long limit) { + RecordingAllocator allocator = new RecordingAllocator(limit, this); + allocators.add(allocator); + return allocator; + } + + @Override + public LanceNamespace connect(String implementation, Map properties, + BufferAllocator allocator) { + FakeLanceNamespace namespace = nextNamespace.get(); + namespaces.add(namespace); + return namespace; + } + + @Override + public Session newSession() { + Session session = nextSession.get(); + if (session != null) { + sessions.add(session); + } + return session; + } + + /** Records that it was closed, and each child it hands out. */ + static final class RecordingAllocator extends RootAllocator { + private final FakeResourceFactory factory; + volatile boolean closed; + + private RecordingAllocator(long limit, FakeResourceFactory factory) { + super(limit); + this.factory = factory; + } + + @Override + public BufferAllocator newChildAllocator(String name, long initReservation, long maxAllocation) { + BufferAllocator child = super.newChildAllocator(name, initReservation, maxAllocation); + factory.childAllocators.countDown(); + return child; + } + + @Override + public void close() { + closed = true; + super.close(); + } + } +} diff --git a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceCatalogClientTest.java b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceCatalogClientTest.java new file mode 100644 index 00000000000000..892c1fa10352dc --- /dev/null +++ b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceCatalogClientTest.java @@ -0,0 +1,290 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.doris.connector.lance; + +import org.apache.doris.connector.lance.FakeResourceFactory.RecordingAllocator; +import org.apache.doris.connector.spi.DorisConnectorException; + +import org.apache.arrow.memory.ArrowBuf; +import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.memory.OutOfMemoryException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.lance.namespace.model.ListNamespacesResponse; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.OptionalLong; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +/** + * The generations of {@link LanceCatalogClient}: a call keeps the generation it started on, a refresh or a close + * waits for no call, and the last call on a retired generation releases its resources. + */ +class LanceCatalogClientTest { + + private final FakeResourceFactory resources = new FakeResourceFactory(); + + @Test + void closeLetsTheCallInFlightFinishThenReleasesAndRefusesNewCalls() throws Exception { + LanceCatalogClient client = client(1024 * 1024); + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + resources.nextNamespace = () -> blockingExistenceChecks(entered, release); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future inFlight = executor.submit(() -> client.tableExists("default", "t")); + Assertions.assertTrue(entered.await(10, TimeUnit.SECONDS)); + client.close(); + client.close(); + Assertions.assertEquals(0, resources.namespaces.get(0).closes.get()); + Assertions.assertFalse(resources.allocators.get(0).closed); + Assertions.assertEquals("Lance catalog resources have been closed", Assertions.assertThrows( + DorisConnectorException.class, () -> client.tableExists("default", "t")).getMessage()); + + release.countDown(); + Assertions.assertTrue(inFlight.get(10, TimeUnit.SECONDS)); + Assertions.assertEquals(1, resources.namespaces.get(0).closes.get()); + Assertions.assertTrue(resources.allocators.get(0).closed); + } finally { + release.countDown(); + shutdown(executor); + } + } + + @Test + void failingToCloseTheNamespaceStillReleasesTheAllocator() { + LanceCatalogClient client = client(1024 * 1024); + resources.nextNamespace = () -> { + FakeLanceNamespace namespace = new FakeLanceNamespace(); + namespace.closeFailure = new IllegalStateException("close failed"); + return namespace; + }; + Assertions.assertTrue(client.tableExists("default", "t")); + client.close(); + client.close(); + Assertions.assertEquals(1, resources.namespaces.get(0).closes.get()); + Assertions.assertTrue(resources.allocators.get(0).closed); + } + + /** A generation that cannot be opened releases what it had opened, and the next call tries again. */ + @Test + void failingToOpenAGenerationReleasesWhatItOpenedAndTheNextCallRetries() { + LanceCatalogClient client = client(1024 * 1024); + resources.nextSession = () -> { + throw new IllegalStateException("no session"); + }; + DorisConnectorException failure = Assertions.assertThrows(DorisConnectorException.class, + () -> client.tableExists("default", "t")); + Assertions.assertTrue(failure.getMessage().startsWith("Failed to initialize Lance filesystem catalog"), + failure.getMessage()); + Assertions.assertEquals(1, resources.namespaces.get(0).closes.get()); + Assertions.assertTrue(resources.allocators.get(0).closed); + + resources.nextSession = () -> null; + Assertions.assertTrue(client.tableExists("default", "t")); + Assertions.assertEquals(2, resources.namespaces.size()); + client.close(); + Assertions.assertEquals(1, resources.namespaces.get(1).closes.get()); + } + + @Test + void refreshLetsTheCallInFlightFinishOnItsGenerationAndMovesNewCallsToANewOne() throws Exception { + LanceCatalogClient client = client(1024 * 1024); + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + resources.nextNamespace = () -> blockingExistenceChecks(entered, release); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future inFlight = executor.submit(() -> client.tableExists("default", "t")); + Assertions.assertTrue(entered.await(10, TimeUnit.SECONDS)); + resources.nextNamespace = FakeLanceNamespace::new; + // Returns without waiting for the call in flight, and closes nothing under it. + client.refresh(); + Assertions.assertEquals(0, resources.namespaces.get(0).closes.get()); + + Assertions.assertTrue(client.tableExists("default", "t")); + Assertions.assertEquals(2, resources.namespaces.size()); + Assertions.assertEquals(1, resources.namespaces.get(1).existenceChecks.size()); + Assertions.assertEquals(0, resources.namespaces.get(0).closes.get()); + + release.countDown(); + Assertions.assertTrue(inFlight.get(10, TimeUnit.SECONDS)); + Assertions.assertEquals(1, resources.namespaces.get(0).closes.get()); + Assertions.assertTrue(resources.allocators.get(0).closed); + Assertions.assertEquals(0, resources.namespaces.get(1).closes.get()); + Assertions.assertFalse(resources.allocators.get(1).closed); + } finally { + release.countDown(); + shutdown(executor); + } + client.close(); + Assertions.assertEquals(1, resources.namespaces.get(1).closes.get()); + Assertions.assertTrue(resources.allocators.get(1).closed); + } + + @Test + void idleGenerationIsReleasedByTheRefreshItself() { + LanceCatalogClient client = client(1024 * 1024); + Assertions.assertTrue(client.tableExists("default", "t")); + client.refresh(); + Assertions.assertEquals(1, resources.namespaces.get(0).closes.get()); + Assertions.assertTrue(resources.allocators.get(0).closed); + client.close(); + Assertions.assertEquals(1, resources.namespaces.size()); + } + + /** An FE replays REFRESH and DDL edits for catalogs nobody has used: invalidating opens nothing. */ + @Test + void invalidationOpensNothingAndCannotReviveAClosedClient() { + LanceCatalogClient client = new LanceCatalogClient(filesystem(), () -> { + throw new AssertionError("an invalidation must not bind storage"); + }, () -> { + throw new AssertionError("an invalidation must not read lance.conf"); + }, resources, () -> 0L); + client.refresh(); + client.invalidateTableAccess(); + client.close(); + client.refresh(); + client.invalidateTableAccess(); + Assertions.assertTrue(resources.namespaces.isEmpty()); + Assertions.assertTrue(resources.allocators.isEmpty()); + Assertions.assertEquals("Lance catalog resources have been closed", Assertions.assertThrows( + DorisConnectorException.class, () -> client.listDatabaseNames()).getMessage()); + } + + /** REFRESH TABLE / DATABASE keep the generation, and with it the Session's cached metadata. */ + @Test + void tableAccessInvalidationKeepsTheGeneration() { + LanceCatalogClient client = client(1024 * 1024); + Assertions.assertTrue(client.tableExists("default", "t")); + client.invalidateTableAccess(); + Assertions.assertTrue(client.tableExists("default", "t")); + Assertions.assertEquals(1, resources.namespaces.size()); + Assertions.assertEquals(2, resources.namespaces.get(0).existenceChecks.size()); + Assertions.assertEquals(0, resources.namespaces.get(0).closes.get()); + client.close(); + } + + @Test + void repeatedPageTokenFailsInsteadOfReturningAPartialListing() { + LanceCatalogClient client = client(1024 * 1024); + resources.nextNamespace = () -> { + FakeLanceNamespace namespace = new FakeLanceNamespace(); + namespace.listNamespaces = request -> new ListNamespacesResponse() + .namespaces(Collections.emptySet()).pageToken("repeated"); + return namespace; + }; + DorisConnectorException failure = Assertions.assertThrows(DorisConnectorException.class, + client::listDatabaseNames); + Assertions.assertTrue(failure.getMessage().contains("Lance namespace repeated a pagination token"), + failure.getMessage()); + Assertions.assertEquals(2, resources.namespaces.get(0).namespaceListings.size()); + client.close(); + } + + /** + * Each read takes a child of its generation's allocator, so concurrent reads share the catalog's Arrow limit, + * and a read gives its child back whether it succeeds or fails. + */ + @Test + void concurrentReadsShareTheArrowLimitAndReleaseTheirAllocators() throws Exception { + LanceCatalogClient client = client(1024); + CountDownLatch release = new CountDownLatch(1); + resources.childAllocators = new CountDownLatch(2); + resources.nextNamespace = () -> { + FakeLanceNamespace namespace = new FakeLanceNamespace(); + namespace.describe = request -> { + await(release); + throw new IllegalStateException("stop before the dataset is opened"); + }; + return namespace; + }; + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Callable read = () -> Assertions.assertThrows(DorisConnectorException.class, + () -> client.loadTableMetadata("default", "t", OptionalLong.empty(), new LanceMetadataMetrics())); + Future first = executor.submit(read); + Future second = executor.submit(read); + Assertions.assertTrue(resources.childAllocators.await(10, TimeUnit.SECONDS)); + RecordingAllocator root = resources.allocators.get(0); + List children = new ArrayList<>(root.getChildAllocators()); + Assertions.assertEquals(2, children.size()); + try (ArrowBuf buffer = children.get(0).buffer(1024)) { + Assertions.assertEquals(1024, root.getAllocatedMemory()); + Assertions.assertThrows(OutOfMemoryException.class, () -> children.get(1).buffer(1)); + } + try (ArrowBuf buffer = children.get(1).buffer(1024)) { + Assertions.assertEquals(1024, root.getAllocatedMemory()); + } + release.countDown(); + Assertions.assertTrue(first.get(10, TimeUnit.SECONDS).getMessage() + .startsWith("Failed to load Lance table metadata for default.t")); + second.get(10, TimeUnit.SECONDS); + Assertions.assertEquals(0, root.getAllocatedMemory()); + Assertions.assertTrue(root.getChildAllocators().isEmpty()); + } finally { + release.countDown(); + shutdown(executor); + client.close(); + } + } + + private LanceCatalogClient client(long arrowMemoryLimitBytes) { + return new LanceCatalogClient(filesystem(), Collections::emptyList, () -> arrowMemoryLimitBytes, resources, + () -> 0L); + } + + private static LanceCatalogProperties filesystem() { + Map properties = new HashMap<>(); + properties.put("type", "lance"); + properties.put("warehouse", "/tmp/lance"); + return LanceCatalogProperties.of(properties); + } + + private static FakeLanceNamespace blockingExistenceChecks(CountDownLatch entered, CountDownLatch release) { + FakeLanceNamespace namespace = new FakeLanceNamespace(); + namespace.tableExists = request -> { + entered.countDown(); + await(release); + }; + return namespace; + } + + private static void await(CountDownLatch latch) { + try { + Assertions.assertTrue(latch.await(10, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + } + + private static void shutdown(ExecutorService executor) throws InterruptedException { + executor.shutdownNow(); + Assertions.assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); + } +} diff --git a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceCatalogPropertiesTest.java b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceCatalogPropertiesTest.java index f19ed8623a0c19..ae915e8fa2e3a9 100644 --- a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceCatalogPropertiesTest.java +++ b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceCatalogPropertiesTest.java @@ -70,6 +70,25 @@ void defaultsDescribeAFilesystemCatalogRootedAtTheWarehouse() { Assertions.assertEquals(Collections.emptyList(), properties.secretValues()); } + /** The table-access cache TTL (4.2's key and rules): 60 seconds by default, 0 disables it, never negative. */ + @Test + void tableAccessCacheTtlDefaultsToAMinuteAndMayBeDisabled() { + Assertions.assertEquals(60, LanceCatalogProperties.of(filesystem("/tmp/lance")).getTableAccessCacheTtlSeconds()); + for (Map catalog : Arrays.asList(filesystem("/tmp/lance"), rest())) { + for (String ttl : new String[] {"0", "120", " 5 "}) { + catalog.put(LanceCatalogProperties.TABLE_ACCESS_CACHE_TTL_SECONDS, ttl); + Assertions.assertEquals(Integer.parseInt(ttl.trim()), + LanceCatalogProperties.of(catalog).getTableAccessCacheTtlSeconds()); + } + catalog.put(LanceCatalogProperties.TABLE_ACCESS_CACHE_TTL_SECONDS, "-1"); + Assertions.assertEquals("Property 'lance.table_access_cache_ttl_seconds' must be non-negative", + rejection(catalog)); + catalog.put(LanceCatalogProperties.TABLE_ACCESS_CACHE_TTL_SECONDS, "a minute"); + Assertions.assertTrue(rejection(catalog).startsWith( + "Failed to set property 'lance.table_access_cache_ttl_seconds'"), rejection(catalog)); + } + } + /** The maps 4.1.x persisted for its Lance catalogs (fe-core's upgrade/415 fixture) still bind unchanged. */ @Test void catalogsWrittenByEarlierVersionsStillBind() { diff --git a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceConnectorNativeTest.java b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceConnectorNativeTest.java index 9bc8e3fd225ae1..08b192905f721a 100644 --- a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceConnectorNativeTest.java +++ b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceConnectorNativeTest.java @@ -26,6 +26,7 @@ import org.apache.doris.connector.spi.handle.NamedColumnHandle; import org.apache.doris.connector.spi.mvcc.ConnectorMvccSnapshot; import org.apache.doris.connector.spi.mvcc.ConnectorTimeTravelSpec; +import org.apache.doris.connector.spi.scan.ConnectorScanProfile; import org.apache.doris.connector.spi.scan.ConnectorScanRange; import org.apache.doris.connector.spi.scan.ConnectorScanRequest; import org.apache.doris.connector.spi.scan.ScanNodePropertyKeys; @@ -204,6 +205,38 @@ void missingVersionAndUnsupportedSelectorsFailClearly() { "Lance tables do not support @branch yet")); } + /** + * The profile of a scan counts each stage of the statement's metadata reads of its table, and its planning: the + * query-begin pin reads the newest version, FOR TIME AS OF opens the newest version and then the one it picks, + * and the scan of the pinned version reuses the statement's first read. + */ + @Test + void scanProfileCountsTheStatementsMetadataReadsAndItsPlanning() { + ConnectorMvccSnapshot pin = metadata.beginQuerySnapshot(session, table).get(); + Assertions.assertEquals(2, metadata.resolveTimeTravel(session, table, + ConnectorTimeTravelSpec.timestamp("2026-07-20 03:53:50.755", false)).get().getSnapshotId()); + plan(metadata.applySnapshot(session, table, pin)); + + List profiles = connector.getScanPlanProvider().collectScanProfiles(session); + Assertions.assertEquals(1, profiles.size()); + Assertions.assertEquals("Lance Metadata Metrics", profiles.get(0).getGroupName()); + Assertions.assertEquals("Table Scan (default.all_types)", profiles.get(0).getScanLabel()); + Map counts = new HashMap<>(profiles.get(0).getMetrics()); + counts.keySet().removeIf(name -> name.endsWith("Time")); + Map expected = new HashMap<>(); + expected.put("MetadataReadCalls", "2"); + expected.put("MetadataReadFailures", "0"); + expected.put("SplitPlanningCalls", "1"); + expected.put("SplitPlanningFailures", "0"); + expected.put("TableAccessResolveCalls", "2"); + expected.put("DatasetOpenCalls", "3"); + expected.put("VersionResolveCalls", "1"); + expected.put("SchemaReadCalls", "2"); + expected.put("FragmentMetadataReadCalls", "2"); + Assertions.assertEquals(expected, counts); + Assertions.assertTrue(connector.getScanPlanProvider().collectScanProfiles(session).isEmpty()); + } + /** The regression dataset carries every type Lance tables map, including the additional ones. */ @Test void projectingAnAdditionalTypeRaisesTheUpgradeFence(@TempDir Path regressionWarehouse) throws Exception { diff --git a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceConnectorTest.java b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceConnectorTest.java index ee1c1127e59a51..fa86bbb18e796f 100644 --- a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceConnectorTest.java +++ b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceConnectorTest.java @@ -58,18 +58,60 @@ void declaresStatementSnapshots() { /** An FE replaying the edit log builds every catalog: building one must not reach storage or lance.conf. */ @Test void buildingTheConnectorReadsNothing() { - LanceTestContext unreachable = new LanceTestContext() { + new LanceConnector(filesystem(), unreachable("building the connector")).close(); + } + + /** + * The engine routes REFRESH CATALOG / DATABASE / TABLE, and their replay, to the connector: on a catalog no + * statement has used yet they open nothing. + */ + @Test + void refreshingAnUnusedCatalogReadsNothing() { + LanceConnector connector = new LanceConnector(filesystem(), unreachable("a refresh")); + connector.invalidateTable("default", "t"); + connector.invalidateDb("default"); + connector.invalidateAll(); + connector.close(); + } + + /** + * REFRESH CATALOG replaces the catalog's generation, so the next call connects a new namespace (with a new + * Session); REFRESH DATABASE and TABLE keep it. + */ + @Test + void onlyCatalogRefreshReplacesTheGeneration() { + FakeResourceFactory resources = new FakeResourceFactory(); + LanceCatalogProperties properties = LanceCatalogProperties.of(filesystem()); + LanceConnector connector = new LanceConnector(properties, new LanceTestContext(), new LanceCatalogClient( + properties, Collections::emptyList, () -> 1024 * 1024, resources, () -> 0L)); + LanceTestSession session = new LanceTestSession(); + connector.getMetadata(session).listDatabaseNames(session); + connector.invalidateTable("default", "t"); + connector.invalidateDb("default"); + connector.getMetadata(session).listDatabaseNames(session); + Assertions.assertEquals(1, resources.namespaces.size()); + Assertions.assertEquals(0, resources.namespaces.get(0).closes.get()); + + connector.invalidateAll(); + Assertions.assertEquals(1, resources.namespaces.get(0).closes.get()); + connector.getMetadata(session).listDatabaseNames(session); + Assertions.assertEquals(2, resources.namespaces.size()); + connector.close(); + Assertions.assertEquals(1, resources.namespaces.get(1).closes.get()); + } + + private static LanceTestContext unreachable(String what) { + return new LanceTestContext() { @Override public ConnectorStorageContext getStorageContext() { - throw new AssertionError("building the connector must not bind storage properties"); + throw new AssertionError(what + " must not bind storage properties"); } @Override public Map getConnectorConfig() { - throw new AssertionError("building the connector must not read lance.conf"); + throw new AssertionError(what + " must not read lance.conf"); } }; - new LanceConnector(filesystem(), unreachable).close(); } /** A REST namespace reads no storage of its own, so CREATE has nothing to check before test_connection. */ diff --git a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceIndexMetadataTest.java b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceIndexMetadataTest.java new file mode 100644 index 00000000000000..2b56d71394650e --- /dev/null +++ b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceIndexMetadataTest.java @@ -0,0 +1,82 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.doris.connector.lance; + +import org.apache.doris.connector.lance.LanceMetadataMetrics.Operation; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +/** How reading a version's field ids and indexes handles what the SDK cannot describe. */ +class LanceIndexMetadataTest { + + /** + * Lance's JNI converter cannot represent some types, notably Dictionary. Field ids are then unavailable, so no + * index segment is planned, but the indexes are still discovered and validated. + */ + @Test + void knownSchemaConversionFailureStillDiscoversTheIndexes() { + AtomicInteger discoveries = new AtomicInteger(); + LanceIndexMetadata metadata = LanceIndexMetadata.read(() -> { + throw new IllegalArgumentException("ArrowSchema conversion error"); + }, () -> { + discoveries.incrementAndGet(); + return Collections.emptyList(); + }, 7, new LanceMetadataMetrics().start(Operation.METADATA_READ)); + Assertions.assertFalse(metadata.canPlanIndexSegments()); + Assertions.assertFalse(metadata.getLanceFieldId("id").isPresent()); + Assertions.assertEquals(1, discoveries.get()); + + // Only that known failure falls back; any other failure of the schema read is an error. + Assertions.assertEquals("another failure", Assertions.assertThrows(IllegalArgumentException.class, + () -> LanceIndexMetadata.read(() -> { + throw new IllegalArgumentException("another failure"); + }, Collections::emptyList, 7, new LanceMetadataMetrics().start(Operation.METADATA_READ))) + .getMessage()); + } + + @Test + void schemaFallbackDoesNotHideInvalidIndexMetadata() { + IllegalArgumentException invalid = new IllegalArgumentException("Lance index names must not be null"); + Assertions.assertSame(invalid, Assertions.assertThrows(IllegalArgumentException.class, + () -> LanceIndexMetadata.read(() -> { + throw new IllegalArgumentException("ArrowSchema conversion error"); + }, () -> { + throw invalid; + }, 7, new LanceMetadataMetrics().start(Operation.METADATA_READ)))); + } + + @Test + void fieldIdAndIndexReadsAreTimedAsTheirStages() { + LanceMetadataMetrics metrics = new LanceMetadataMetrics(); + try (LanceMetadataMetrics.Timer timer = metrics.start(Operation.METADATA_READ)) { + LanceIndexMetadata.read(() -> { + throw new IllegalArgumentException("ArrowSchema conversion error"); + }, Collections::emptyList, 7, timer); + timer.succeeded(); + } + Map values = metrics.drain(); + Assertions.assertEquals("1", values.get("FieldIdsReadCalls")); + Assertions.assertEquals("1", values.get("IndexMetadataReadCalls")); + Assertions.assertFalse(values.containsKey("DatasetOpenCalls")); + } +} diff --git a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceMetadataMetricsTest.java b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceMetadataMetricsTest.java new file mode 100644 index 00000000000000..edbd75dae7304a --- /dev/null +++ b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceMetadataMetricsTest.java @@ -0,0 +1,161 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.doris.connector.lance; + +import org.apache.doris.connector.lance.LanceMetadataMetrics.Operation; +import org.apache.doris.connector.lance.LanceMetadataMetrics.Stage; +import org.apache.doris.connector.spi.scan.ConnectorScanProfile; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +class LanceMetadataMetricsTest { + + /** A failed read counts once, as a call and a failure, with the stages it reached. */ + @Test + void failedReadKeepsAccurateTotals() { + LanceMetadataMetrics metrics = new LanceMetadataMetrics(); + IllegalStateException original = new IllegalStateException("read failed"); + LanceMetadataMetrics.Timer failedRead = metrics.start(Operation.METADATA_READ); + Assertions.assertSame(original, Assertions.assertThrows(IllegalStateException.class, + () -> failedRead.measure(Stage.DATASET_OPEN, () -> { + throw original; + }))); + failedRead.close(); + failedRead.close(); + try (LanceMetadataMetrics.Timer read = metrics.start(Operation.METADATA_READ)) { + Assertions.assertEquals("schema", read.measure(Stage.SCHEMA, () -> "schema")); + read.succeeded(); + } + try (LanceMetadataMetrics.Timer plan = metrics.start(Operation.SPLIT_PLANNING)) { + plan.succeeded(); + } + + Map values = metrics.drain(); + Assertions.assertEquals(Arrays.asList("MetadataReadTime", "MetadataReadCalls", "MetadataReadFailures", + "SplitPlanningTime", "SplitPlanningCalls", "SplitPlanningFailures", "DatasetOpenTime", + "DatasetOpenCalls", "SchemaReadTime", "SchemaReadCalls"), new ArrayList<>(values.keySet())); + Assertions.assertEquals("2", values.get("MetadataReadCalls")); + Assertions.assertEquals("1", values.get("MetadataReadFailures")); + Assertions.assertEquals("1", values.get("SplitPlanningCalls")); + Assertions.assertEquals("0", values.get("SplitPlanningFailures")); + Assertions.assertEquals("1", values.get("DatasetOpenCalls")); + Assertions.assertEquals("1", values.get("SchemaReadCalls")); + // Drained: the next scan of the table reports only what comes after. + Assertions.assertTrue(metrics.drain().isEmpty()); + } + + @Test + void concurrentReadsAccumulateWithoutOverwritingOneAnother() throws Exception { + LanceMetadataMetrics metrics = new LanceMetadataMetrics(); + ExecutorService executor = Executors.newFixedThreadPool(4); + try { + List> work = new ArrayList<>(); + for (int i = 0; i < 100; i++) { + work.add(executor.submit(() -> { + try (LanceMetadataMetrics.Timer read = metrics.start(Operation.METADATA_READ)) { + read.measure(Stage.SCHEMA, () -> "schema"); + read.succeeded(); + } + })); + } + for (Future future : work) { + future.get(10, TimeUnit.SECONDS); + } + } finally { + executor.shutdownNow(); + Assertions.assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); + } + Map values = metrics.drain(); + Assertions.assertEquals("100", values.get("MetadataReadCalls")); + Assertions.assertEquals("0", values.get("MetadataReadFailures")); + Assertions.assertEquals("100", values.get("SchemaReadCalls")); + } + + /** + * The totals are per table and per statement, and each scan publishes and restarts its table's totals; the + * engine collects the published profiles once. + */ + @Test + void eachScanPublishesItsTablesTotalsOnce() { + LanceTestSession session = new LanceTestSession(); + LanceMetadataMetrics items = LanceMetadataMetrics.forTable(session, "default", "items"); + Assertions.assertSame(items, LanceMetadataMetrics.forTable(session, "default", "items")); + Assertions.assertNotSame(items, LanceMetadataMetrics.forTable(session, "default", "other")); + Assertions.assertNotSame(items, LanceMetadataMetrics.forTable(new LanceTestSession(), "default", "items")); + try (LanceMetadataMetrics.Timer read = items.start(Operation.METADATA_READ)) { + read.succeeded(); + } + + LanceMetadataMetrics.publishScan(session, "default", "items", items); + List profiles = LanceMetadataMetrics.collectScanProfiles(session); + Assertions.assertEquals(1, profiles.size()); + Assertions.assertEquals("Lance Metadata Metrics", profiles.get(0).getGroupName()); + Assertions.assertEquals("Table Scan (default.items)", profiles.get(0).getScanLabel()); + Assertions.assertEquals("1", profiles.get(0).getMetrics().get("MetadataReadCalls")); + Assertions.assertTrue(LanceMetadataMetrics.collectScanProfiles(session).isEmpty()); + + // A second scan of the table in the statement reports only what came after the first. + LanceMetadataMetrics.publishScan(session, "default", "items", items); + Assertions.assertTrue(LanceMetadataMetrics.collectScanProfiles(session).get(0).getMetrics().isEmpty()); + } + + /** Outside a live statement a read still runs and fails as it would, and nothing is ever published. */ + @Test + void readsOutsideAStatementRunAndReportNothing() { + LanceTestSession offline = LanceTestSession.withoutStatement(); + LanceMetadataMetrics metrics = LanceMetadataMetrics.forTable(offline, "default", "items"); + Assertions.assertNotSame(metrics, LanceMetadataMetrics.forTable(offline, "default", "items")); + try (LanceMetadataMetrics.Timer read = metrics.start(Operation.METADATA_READ)) { + Assertions.assertEquals(42, read.measure(Stage.SCHEMA, () -> 42)); + IllegalArgumentException failure = new IllegalArgumentException("bad metadata"); + Assertions.assertSame(failure, Assertions.assertThrows(IllegalArgumentException.class, + () -> read.measure(Stage.INDEXES, () -> { + throw failure; + }))); + } + LanceMetadataMetrics.publishScan(offline, "default", "items", metrics); + Assertions.assertTrue(LanceMetadataMetrics.collectScanProfiles(offline).isEmpty()); + Assertions.assertNotSame(LanceMetadataMetrics.forTable(null, "default", "items"), + LanceMetadataMetrics.forTable(null, "default", "items")); + } + + @Test + void timesAreRenderedAsTheProfileRendersNanosecondTimers() { + Assertions.assertEquals("0ns", LanceMetadataMetrics.prettyNanos(0)); + Assertions.assertEquals("999ns", LanceMetadataMetrics.prettyNanos(999)); + Assertions.assertEquals("1.000us", LanceMetadataMetrics.prettyNanos(1_000)); + Assertions.assertEquals("12.005us", LanceMetadataMetrics.prettyNanos(12_005)); + Assertions.assertEquals("1.005ms", LanceMetadataMetrics.prettyNanos(1_005_000)); + Assertions.assertEquals("999.999ms", LanceMetadataMetrics.prettyNanos(999_999_999)); + Assertions.assertEquals("1sec0ms", LanceMetadataMetrics.prettyNanos(TimeUnit.SECONDS.toNanos(1))); + Assertions.assertEquals("2sec5ms", LanceMetadataMetrics.prettyNanos(TimeUnit.MILLISECONDS.toNanos(2_005))); + Assertions.assertEquals("1min1sec", LanceMetadataMetrics.prettyNanos(TimeUnit.MILLISECONDS.toNanos(61_500))); + Assertions.assertEquals("1hour2min", LanceMetadataMetrics.prettyNanos( + TimeUnit.MINUTES.toNanos(62) + TimeUnit.SECONDS.toNanos(3))); + } +} diff --git a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceRestCatalogTest.java b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceRestCatalogTest.java index 1670ac7be66d6d..5616a42d521beb 100644 --- a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceRestCatalogTest.java +++ b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceRestCatalogTest.java @@ -229,6 +229,46 @@ void describeAsksForVendedCredentialsAndOpensTheDescribedDataset() throws IOExce } } + /** + * A described table access serves the later statements until its TTL runs out or a refresh: REFRESH TABLE and + * REFRESH DATABASE describe the table again, and so does the new generation REFRESH CATALOG opens. With a TTL + * of 0 every statement describes it. + */ + @Test + void describedAccessServesLaterStatementsUntilARefresh() throws IOException { + datasetUri = LanceNativeTestSupport.copyDataset(LanceNativeTestSupport.VERSIONED_ALL_TYPES, warehouse) + .toUri().toString(); + LanceConnector connector = open(rest(restUri)); + try { + Assertions.assertEquals(3, newestVersion(connector)); + Assertions.assertEquals(3, newestVersion(connector)); + Assertions.assertEquals(1, describes()); + connector.invalidateTable("default", "all_types"); + newestVersion(connector); + Assertions.assertEquals(2, describes()); + connector.invalidateDb("default"); + newestVersion(connector); + Assertions.assertEquals(3, describes()); + connector.invalidateAll(); + Assertions.assertEquals(3, newestVersion(connector)); + Assertions.assertEquals(4, describes()); + } finally { + connector.close(); + } + + requests.clear(); + Map uncached = rest(restUri); + uncached.put(LanceCatalogProperties.TABLE_ACCESS_CACHE_TTL_SECONDS, "0"); + LanceConnector everyRead = open(uncached); + try { + newestVersion(everyRead); + newestVersion(everyRead); + Assertions.assertEquals(2, describes()); + } finally { + everyRead.close(); + } + } + /** U4: until Doris reads the versions a namespace records, such a table is refused, not read at random. */ @Test void tablesWhoseVersionsTheNamespaceManagesAreRefused() { @@ -250,6 +290,17 @@ void tablesWhoseVersionsTheNamespaceManagesAreRefused() { } } + /** The newest version a new statement pins. */ + private static long newestVersion(LanceConnector connector) { + LanceTestSession session = new LanceTestSession(); + return connector.getMetadata(session).beginQuerySnapshot(session, new LanceTableHandle("default", "all_types")) + .get().getSnapshotId(); + } + + private long describes() { + return requests.stream().filter(request -> request.path.endsWith("/describe")).count(); + } + private static Map rest(String uri) { Map properties = new HashMap<>(); properties.put("type", "lance"); diff --git a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceScanPlanProviderTest.java b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceScanPlanProviderTest.java index 7d457695e7641e..95d9a344a4ad6b 100644 --- a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceScanPlanProviderTest.java +++ b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceScanPlanProviderTest.java @@ -26,6 +26,7 @@ import org.apache.doris.connector.spi.pushdown.ConnectorComparison; import org.apache.doris.connector.spi.pushdown.ConnectorExpression; import org.apache.doris.connector.spi.pushdown.ConnectorLiteral; +import org.apache.doris.connector.spi.scan.ConnectorScanProfile; import org.apache.doris.connector.spi.scan.ConnectorScanRange; import org.apache.doris.connector.spi.scan.ConnectorScanRequest; import org.apache.doris.connector.spi.scan.ScanNodePropertiesResult; @@ -440,4 +441,30 @@ void scanWithNothingPushedNeverReadsIndexMetadata() { // The control: a pushed predicate does ask for the index metadata. Assertions.assertThrows(AssertionError.class, () -> plan(provider, request().filter(Optional.of(ID_IS_5)))); } + + /** + * Every planned scan leaves its table's metadata metrics for the engine to collect, a failed plan too. The + * statement read this version before, so the scans made no metadata read of their own. + */ + @Test + void everyPlannedScanLeavesItsProfileEvenWhenPlanningFails() { + readInThisStatement(metadata(Collections.emptyMap(), new LanceFragmentInfo(0, 1, 1))); + LanceScanPlanProvider provider = provider(Collections.emptyMap()); + Assertions.assertEquals(1, plan(provider, request()).size()); + session.setSessionProperty(LanceScanPlanProvider.SESSION_FRAGMENTS_PER_SPLIT, "-1"); + Assertions.assertEquals("lance_fragments_per_split must be non-negative", Assertions.assertThrows( + DorisConnectorException.class, () -> plan(provider, request())).getMessage()); + + List profiles = provider.collectScanProfiles(session); + Assertions.assertEquals(2, profiles.size()); + for (ConnectorScanProfile profile : profiles) { + Assertions.assertEquals("Lance Metadata Metrics", profile.getGroupName()); + Assertions.assertEquals("Table Scan (default.all_types)", profile.getScanLabel()); + Assertions.assertEquals("1", profile.getMetrics().get("SplitPlanningCalls")); + Assertions.assertFalse(profile.getMetrics().containsKey("MetadataReadCalls")); + } + Assertions.assertEquals("0", profiles.get(0).getMetrics().get("SplitPlanningFailures")); + Assertions.assertEquals("1", profiles.get(1).getMetrics().get("SplitPlanningFailures")); + Assertions.assertTrue(provider.collectScanProfiles(session).isEmpty()); + } } diff --git a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceSharedSessionNativeTest.java b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceSharedSessionNativeTest.java new file mode 100644 index 00000000000000..c6a00f12f54fdb --- /dev/null +++ b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceSharedSessionNativeTest.java @@ -0,0 +1,223 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.doris.connector.lance; + +import com.github.benmanes.caffeine.cache.Ticker; +import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.memory.RootAllocator; +import org.apache.arrow.vector.IntVector; +import org.apache.arrow.vector.VectorSchemaRoot; +import org.apache.arrow.vector.types.pojo.ArrowType; +import org.apache.arrow.vector.types.pojo.Field; +import org.apache.arrow.vector.types.pojo.Schema; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.lance.Dataset; +import org.lance.Fragment; +import org.lance.FragmentMetadata; +import org.lance.FragmentOperation; +import org.lance.Session; +import org.lance.WriteParams; +import org.lance.index.IndexParams; +import org.lance.index.IndexType; +import org.lance.index.scalar.ScalarIndexParams; +import org.lance.namespace.model.DescribeTableResponse; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.OptionalLong; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * A catalog's Lance Session on a real dataset: every metadata read of a generation opens its dataset with that one + * Session, a later read of a version already read is served from its metadata cache, the newest version is still + * found, and a refresh closes it and moves the next read to a new one, which reads afresh a dataset written again + * at the same URI. + * + *

Describes go to a recording namespace that names the copied dataset, so that the table-access cache can be + * counted; the allocator, the Session and the dataset reads are the real ones. Skips, loudly, where the native + * libraries cannot load; see {@link LanceNativeTestSupport}. + */ +class LanceSharedSessionNativeTest { + + @TempDir + Path warehouse; + + private final FakeResourceFactory resources = new FakeResourceFactory(); + private Path dataset; + private LanceCatalogProperties properties; + private LanceCatalogClient client; + + @BeforeEach + void openCatalogOverTheVersionedDataset() throws Exception { + LanceNativeTestSupport.requireNativeLibraries(); + dataset = LanceNativeTestSupport.copyDataset(LanceNativeTestSupport.VERSIONED_ALL_TYPES, warehouse); + String uri = dataset.toString(); + resources.nextNamespace = () -> new FakeLanceNamespace().describing( + new DescribeTableResponse().tableUri(uri)); + resources.nextSession = () -> Session.builder() + .metadataCacheSizeBytes(LanceCatalogClient.SESSION_METADATA_CACHE_BYTES) + .indexCacheSizeBytes(LanceCatalogClient.SESSION_INDEX_CACHE_BYTES).build(); + Map catalogProperties = new HashMap<>(); + catalogProperties.put("type", "lance"); + catalogProperties.put("warehouse", warehouse.toString()); + properties = LanceCatalogProperties.of(catalogProperties); + client = new LanceCatalogClient(properties, Collections::emptyList, + () -> 256L * 1024 * 1024, resources, Ticker.systemTicker()); + } + + @AfterEach + void closeCatalog() { + if (client != null) { + client.close(); + } + } + + @Test + void readsShareOneSessionAndALaterReadOfAVersionHitsItsCache() { + Assertions.assertEquals(3, read(OptionalLong.of(3)).getVersion()); + Session session = resources.sessions.get(0); + long hits = session.metadataCacheStats().getHits(); + Assertions.assertEquals(3, read(OptionalLong.of(3)).getVersion()); + Assertions.assertTrue(session.metadataCacheStats().getHits() > hits, + "the second read of version 3 must be served from the Session's metadata cache"); + Assertions.assertEquals(1, read(OptionalLong.of(1)).getFragments().size()); + Assertions.assertEquals(1, resources.sessions.size()); + // The access described by the first read served the other two. + Assertions.assertEquals(1, resources.namespaces.get(0).describes.size()); + } + + @Test + void newestVersionIsStillFoundThroughTheSharedSession() { + Assertions.assertEquals(3, read(OptionalLong.empty()).getVersion()); + try (Dataset writer = Dataset.open(dataset.toString())) { + writer.updateConfig(Collections.singletonMap("doris_test_key", "new_version")); + } + Assertions.assertEquals(4, read(OptionalLong.empty()).getVersion()); + Assertions.assertEquals(3, read(OptionalLong.of(3)).getVersion()); + Assertions.assertEquals(1, resources.sessions.size()); + } + + @Test + void tableAccessInvalidationDescribesAgainWithTheSameSession() { + read(OptionalLong.of(3)); + client.invalidateTableAccess(); + read(OptionalLong.of(3)); + Assertions.assertEquals(2, resources.namespaces.get(0).describes.size()); + Assertions.assertEquals(1, resources.sessions.size()); + Assertions.assertFalse(resources.sessions.get(0).isClosed()); + } + + @Test + void refreshClosesTheSessionAndTheNextReadOpensANewGeneration() { + read(OptionalLong.of(3)); + Session first = resources.sessions.get(0); + client.refresh(); + Assertions.assertTrue(first.isClosed()); + + Assertions.assertEquals(3, read(OptionalLong.of(3)).getVersion()); + Assertions.assertEquals(2, resources.sessions.size()); + Assertions.assertFalse(resources.sessions.get(1).isClosed()); + Assertions.assertEquals(1, resources.namespaces.get(1).describes.size()); + client.close(); + Assertions.assertTrue(resources.sessions.get(1).isClosed()); + } + + /** + * A dataset deleted and written again at the same URI starts its versions over. With V1 manifest names Lance + * keys a version's index list by the version alone, so the old Session can serve the deleted dataset's indexes + * for the new dataset's version 2; REFRESH CATALOG moves the next read to a new Session, which reads the new + * dataset's. + */ + @Test + void catalogRefreshReadsTheIndexesOfADatasetWrittenAgainAtTheSameUri() throws IOException { + Path recreated = warehouse.resolve("recreated.lance"); + String uri = recreated.toString(); + resources.nextNamespace = () -> new FakeLanceNamespace().describing( + new DescribeTableResponse().tableUri(uri)); + // Version 1 holds the rows, version 2 adds a BTREE index on them. + commitRows(uri, 0); + try (Dataset writer = Dataset.open(uri)) { + writer.createIndex(Collections.singletonList("id"), IndexType.BTREE, Optional.of("id_idx"), + IndexParams.builder().setScalarIndexParams(ScalarIndexParams.create("btree")).build(), true); + } + Assertions.assertEquals(Collections.singletonList("id_idx"), indexesOfTheNewestVersion(2)); + + // The same URI again: version 1 holds other rows, version 2 changes a setting and indexes nothing. + deleteRecursively(recreated); + commitRows(uri, 100); + try (Dataset writer = Dataset.open(uri)) { + writer.updateConfig(Collections.singletonMap("doris_test_key", "written_again")); + } + Assertions.assertTrue(Files.exists(recreated.resolve("_versions").resolve("2.manifest")), + "V1 manifest names expected: with V2 names Lance keys the index list by the manifest's e-tag too"); + + new LanceConnector(properties, new LanceTestContext(), client).invalidateAll(); + Assertions.assertEquals(Collections.emptyList(), indexesOfTheNewestVersion(2)); + Assertions.assertEquals(2, resources.sessions.size()); + } + + private LanceTableMetadata read(OptionalLong version) { + return client.loadTableMetadata("default", "all_types", version, new LanceMetadataMetrics()); + } + + /** What planning a scan with a pushed filter reads: the newest version, then the indexes of that version. */ + private List indexesOfTheNewestVersion(long expectedVersion) { + LanceMetadataMetrics metrics = new LanceMetadataMetrics(); + long version = client.loadTableMetadata("default", "recreated", OptionalLong.empty(), metrics).getVersion(); + Assertions.assertEquals(expectedVersion, version); + return client.loadIndexMetadata("default", "recreated", version, metrics).getIndexes().stream() + .map(LanceIndexSegmentGroup::getName).collect(Collectors.toList()); + } + + /** Commits three rows from {@code first} on as version 1 of a new dataset at {@code uri}. */ + private static void commitRows(String uri, int first) { + Schema schema = new Schema(Collections.singletonList(Field.nullable("id", new ArrowType.Int(32, true)))); + try (BufferAllocator allocator = new RootAllocator(); + VectorSchemaRoot rows = VectorSchemaRoot.create(schema, allocator)) { + rows.allocateNew(); + IntVector ids = (IntVector) rows.getVector("id"); + for (int i = 0; i < 3; i++) { + ids.setSafe(i, first + i); + } + rows.setRowCount(3); + List fragments = Fragment.create(uri, allocator, rows, new WriteParams.Builder().build()); + new FragmentOperation.Overwrite(fragments, schema) + .commit(allocator, uri, Optional.empty(), Collections.emptyMap()).close(); + } + } + + private static void deleteRecursively(Path directory) throws IOException { + try (Stream paths = Files.walk(directory)) { + for (Path path : paths.sorted(Comparator.reverseOrder()).collect(Collectors.toList())) { + Files.delete(path); + } + } + } +} diff --git a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceStatementScopeTest.java b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceStatementScopeTest.java index c631d594e3ba93..43dfaab6c4d588 100644 --- a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceStatementScopeTest.java +++ b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceStatementScopeTest.java @@ -35,7 +35,8 @@ class LanceStatementScopeTest { void namespaceIsPrefixedWithTheConnectorType() { String type = new LanceConnectorProvider().getType(); for (String namespace : Arrays.asList(LanceStatementScope.TABLE_METADATA_NAMESPACE, - LanceStatementScope.INDEX_METADATA_NAMESPACE)) { + LanceStatementScope.INDEX_METADATA_NAMESPACE, LanceMetadataMetrics.TABLE_METRICS_NAMESPACE, + LanceMetadataMetrics.SCAN_PROFILES_KEY_PREFIX)) { Assertions.assertTrue(namespace.startsWith(type + "."), "Namespace '" + namespace + "' must start with the connector type '" + type + ".'"); } diff --git a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceTableAccessCacheTest.java b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceTableAccessCacheTest.java new file mode 100644 index 00000000000000..979884f36c0b12 --- /dev/null +++ b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceTableAccessCacheTest.java @@ -0,0 +1,324 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.doris.connector.lance; + +import org.apache.doris.connector.spi.DorisConnectorException; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.lance.namespace.model.DescribeTableResponse; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +/** + * The table-access cache of {@link LanceNamespaceClient}: a described dataset URI and its storage options are + * reused until the TTL counted from the describe runs out, never when they may carry credentials, and an + * invalidation is never undone by a describe that was in flight. + */ +class LanceTableAccessCacheTest { + + @Test + void repeatedFilesystemReadDescribesOnce() { + FakeLanceNamespace namespace = new FakeLanceNamespace(); + LanceNamespaceClient client = client(namespace, false, 60, new AtomicLong(1_000_000)); + Assertions.assertEquals("file:///warehouse/items.lance", + client.resolveTableAccess("default", "items").getDatasetUri()); + client.resolveTableAccess("default", "items"); + Assertions.assertEquals(1, namespace.describes.size()); + } + + @Test + void repeatedRestReadDescribesOnceAndAsksForVendedCredentials() { + FakeLanceNamespace namespace = new FakeLanceNamespace().describing( + new DescribeTableResponse().tableUri("s3://example-bucket/items.lance")); + LanceNamespaceClient client = client(namespace, true, 60, new AtomicLong(1_000_000)); + client.resolveTableAccess("default", "items"); + client.resolveTableAccess("default", "items"); + Assertions.assertEquals(1, namespace.describes.size()); + Assertions.assertEquals(Boolean.TRUE, namespace.describes.get(0).getVendCredentials()); + } + + @Test + void expiryIsCountedFromTheDescribeAndNotExtendedByHits() { + FakeLanceNamespace namespace = new FakeLanceNamespace(); + AtomicLong millis = new AtomicLong(1_000_000); + LanceNamespaceClient client = client(namespace, false, 60, millis); + client.resolveTableAccess("default", "items"); + millis.addAndGet(59_000); + client.resolveTableAccess("default", "items"); + Assertions.assertEquals(1, namespace.describes.size()); + millis.addAndGet(1_000); + client.resolveTableAccess("default", "items"); + Assertions.assertEquals(2, namespace.describes.size()); + } + + @Test + void zeroTtlDescribesOnEveryRead() { + FakeLanceNamespace namespace = new FakeLanceNamespace(); + LanceNamespaceClient client = client(namespace, true, 0, new AtomicLong(1_000_000)); + client.resolveTableAccess("default", "items"); + client.resolveTableAccess("default", "items"); + Assertions.assertEquals(2, namespace.describes.size()); + } + + /** A table the connector refuses is described, and refused, again on every read: no refusal is cached. */ + @Test + void namespaceManagedTableIsRefusedOnEveryRead() { + FakeLanceNamespace namespace = new FakeLanceNamespace().describing(new DescribeTableResponse() + .location("s3://example-bucket/items.lance").tableUri("s3://example-bucket/items.lance") + .managedVersioning(true)); + LanceNamespaceClient client = client(namespace, true, 60, new AtomicLong(1_000_000)); + for (int read = 0; read < 2; read++) { + Assertions.assertEquals("Lance table default.items has its versions managed by the namespace" + + " (managed_versioning), which is not supported yet", Assertions.assertThrows( + DorisConnectorException.class, () -> client.resolveTableAccess("default", "items")) + .getMessage()); + } + Assertions.assertEquals(2, namespace.describes.size()); + } + + @Test + void vendedCredentialsAreDescribedForEveryRead() { + AtomicLong millis = new AtomicLong(1_000_000); + Map vended = vendedS3Credentials(); + vended.put("expires_at_millis", "1040000"); + FakeLanceNamespace namespace = new FakeLanceNamespace().describing(new DescribeTableResponse() + .tableUri("s3://example-bucket/items.lance").storageOptions(vended)); + LanceNamespaceClient client = client(namespace, true, 60, millis); + LanceTableAccess first = client.resolveTableAccess("default", "items"); + Assertions.assertThrows(UnsupportedOperationException.class, + () -> first.getStorageOptions().put("aws_session_token", "modified")); + millis.addAndGet(9_000); + // A new scan may outlive what is left of the credentials, whatever the cache TTL. + Assertions.assertNotSame(first, client.resolveTableAccess("default", "items")); + Assertions.assertEquals(2, namespace.describes.size()); + } + + @Test + void vendedCredentialsWithAnyExpiryAreNotCached() { + for (String expiry : new String[] {null, "invalid", "-9223372036854775808", "999999", "1029999", + "99999999999"}) { + Map vended = vendedS3Credentials(); + if (expiry != null) { + vended.put("expires_at_millis", expiry); + } + FakeLanceNamespace namespace = new FakeLanceNamespace().describing(new DescribeTableResponse() + .tableUri("s3://example-bucket/items.lance").storageOptions(vended)); + LanceNamespaceClient client = client(namespace, true, 60, new AtomicLong(1_000_000)); + client.resolveTableAccess("default", "items"); + client.resolveTableAccess("default", "items"); + Assertions.assertEquals(2, namespace.describes.size(), "expires_at_millis=" + expiry); + } + } + + /** Presigned, SAS and user-info URIs carry credentials even without storage options. */ + @Test + void uriThatMayCarryCredentialsIsNotCached() { + for (String uri : new String[] { + "s3://example-bucket/items.lance?X-Amz-Signature=example", + "az://container/items.lance?sig=example&se=example", + "s3://example:password@example-bucket/items.lance", + "s3://example@example_bucket/items.lance", + "s3://example-bucket/items.lance#example", + "s3://example-bucket/items lance"}) { + FakeLanceNamespace namespace = new FakeLanceNamespace().describing( + new DescribeTableResponse().tableUri(uri)); + LanceNamespaceClient client = client(namespace, true, 60, new AtomicLong(1_000_000)); + client.resolveTableAccess("default", "items"); + client.resolveTableAccess("default", "items"); + Assertions.assertEquals(2, namespace.describes.size(), uri); + } + } + + @Test + void cacheKeyIsTheFullTableIdentifier() { + FakeLanceNamespace namespace = new FakeLanceNamespace(); + LanceNamespaceClient client = new LanceNamespaceClient(namespace, false, "default", + Collections.singletonList("parent"), Collections.emptyList(), 60, () -> 0L); + client.resolveTableAccess("default", "items"); + client.resolveTableAccess("sales", "items"); + client.resolveTableAccess("default", "other"); + client.resolveTableAccess("sales", "items"); + client.resolveTableAccess("default", "items"); + Assertions.assertEquals(Arrays.asList(Arrays.asList("parent", "items"), + Arrays.asList("parent", "sales", "items"), Arrays.asList("parent", "other")), describedIds(namespace)); + } + + @Test + void failedDescribeIsNotCached() { + FakeLanceNamespace namespace = new FakeLanceNamespace(); + AtomicInteger attempts = new AtomicInteger(); + namespace.describe = request -> { + if (attempts.getAndIncrement() == 0) { + throw new IllegalStateException("unavailable"); + } + return new DescribeTableResponse().tableUri("file:///warehouse/items.lance"); + }; + LanceNamespaceClient client = client(namespace, false, 60, new AtomicLong(1_000_000)); + Assertions.assertThrows(IllegalStateException.class, () -> client.resolveTableAccess("default", "items")); + client.resolveTableAccess("default", "items"); + client.resolveTableAccess("default", "items"); + Assertions.assertEquals(2, namespace.describes.size()); + } + + @Test + void invalidationMakesTheNextReadSeeAMovedTable() { + FakeLanceNamespace namespace = new FakeLanceNamespace(); + LanceNamespaceClient client = client(namespace, false, 60, new AtomicLong(1_000_000)); + Assertions.assertEquals("file:///warehouse/items.lance", + client.resolveTableAccess("default", "items").getDatasetUri()); + namespace.describing(new DescribeTableResponse().tableUri("file:///warehouse/replacement.lance")); + Assertions.assertEquals("file:///warehouse/items.lance", + client.resolveTableAccess("default", "items").getDatasetUri()); + client.invalidateTableAccessCache(); + Assertions.assertEquals("file:///warehouse/replacement.lance", + client.resolveTableAccess("default", "items").getDatasetUri()); + } + + @Test + void concurrentMissesShareOneDescribe() throws Exception { + FakeLanceNamespace namespace = new FakeLanceNamespace(); + LanceNamespaceClient client = client(namespace, false, 60, new AtomicLong(1_000_000)); + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + namespace.describe = request -> { + entered.countDown(); + await(release); + return new DescribeTableResponse().tableUri("file:///warehouse/items.lance"); + }; + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = executor.submit(() -> client.resolveTableAccess("default", "items")); + Assertions.assertTrue(entered.await(10, TimeUnit.SECONDS)); + Future second = executor.submit(() -> client.resolveTableAccess("default", "items")); + release.countDown(); + Assertions.assertSame(first.get(10, TimeUnit.SECONDS), second.get(10, TimeUnit.SECONDS)); + Assertions.assertEquals(1, namespace.describes.size()); + } finally { + release.countDown(); + shutdown(executor); + } + } + + /** + * An invalidation neither waits for a describe in flight nor lets it repopulate the cache: the in-flight read + * gets its answer, and the next read describes again. + */ + @Test + void invalidationDoesNotWaitForOrKeepADescribeInFlight() throws Exception { + FakeLanceNamespace namespace = new FakeLanceNamespace(); + LanceNamespaceClient client = client(namespace, false, 60, new AtomicLong(1_000_000)); + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + AtomicInteger attempts = new AtomicInteger(); + namespace.describe = request -> { + if (attempts.getAndIncrement() == 0) { + entered.countDown(); + await(release); + return new DescribeTableResponse().tableUri("file:///warehouse/original.lance"); + } + return new DescribeTableResponse().tableUri("file:///warehouse/replacement.lance"); + }; + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = executor.submit(() -> client.resolveTableAccess("default", "items")); + Assertions.assertTrue(entered.await(10, TimeUnit.SECONDS)); + executor.submit(client::invalidateTableAccessCache).get(10, TimeUnit.SECONDS); + release.countDown(); + Assertions.assertEquals("file:///warehouse/original.lance", + first.get(10, TimeUnit.SECONDS).getDatasetUri()); + Assertions.assertEquals("file:///warehouse/replacement.lance", + client.resolveTableAccess("default", "items").getDatasetUri()); + } finally { + release.countDown(); + shutdown(executor); + } + } + + /** A hit takes neither the namespace lock nor I/O, so a stalled namespace request does not hold it up. */ + @Test + void cacheHitDoesNotWaitForAnotherNamespaceRequest() throws Exception { + FakeLanceNamespace namespace = new FakeLanceNamespace(); + LanceNamespaceClient client = client(namespace, true, 60, new AtomicLong(1_000_000)); + LanceTableAccess cached = client.resolveTableAccess("default", "items"); + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + namespace.tableExists = request -> { + entered.countDown(); + await(release); + }; + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future exists = executor.submit(() -> client.tableExists("default", "other")); + Assertions.assertTrue(entered.await(10, TimeUnit.SECONDS)); + Assertions.assertSame(cached, + executor.submit(() -> client.resolveTableAccess("default", "items")).get(10, TimeUnit.SECONDS)); + release.countDown(); + Assertions.assertTrue(exists.get(10, TimeUnit.SECONDS)); + } finally { + release.countDown(); + shutdown(executor); + } + } + + private static Map vendedS3Credentials() { + Map options = new HashMap<>(); + options.put("aws_access_key_id", "example-access-key"); + options.put("aws_secret_access_key", "example-secret-key"); + options.put("aws_session_token", "example-token"); + return options; + } + + private static List> describedIds(FakeLanceNamespace namespace) { + List> ids = new ArrayList<>(); + namespace.describes.forEach(request -> ids.add(request.getId())); + return ids; + } + + private static LanceNamespaceClient client(FakeLanceNamespace namespace, boolean rest, int ttlSeconds, + AtomicLong millis) { + return new LanceNamespaceClient(namespace, rest, "default", Collections.emptyList(), Collections.emptyList(), + ttlSeconds, () -> TimeUnit.MILLISECONDS.toNanos(millis.get())); + } + + private static void await(CountDownLatch latch) { + try { + Assertions.assertTrue(latch.await(10, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + } + + private static void shutdown(ExecutorService executor) throws InterruptedException { + executor.shutdownNow(); + Assertions.assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); + } +} diff --git a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceTestSession.java b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceTestSession.java index 2a458f6e0fa9a9..702bf218149aad 100644 --- a/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceTestSession.java +++ b/fe/fe-connector/fe-connector-lance/src/test/java/org/apache/doris/connector/lance/LanceTestSession.java @@ -25,19 +25,29 @@ import java.util.Map; import java.util.function.Supplier; -/** A statement's session: a fixed time zone and a real statement scope that records its loads. */ +/** + * A statement's session: a fixed time zone and a real statement scope that records its loads, or, made by + * {@link #withoutStatement()}, a session with no live statement, whose scope memoizes nothing. + */ final class LanceTestSession implements ConnectorSession { private final String timeZone; + private final boolean liveStatement; private final Map memo = new HashMap<>(); private final Map sessionProperties = new HashMap<>(); private int loads; + private boolean loading; LanceTestSession() { this("UTC"); } LanceTestSession(String timeZone) { + this(timeZone, true); + } + + private LanceTestSession(String timeZone, boolean liveStatement) { this.timeZone = timeZone; + this.liveStatement = liveStatement; } /** How many times the statement scope ran a loader, which is how many metadata reads were made. */ @@ -55,16 +65,38 @@ void remember(String key, Object value) { memo.put(key, value); } + /** A session outside any statement, as the engine's offline and background calls run. */ + static LanceTestSession withoutStatement() { + return new LanceTestSession("UTC", false); + } + @Override public ConnectorStatementScope getStatementScope() { + if (!liveStatement) { + return ConnectorStatementScope.NONE; + } return new ConnectorStatementScope() { + /** + * As the engine's scope requires, a loader may not use the scope: its ConcurrentHashMap throws + * "Recursive update" when the inner key falls in the outer key's bin, so a re-entry fails here every + * time rather than now and then. + */ @Override @SuppressWarnings("unchecked") public T computeIfAbsent(String key, Supplier loader) { + if (loading) { + throw new IllegalStateException("Recursive update: a statement-scope loader used the scope for " + + key); + } Object value = memo.get(key); if (value == null) { loads++; - value = loader.get(); + loading = true; + try { + value = loader.get(); + } finally { + loading = false; + } memo.put(key, value); } return (T) value; diff --git a/regression-test/suites/external_table_p0/lance/test_lance_array_predicate_pushdown.groovy b/regression-test/suites/external_table_p0/lance/test_lance_array_predicate_pushdown.groovy index d9f9d3a151d06b..354def638bd88a 100644 --- a/regression-test/suites/external_table_p0/lance/test_lance_array_predicate_pushdown.groovy +++ b/regression-test/suites/external_table_p0/lance/test_lance_array_predicate_pushdown.groovy @@ -106,6 +106,15 @@ suite("test_lance_array_predicate_pushdown", "p0,external") { assertEquals(expectedCandidates, counter("LanceScalarIndexCandidateRows")) } assertEquals(0L, counter("LanceScalarIndexSegmentFallbacks")) + if (caseId == 0) { + // The FE side of the same scan: the statement's metadata reads of the table, + // the index metadata an indexed predicate needs included, and the split planning. + for (String line : ["Lance Metadata Metrics", "Table Scan (default.${table})", + "MetadataReadFailures: 0", "IndexMetadataReadCalls: 1", + "SplitPlanningCalls: 1", "SplitPlanningFailures: 0"]) { + assertTrue(profile.contains(line), "Missing '${line}': ${profile}") + } + } } } // NULL needle matching and ordered subsequence matching have Doris-specific semantics. diff --git a/regression-test/suites/external_table_p0/lance/test_lance_catalog_all_types.groovy b/regression-test/suites/external_table_p0/lance/test_lance_catalog_all_types.groovy index 26f67a4021ed60..848494d6ead14b 100644 --- a/regression-test/suites/external_table_p0/lance/test_lance_catalog_all_types.groovy +++ b/regression-test/suites/external_table_p0/lance/test_lance_catalog_all_types.groovy @@ -194,4 +194,22 @@ suite("test_lance_catalog_all_types", "p0,external") { exception "Lance S3 AssumeRole access is not supported yet" } + // How long a table's described URI and options are reused, in seconds; 0 describes on every read. + sql """DROP CATALOG IF EXISTS `test_lance_negative_access_cache_ttl`""" + test { + sql """ + CREATE CATALOG `test_lance_negative_access_cache_ttl` PROPERTIES ( + "type" = "lance", + "warehouse" = "s3://warehouse/lance", + "s3.endpoint" = "http://${externalEnvIp}:${minioPort}", + "s3.access_key" = "admin", + "s3.secret_key" = "password", + "s3.region" = "us-east-1", + "use_path_style" = "true", + "lance.table_access_cache_ttl_seconds" = "-1" + ) + """ + exception "Property 'lance.table_access_cache_ttl_seconds' must be non-negative" + } + }