Repository navigation
[improvement](lance) Reuse Lance metadata across queries and show its FE time in the profile - #70830
Conversation
|
run buildall |
|
/review |
There was a problem hiding this comment.
Static review of the complete Lance PR is complete. I inspected metadata/session caching and refresh lifecycle, Substrait predicate conversion and residual pruning, scalar-index discovery and split coverage, COUNT(*) and LIMIT handling, profile metrics, session-variable forwarding, plugin packaging, fixture builders, and all changed regression/unit-test paths. Two P2 findings are included inline: literal-left comparisons are not translated despite the new reversed-operand pushdown expectations, and table/database invalidation can miss a replacement catalog generation during concurrent refresh, leaving stale table access cached until TTL. No existing blocking review comments apply, and no additional user focus was provided. Validation was static inspection only; no builds or tests were executed. Convergence: true after 2 review rounds; all assigned coverage passes completed with no unresolved candidates.
Review converged after 2 round(s).
| private Optional<Expression> convertComparison(ConnectorComparison predicate) { | ||
| ResolvedField field = findField(predicate.getLeft()); | ||
| if (field == null || !LanceSubstraitSerializer.supportsType(field.field.getType()) | ||
| || !(predicate.getRight() instanceof ConnectorLiteral)) { |
There was a problem hiding this comment.
[P2] Handle literal-left comparisons in Lance pushdown. ExprToConnectorExpressionConverter preserves the SQL operand order, but convertComparison only accepts a column on the left and a literal on the right, so queries such as 10 < int64_value remain residual and fail the new regression suite's verifyFullyPushedDown reversed-operand cases. Commute the operands and invert LT/LE/GT/GE (while preserving EQ/NE/EQ_FOR_NULL), or normalize this before conversion.
There was a problem hiding this comment.
Not changing this. The engine never hands a connector a literal-left comparison: Nereids' NormalizeBinaryPredicatesRule, part of ExpressionNormalization, commutes constant op slot into slot op' constant before the plan is translated (5 > id -> id < 5), so 10 < int64_value reaches convertComparison as int64_value > 10. The reversed-operand cases this comment cites show it: test_lance_int_predicate_pushdown (WHERE 10 < <column> for each integer and float column) and test_lance_scalar_predicate_pushdown (WHERE <value> < <column>, WHERE true = bool_value) assert verifyFullyPushedDown (lancePushdownPredicate= present, no PREDICATES:), and both pass: in the External pipeline on #70827's head (TeamCity build 9133, all eight Lance suites green) and locally with this PR's plugin. Master's Iceberg and Paimon converters take only the column-op-literal form for the same reason (IcebergPredicateConverter.buildComparison, PaimonPredicateConverter.convertComparison). A comparison the converter does not take stays in Doris, so a miss would cost pushdown, never rows.
The converter came with #70827, now merged; this PR no longer changes it.
| * REFRESH TABLE / DATABASE: the next read describes its table again; the Session and its cached metadata | ||
| * stay. Opens nothing: before the first call nothing is cached. | ||
| */ | ||
| void invalidateTableAccess() { |
There was a problem hiding this comment.
[P2] Invalidate the current generation atomically with refresh. invalidateTableAccess() reads current under the monitor, unlocks, and then swaps that generation's cache. A concurrent refresh() can retire it and open G2 before the swap, so the invalidation only clears retired G1; G2 can keep a stale URI/access until its TTL expires. Keep the generation check and cache swap under the same monitor, or retry against the active generation after a race.
There was a problem hiding this comment.
Not changing this: the interleaving is real, but it cannot leave a stale access in a newer generation. refresh() opens nothing; G2 is opened by a later call's enter() under the same monitor, so it exists only after invalidateTableAccess() has read current == G1, and its LanceNamespaceClient starts with an empty access cache. Everything G2 caches is therefore described after the REFRESH TABLE / DATABASE started, which is all that refresh promises: no access described before it is served to a read that starts after it. The swap that lands on retired G1 still matters to the calls admitted to G1 before the REFRESH CATALOG, which keep G1 until they finish, by design. Holding the monitor across the swap, or retrying on the active generation, would change nothing a read can observe.
… FE time in the profile ### Background On master, `lance` catalogs are served by the `fe-connector-lance` plugin. To plan a scan, FE asks the Lance namespace (a warehouse directory or a REST server) to describe the table, which gives the dataset URI and its storage options, then opens the dataset at the statement's version and reads its schema, fragments and, for a pushed filter, its indexes; BE reads the data through lance-c. Lance keeps the manifests and index metadata it has read in a `Session`. This is the last of four PRs porting the Lance read path (apache#70680). ### What problem does this PR solve? Issue Number: close apache#70680 Related PR: apache#70827 (pushdown, the third PR; this builds on it), apache#70725 (REST catalogs and OSS, the second PR), apache#70681 (the plugin, the first PR), apache#68078, apache#68305 (the branch-4.x PRs this ports) PR Type: Enhancement Problem Summary: On master every statement describes the table again and opens each dataset with a Session of its own, so a repeated query repeats the namespace round trip and re-reads the manifest from storage, and its profile shows none of this time. 4.1.5 and 4.2 avoid both (apache#68078, apache#68305). This PR ports them: each catalog keeps one Lance Session, a described table is reused for the catalog property `lance.table_access_cache_ttl_seconds` (default 60, 0 off; vended credentials are always described again), and each Lance scan's profile gets a `Lance Metadata Metrics` entry. Most of the diff is tests. Ten identical `EXPLAIN SELECT int32_value FROM doris.predicate_pushdown WHERE int32_value = 10` on a filesystem catalog over S3, one statement each, with only the plugin swapped: | Plugin | S3 requests from FE | Per statement | | --- | --- | --- | | before (apache#70827) | 100 | 4 HEAD + 2 GET on `__manifest` (the describe), 1 LIST, 1 HEAD + 2 GET of the table's manifest | | after | 40 | 2 HEAD on `__manifest` (the existence check), 1 LIST + 1 HEAD (finding the newest version) | A query's profile: ``` Lance Metadata Metrics: Table Scan (doris.predicate_pushdown): - MetadataReadTime: 6.046ms - MetadataReadCalls: 2 - MetadataReadFailures: 0 - SplitPlanningTime: 229.875us - SplitPlanningCalls: 1 - SplitPlanningFailures: 0 - TableAccessResolveTime: 47.708us - TableAccessResolveCalls: 2 - DatasetOpenTime: 5.374ms - DatasetOpenCalls: 2 ... ``` Original authors: @zhangstar333 and @Gabriel39. ### Details - **Change map:** +2215 −147 in 27 files: production code +778 −140 (10 files), tests +1415 −7 (16 files: FE unit tests, two regression checks), build +22 (Caffeine 2.9.3 in the plugin zip, Apache-2.0, the version the other connector plugins bundle). The production code, all in the plugin, in reading order: 1. Catalog generations and the shared Session (+297 −116): `LanceCatalogClient` opens a generation (Arrow allocator, namespace, Session, namespace client) on the first call, runs each call on one generation from start to end, and retires it on `refresh()`; the last call on a retired generation releases it. `LanceConnector` routes the engine's `invalidateAll` / `invalidateDb` / `invalidateTable` to it. 2. Table-access cache (+135 −7): `LanceNamespaceClient` (Caffeine, each entry expiring a fixed time after its describe) and the property in `LanceCatalogProperties`. 3. Metadata metrics (+338 −14): `LanceMetadataMetrics`, kept per statement and table in the statement scope and published through `collectScanProfiles`; the timing in the client, `LanceIndexMetadata` and `LanceScanPlanProvider`. 4. The `lance.conf` wording (+8 −3): the Arrow limit applies per generation, and the Session's caches are not counted. - **Before and after:** | | Before | After | | --- | --- | --- | | Describing the table | every statement | once per table per TTL (default 60 s); every statement when the namespace vends credentials or the URI may carry them | | Manifest, fragment and index metadata | re-read by every statement | from the catalog's Session after the first read | | REFRESH CATALOG | nothing cached | new namespace and Session; reads in flight finish on the old ones | | REFRESH TABLE / DATABASE | nothing cached | the next read describes again; the Session is kept | | Query profile | nothing about Lance metadata | `Lance Metadata Metrics` per scanned table: `MetadataRead` and `SplitPlanning` time, calls, failures, and time and calls per stage (`TableAccessResolve`, `DatasetOpen`, `VersionResolve`, `SchemaRead`, `FragmentMetadataRead`, `FieldIdsRead`, `IndexMetadataRead`) | - **Configs and defaults:** catalog property `lance.table_access_cache_ttl_seconds`: seconds, default 60, 0 describes on every read, negative or non-integer values rejected by CREATE and ALTER CATALOG, a new value applies at once (ALTER rebuilds the connector). Same key and rules as 4.1.5 and 4.2. The Session's capacities are fixed (64 MiB of metadata, 128 MiB of index metadata), as on 4.x. - **Impact on existing users:** Catalogs upgraded from 4.1.5 or 4.2 keep their caching and their value of the key. Unlike 4.x, the profile group has one child per scan with formatted values, and Lance time is not added to `External Table Get Table Meta Time`, which master's other plugin connectors leave empty too. As on 4.x, a moved table is read at its old URI for up to the TTL unless refreshed, a dataset replaced at the same URI needs REFRESH CATALOG, and each catalog's Session may hold up to 192 MiB of native memory (twice that while a REFRESH CATALOG overlaps two generations). - **Results:** The table above, and the eight Lance regression suites on the same cluster: 9,254 S3 requests with apache#70827's plugin, 4,780 with this one (FE and BE together). No latency was measured. ### Testing - `fe-connector-lance` unit tests, locally on Mac arm64 with the JNI libraries loaded: 254 pass, none skipped (213 before). New: `LanceTableAccessCacheTest` (TTL from the describe, what is never cached, invalidation during a describe, hits without the namespace lock), `LanceCatalogClientTest` (close and refresh with a call in flight, failed opening, shared Arrow limit), `LanceSharedSessionNativeTest` (real Sessions: cache hits, newest version still found, refresh closes the Session), `LanceMetadataMetricsTest`, `LanceIndexMetadataTest`; and cases in `LanceRestCatalogTest` (describe requests counted across statements and refreshes), `LanceConnectorNativeTest` (profile counts end to end) and three more classes. 19 mutations of the new behavior each turn their target tests red. - The test session's statement scope now rejects a loader that uses the scope, as the engine's does (`Recursive update`): the cluster run caught such a loader in an earlier revision of this PR, on which 11 unit tests fail with the stricter scope. - Regression, locally on an FE and BE built from apache#70827's head with this plugin, against a host S3 substitute and the REST stub instead of MinIO: the eight `external_table_p0/lance` suites pass, with two added checks: the scan profile in `test_lance_array_predicate_pushdown` (failing against apache#70827's plugin) and a negative TTL in `test_lance_catalog_all_types`. - After apache#70827 merged, this PR's commit was replayed onto master without conflicts and with the same patch. Master's commits since apache#70827's base change none of the plugin's modules, its dependencies or the Lance suites, so the results above were not re-run on the new base. ### Notes for Reviewers - Caffeine rather than fe-connector-cache's `MetaCache`, which expires entries after their last access: apache#68305's TTL counts from the describe, so a busy table must still be described again. - REFRESH TABLE drops the whole access cache, as on 4.2: swapping it never waits for a describe in flight, invalidating one Caffeine key would. - Generations open on the first call, so a refresh builds nothing, and 4.2's slow or failed replacements cannot happen. - Metrics use the existing `collectScanProfiles`, so no SPI change. The test seams (`LanceCatalogClient.ResourceFactory`, a package-private `LanceConnector` constructor, `LanceIndexMetadata.read` over suppliers) stand in for 4.2's Mockito mocks, which connector modules do not allow. ### Release note Lance catalogs keep reusing table metadata across queries, as in 4.1 and 4.2, with `lance.table_access_cache_ttl_seconds` (default 60 seconds). In the query profile, `Lance Metadata Metrics` now has one entry per scanned table, and Lance metadata time is no longer included in `External Table Get Table Meta Time`. ### Check List (For Author) - Behavior changed: Yes (see Details) - Does this need documentation: No (the property and its refresh behavior are documented by apache/doris-website#4159) - Pre-submission status: Partially verified: the regression suites ran locally against a host S3 substitute and the REST stub, not the External pipeline's MinIO; the native unit tests ran on Mac arm64 only ### AI Disclosure - Tool: Claude Code (Claude Opus 5.5) - Generated: the code, the tests and this description - Human review: The author reviewed part of the changes. - Prompts: Open a new branch on apache#70827's branch and continue with the next task of the Lance port (4.2's session cache, table-access cache and metadata profile), and open the PR once development is done. After apache#70827 merged: rebase this PR, fix what the review comments need, and answer the rest. Co-authored-by: zhangstar333 <zhangsida@selectdb.com> Co-authored-by: Gabriel <liwenqiang@selectdb.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5beb493 to
0866676
Compare
|
run buildall |
|
/review |
There was a problem hiding this comment.
Static review of the complete 27-file diff converged in round 2. The change's goal is to reuse Lance table access and native metadata resources while adding refresh lifecycle handling and scan metadata metrics. I verified two new blocking issues: REFRESH TABLE/DATABASE leaves the generation Session's URI/version caches warm across same-URI table replacement, and repeated REFRESH CATALOG/new-call cycles can retain an unbounded number of retired generations and native Session cache capacity while calls drain. The vended-credential concern was independently challenged and dismissed for this head because changed FE calls are metadata-only and the relevant Lance cache/object-store keys distinguish fresh options; it remains useful hardening coverage. Metrics/profile publication, pinned-version/index fallback, FE/BE scan parameters, packaging, typed property replay, security surface, and template/config checks had no additional substantiated findings. No user-provided review focus was supplied. Existing P2 threads 4651002518 and 4651002597 were read and not duplicated; neither is an existing P0/P1 finding. Review was static inspection only: no builds or tests were executed.
Review converged after 2 round(s).
| .setStorageOptions(access.getStorageOptions()) | ||
| .setIndexCacheSizeBytes(0) | ||
| .setMetadataCacheSizeBytes(METADATA_CACHE_SIZE_BYTES); | ||
| .setSession(generation.session); |
There was a problem hiding this comment.
[P1] Invalidate the Lance Session caches when refreshing a table/database. invalidateTableAccess() swaps only the namespace access cache while the generation Session remains warm, and every Dataset.open() reuses that Session. Lance's URI-scoped metadata/index caches retain version-keyed entries; if a table is dropped/recreated or replaced at the same URI and its version restarts, a REFRESH TABLE/DATABASE can reopen the new URI but serve cached state from the previous incarnation. FE refresh/replay uses these methods, while only REFRESH CATALOG creates a cold Session. Retire/reset the affected Session (or otherwise partition/clear its caches) on table/database invalidation and add a same-URI replacement test.
There was a problem hiding this comment.
Not changing what REFRESH TABLE / DATABASE do; b121338 corrects the comment and adds the test. The stale window is narrower than this says. Manifests, schemas and fragment lists are cached by version plus the manifest's e-tag, and opening the newest version always resolves a fresh location, so after a same-URI rewrite a REFRESH TABLE reads them right (probed with the bundled lance-core 12.0.0). Only a pinned version's index list can go stale, and only with V1 manifest names (_versions/<n>.manifest): Lance keys it with e_tag.unwrap_or(""), and a pinned V1 open has no e-tag. Keeping the Session on REFRESH TABLE / DATABASE is 4.2's design (only REFRESH CATALOG rotates it), the PR description names REFRESH CATALOG for a dataset replaced at the same URI, and rotating on every REFRESH TABLE would drop the cached metadata of every table in the catalog. The invalidateDb javadoc's "versions are immutable" missed this case and now says so; LanceSharedSessionNativeTest.catalogRefreshReadsTheIndexesOfADatasetWrittenAgainAtTheSameUri reads [id_idx] instead of [] when REFRESH CATALOG drops only the access cache.
There was a problem hiding this comment.
I followed the stale index through the BE reader using the new test's V1 dataset. After recreating the same URI at version 2 without the index, I called invalidateTable and planned WHERE id = 101 in a fresh statement. The FE range still contained the deleted index's segment UUID for fragment 0. Passing that range to lance-c failed with scalar index segment … is absent from the dataset snapshot. The missing-UUID check runs before fallback. After invalidateAll, FE planned the same fragment without the UUID and the scanner returned the expected one row.
This makes an ordinary filtered query fail after an explicit table refresh. Could table/database invalidation also invalidate the affected native index metadata, or use a fresh Session for the affected table's pinned index lookup? The existing fixture could assert that the next filtered scan succeeds after invalidateTable as well. lance-c segment validation
| * last of them releases it. | ||
| */ | ||
| void refresh() { | ||
| Generation idle = retireCurrent(); |
There was a problem hiding this comment.
[P2] Bound overlapping retired generations during REFRESH CATALOG. refresh() detaches the current generation and relies on its in-flight calls to drain before closing it, but a new call can open G2 while G1 is still blocked and the next refresh can retire G2 as well. Each generation allocates up to 192 MiB of native Session caches outside the Arrow limit, with no cap, so repeated refresh/new-call cycles can retain one cache set per slow call until they finish and exhaust FE native memory. Coalesce or bound retired generations, or otherwise prevent unbounded Session allocation.
There was a problem hiding this comment.
Not changing this; b121338 corrects the "two generations" wording in lance.conf.template and LanceConf. The 192 MiB are capacities that fill on demand, not allocations: a new Session with them reports sizeBytes() = 152. A retired generation lives only while a call admitted before the refresh still runs on it, and its last call releases it, so the retired generations alive at once never outnumber the catalog's calls in flight; and since generations open on the first call, a REFRESH CATALOG with no call since the previous one retires nothing. 4.2 uses the same model and even builds a replacement on every refresh. A bound would make a refresh or a new call wait for old calls to drain, which 4.2 avoids by design (a refresh never waits for reads in flight), and closing a retired Session early is unsafe under a running JNI call; the 12.0.0 Java Session cannot be shrunk while in use either.
…e same URI ### Background Each Lance catalog keeps one Lance `Session` per generation of its resources, and every FE metadata read opens its dataset with it, so a later statement reads manifests and index metadata from memory. REFRESH CATALOG retires the generation, and the next read opens a new one with a cold Session; REFRESH TABLE and REFRESH DATABASE only make the next read describe the table again and keep the Session, as on branch-4.2. The previous commit of this PR added both. ### What problem does this PR solve? Issue Number: apache#70680 Related PR: apache#68078 (the branch-4.2 shared Session that this PR ports, with the same REFRESH semantics) PR Type: Test Problem Summary: This commit answers two findings from the review of this PR. The javadoc of `invalidateDb` justified keeping the Session with "Lance versions are immutable", which fails for a dataset deleted and written again at the same URI: its versions start over, and with V1 manifest names (`_versions/<n>.manifest`) Lance keys a version's index list by the version alone, so the kept Session serves the deleted dataset's indexes. The javadoc now says so and points to REFRESH CATALOG, which the PR description already names for this case, and a native test shows REFRESH CATALOG reading the new dataset's indexes. `lance.conf.template` and `LanceConf` also said that a REFRESH CATALOG overlaps two generations, while every older generation still serving a read stays until that read ends; they now say that. ### Details - **Scenarios:** A dataset at a fixed path gets a BTREE index at version 2, and FE plans a read of that version, which caches its index list. The directory is deleted and a new dataset is written at the same path: version 1 with other rows, version 2 a config change and no index. After REFRESH CATALOG (`LanceConnector.invalidateAll`), the newest version is 2 again and its index list is empty. The test also asserts that the dataset has V1 manifest names, the only ones whose index list Lance caches without an e-tag when FE opens a pinned version. - **What existing tests miss:** The native Session tests read one copied dataset and never write a dataset again at the same path. - **Fails when broken:** With REFRESH CATALOG dropping only the table-access cache, or with `refresh()` retiring nothing, the test reads `[id_idx]` instead of `[]`. ### Testing - `fe-connector-lance` unit tests in an export of this branch, locally on Mac arm64 with the JNI libraries loaded: 255 pass, none skipped, 0 Checkstyle violations (254 on the previous commit, same environment). - The two mutations above, run against `LanceSharedSessionNativeTest` and `LanceConnectorTest`: each fails the new test on its index assertion (`expected: <[]> but was: <[id_idx]>`), and `LanceConnectorTest.onlyCatalogRefreshReplacesTheGeneration` as well. ### Release note None ### Check List (For Author) - Behavior changed: No - Does this need documentation: No - Pre-submission status: Partially verified: the native test ran on Mac arm64 only ### AI Disclosure - Tool: Claude Code (Claude Opus 5.5) - Generated: the test, the comment changes and this description - Human review: not stated Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
run buildall |
|
/review |
There was a problem hiding this comment.
Static review of the complete 27-file Lance diff at head b121338 is complete. The change's goal is to reuse Lance table access and native metadata resources and expose FE metadata timing. The generation/session lifecycle, refresh interleavings, allocator cleanup, table-access TTL/credential handling, FE/BE option propagation, statement-scope keys, synchronous/batch/streaming profile finalization, and package/config paths were inspected. One new P2 regression is reported inline: null-session metadata-only COUNT planning still computes ranges but now fails in the new profile-publication finally block. The existing P1 same-URI replacement and pinned V1 index-cache issue (4661513530) still applies to REFRESH TABLE/DATABASE and is carried by ID without a duplicate comment. Existing P2 threads 4661513665, 4651002597, and 4651002518 were read, independently dispositioned, and not duplicated. No additional user-provided review focus was supplied. No thrift/proto or cross-version protocol changes are present. Validation was static inspection only; no builds or tests were executed. Review converged after 2 rounds: all assigned reviewers returned NO_NEW_VALUABLE_FINDINGS in round 2, and no new candidate remains unresolved.
Review converged after 2 round(s).
Existing P0/P1 findings confirmed for this head: #70830 (comment)
| this.backendStorageProperties = backendStorageProperties; | ||
| } | ||
|
|
||
| /** |
There was a problem hiding this comment.
[P2] Keep null-session count planning offline-safe. When planScan receives a null session and the request is metadata-only COUNT with no filter, the new finally calls publishScan, whose pendingProfiles dereferences session.getCatalogId()/getQueryId() after the ranges have already been computed. This changes the pre-change null-session result into an NPE; ConnectorStatementScopes explicitly supports null offline sessions and other connector tests invoke planScan(null, ...). Skip profile publication/collection when the session is null and add a regression test.
There was a problem hiding this comment.
Not changing this. A null session never reaches planScan: its only engine caller, PluginDrivenScanNode.getSplits, dereferences the session in its first statement (registerQueryFinishCleanup(connectorSession) reads getQueryId()), the session comes from PluginDrivenExternalCatalog.buildConnectorSession(), which always builds one, and the SPI documents the parameter as "the current session". Paimon's and Iceberg's null guards say the same ("production planScan always carries one"), and no Lance test calls planScan with a null session. Nor was Lance's planScan null-safe before this PR: only the COUNT branch without a filter left the session alone, and every other request dereferenced it in fragmentsPerSplit (LanceScanPlanProvider.java:205 at 3b476bd). The offline case the metrics are built for is a session without a live statement (ConnectorStatementScope.NONE), where publishScan and collectScanProfiles publish nothing; LanceMetadataMetricsTest.readsOutsideAStatementRunAndReportNothing covers it. A null check here would guard an input nothing produces, which the repository's AGENTS.md rules out.
| private static Dataset openDataset(Generation generation, BufferAllocator readAllocator, | ||
| LanceTableAccess access, OptionalLong version, LanceMetadataMetrics.Timer timer) { | ||
| ReadOptions.Builder options = new ReadOptions.Builder() | ||
| .setStorageOptions(access.getStorageOptions()) |
There was a problem hiding this comment.
[P2] Can we skip the catalog-wide Session for accesses with vended storage options? A REST namespace can return a fresh session token on each describe. The zero TTL handles the Java cache, but every open here still uses the same native Session. Lance 12's object-store registry keys entries by the full options, holds the keys strongly, and only removes an expired weak store on lookup of that same key. A rotated token leaves its old options in native memory until the catalog Session closes. The 64/128 MiB cache limits do not cover this registry.
I checked with lance-core 12.0.0 on macOS, opening the same local dataset and closing it after every read. With 48 reads using one synthetic token, the number of live native allocations in the token's size class stayed flat. With 48 distinct tokens it grew by 96, then fell back after closing the Session. Carrying the vended-options flag from describe to open would let these reads use a dataset-owned Session while ordinary reads keep the shared cache. Lance registry lookup and insertion
…ed reads out of it ### Background Each Lance catalog keeps its FE resources in a generation: the namespace, an Arrow allocator, the cache of described table accesses, and one Lance `Session` that every FE metadata read opens its dataset with, so a later statement reads manifests and index metadata from memory. apache#70830 added the generation and the shared Session (ported from branch-4.2 apache#68078 and apache#68305). REFRESH CATALOG replaced the generation; REFRESH TABLE and REFRESH DATABASE only dropped the cached table accesses and kept the Session. ### What problem does this PR solve? Issue Number: apache#70680 Related PR: apache#70830 (added the shared Session; a code owner found both problems in its review), apache#68078 (branch-4.2's shared Session, which has both) PR Type: Bugfix Problem Summary: REFRESH TABLE and REFRESH DATABASE kept the Session. For a dataset deleted and written again at the same URI with V1 manifest names, the Session serves the deleted dataset's index list. A filtered scan of the new dataset is then planned over index segments it does not have, and the BE fails the query with `scalar index segment ... is absent from the dataset snapshot`; only REFRESH CATALOG recovered. Every REFRESH now starts a new generation. Separately, a REST namespace may vend a new token on every describe. The shared Session keeps an object store for every distinct set of storage options and drops an unused one only when the same options are looked up again, so every token stayed in native memory until the generation was retired, outside the Session's 64 MiB and 128 MiB capacities. A table described with vended options is now opened with a Session of its own, as master did before apache#70830. ### Details - **Frequency:** The first needs a dataset deleted and written again at the same URI with V1 manifest names (older writers, or the Java `Fragment.create` plus `FragmentOperation.Overwrite` commit path), and a version that had an index before and has none now; every filtered query on that version fails until REFRESH CATALOG. The second needs a REST namespace that vends a different token on every describe; FE native memory then grows with every read of such a table. - **Root cause:** Lance 12 keys a version's index list by URI, version and manifest e-tag, and a pinned open of a V1-named dataset has no e-tag, so the deleted dataset's entry matches the new one. The Java `Session` of lance-core 12.0.0 cannot drop the entries of one URI. A Session's object-store registry is keyed by the full storage options and prunes a dead entry only when the same key is looked up again (`rust/lance-io/src/object_store/providers.rs` at Lance v12.0.0). - **Why existing tests missed it:** The native test of the same-URI rewrite asserted recovery after REFRESH CATALOG only, and the shared-Session tests read with storage options that never change. - **Fix:** `invalidateTable` and `invalidateDb` retire the generation as `invalidateAll` does, and the invalidation that dropped only the cached table accesses is removed. A described access records whether the namespace vended options, the same condition the access cache already used to skip caching. Such a read opens its dataset with a Session of its own: a 64 MiB metadata cache and no index cache, as before apache#70830. - **Other paths and branches:** branch-4.2 has both problems: its query reads use the shared Session, and REFRESH TABLE keeps it. The engine also calls `invalidateTable` or `invalidateDb` when a lookup finds a known table gone, and that now starts a new generation too. ### Testing - `fe-connector-lance` unit tests, run locally on Mac arm64 with the JNI libraries loaded: 257 pass, none skipped, 0 Checkstyle violations. - `LanceSharedSessionNativeTest.everyRefreshReadsTheIndexesOfADatasetWrittenAgainAtTheSameUri` now runs for REFRESH TABLE, DATABASE and CATALOG. `readsWithVendedOptionsKeepOutOfTheSharedSession` reads 8 times, with a new token each time, and asserts that the shared Session's metadata cache saw none of them; a read without vended options still hits it. - Mutations, each run against its test classes (the unmutated run passes all of them): REFRESH TABLE and DATABASE dropping only the described accesses again fails the same-URI test for TABLE and DATABASE (`expected: <[]> but was: <[id_idx]>`) and both generation tests, while CATALOG still passes; opening vended reads with the shared Session fails the vended test (the shared cache saw all 8 reads), and so does never recording the vended flag, which also fails the two access-cache tests of vended credentials. ### Release note None (changes behavior that apache#70830 added and no release has shipped) ### Check List (For Author) - Behavior changed: Yes (REFRESH TABLE and REFRESH DATABASE on a Lance catalog also start a new Lance Session; reads with vended options do not use the shared Session) - Does this need documentation: Yes, apache/doris-website#4159 documents the refresh behavior of apache#70830 and needs the same change - Pre-submission status: Partially verified: the native tests ran on Mac arm64 only; the BE failure is the reviewer's report and was not reproduced here ### AI Disclosure - Tool: Claude Code (Claude Opus 5.5) - Generated: the code, the tests and this description - Human review: not stated Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…le format SPI
### Background
A Lance dataset is a directory of versioned manifests that list its fragments (data files) and indexes. branch-4.1 (since 4.1.4) and branch-4.2 read one with `s3("uri" = ..., "format" = "lance")`: the FE opens the dataset, pins its newest version and plans one range per fragment. On master, Lance lives in the `fe-connector-lance` plugin, which serves Lance catalogs (apache#70681, apache#70725, apache#70827). The file table functions (`s3()`, `file()`, `hdfs()`, ...) read only the formats of a closed list in fe-core: the FE lists the files and the BE's file readers read them.
### What problem does this PR solve?
Issue Number: apache#70680
Related PR: apache#70830 (builds on it), apache#70827 (the pushdown this scan reuses), apache#65730, apache#66805, apache#67325, apache#67921, apache#68078 (the branch-4.x implementation this ports)
PR Type: Feature
Problem Summary:
Users who read Lance datasets with `s3()` on 4.1.4 and 4.2 get an error on master, because fe-core no longer knows the format. This PR lets a connector plugin serve a format to the file table functions: `s3()`, and `file()` over S3-compatible storage, hand the dataset's location and storage to the plugin, which pins the newest version, gives the columns, and plans the scan through the scan node of catalog tables, pushdown included. The Lance plugin serves `lance`. Half of the diff is tests. The branch also carries three review fixes for the Lance plugin, each in its own commit. Other formats and table functions are unchanged.
```sql
SELECT count(*), sum(row_id) FROM s3(
"uri" = "s3://warehouse/lance/all_types.lance", "s3.endpoint" = "http://127.0.0.1:19001",
"s3.access_key" = "<ak>", "s3.secret_key" = "<sk>", "s3.region" = "us-east-1",
"use_path_style" = "true", "format" = "lance");
```
| FE | Result |
|---|---|
| master before this PR | `ERROR 1105 (HY000): errCode = 2, detailMessage = Can not build s3(): format:lance is not supported.` |
| this PR | `12 78` |
### Details
- **Change map:** The feature commit is +2043 −69 in 37 files, more than half of it tests: unit tests +613, two regression suites with a fixture builder +341, their generated `.out` +116, and a 5 KB Lance fixture copied from branch-4.2. The production code is +967 −63, in three parts, in reading order:
1. The SPI (+150 −1): `ConnectorProvider#getFileFormats` and `#createFileFormatConnector`, `ConnectorFileSource`, `ConnectorFileSourceOps`; connector plugin API 35.0 -> 36.0 with its surface baseline.
2. fe-core (+310 −12): format claims and one connector per format (`ConnectorPluginManager`, `PluginFileFormat`); `ExternalFileTableValuedFunction` and `S3TableValuedFunction` hand the location to the plugin and scan with `PluginDrivenScanNode`; two small `PluginDrivenScanNode` fixes for a table that belongs to no catalog (Notes for Reviewers).
3. The Lance plugin (+508 −51): `LanceFileFormatConnector`, `LanceFileMetadata`, `LanceFileTableHandle`, and `LanceScanPlanProvider` split by where the metadata comes from (`CatalogSource`, the old behavior; `FileSource`, the new one).
The two commits before it hold the carried review fixes (+248 −194).
- **Scope:** `s3()`, and `file()` over S3-compatible storage. The uri is the dataset root: nothing is listed and no glob applies. The statement reads the version that is newest when it is analyzed. `DESC FUNCTION` shows the columns as a Lance catalog does. Predicates, LIMIT and `COUNT(*)` are pushed as for a catalog table; the 4.x table function pushed none. Read only: `INSERT INTO s3(...)`, `OUTFILE ... FORMAT AS lance` and routine load still fail with `format:lance is not supported.`. `hdfs()` and `http()` refuse the format, as on 4.x, and so do `path_partition_keys` and a streaming job's file list. `local()` is out: master disables it for every format (apache#69591).
- **Design:** A plugin declares its formats (`ConnectorProvider#getFileFormats()`) and builds, for each, a connector that belongs to no catalog (`createFileFormatConnector`). Its metadata implements `ConnectorFileSourceOps#getFileTableHandle(session, ConnectorFileSource)`, which resolves the location and storage to a table handle and pins the version; from there the engine uses the existing interfaces, as the `query()` table function does: `getTableSchema` for the columns, `PluginDrivenScanNode` for the scan. fe-core claims format names when it admits a plugin: case-insensitive, one plugin per name, and the formats the engine reads itself are reserved. A format's connector is built on first use, kept for the life of the FE, and given a negative catalog id, which no catalog has, so its per-statement state stays apart. Rejected: a narrow `TVFScanNode` interface returning a schema and splits, which would duplicate the plugin scan node's range and storage plumbing and lose the pushdown. Not discussed publicly; apache#70680 lists this as a follow-up.
- **Usage:**
```sql
DESC FUNCTION s3("uri" = "s3://bucket/path/data.lance", "s3.endpoint" = "...",
"s3.access_key" = "...", "s3.secret_key" = "...", "s3.region" = "...", "format" = "lance");
SELECT row_id FROM file("uri" = "s3://bucket/path/data.lance", "s3.endpoint" = "...",
"s3.access_key" = "...", "s3.secret_key" = "...", "s3.region" = "...", "format" = "lance")
WHERE int64_col > 0;
```
EXPLAIN of the second statement:
```
TABLE: null.null.S3TableValuedFunction
CONNECTOR: lance
lanceCatalogType=tvf
lanceVersion=1
lanceFragments=1
lancePushdownPredicate=(int64_col > 0)
```
- **Default behavior:** Available whenever the Lance plugin is installed, as the FE package does by default.
- **Compatibility:** FE only: the ranges carry the same `TLanceFileDesc` and `TLanceScanParams` as a catalog scan, so neither the BE nor thrift changes. A column of the types the BE reader added in 4.2 keeps a smooth-upgrade source BE out of the scan, as for a catalog table. Plugins built for API 35.0 are refused by the version gate, as after every SPI change. Nothing is persisted.
- **Security and privileges:** The FE reads the dataset's manifest and fragment list at the endpoint the user names, with the user's credentials: the request `s3()` already makes to list files, behind the same gate, which runs before the plugin opens anything (`s3_load_endpoint_white_list`, and the SSRF check when `security_checker_class_name` is set). The privilege is that of `s3()`: none beyond running the query, USAGE when a `resource` is named. Credentials stay out of EXPLAIN, the handle's `toString` and error messages.
- **Carried review fixes:**
1. REFRESH TABLE and REFRESH DATABASE also start a new Lance Session (`535b9085a51`, [apache#70830 r4661513530](apache#70830 (comment))). A dataset deleted and written again at the same URI with V1 manifest names kept a stale index list after REFRESH TABLE, and the BE refused filtered scans (`scalar index segment ... is absent from the dataset snapshot`); lance-core 12's Java `Session` cannot drop one URI's entries. Cost: REFRESH TABLE drops the catalog's cached Lance metadata, where branch-4.x rotates the Session only on REFRESH CATALOG.
2. Reads with namespace-vended storage options use a Session of their own (`535b9085a51`, [apache#70830 r4665616715](apache#70830 (comment))): a namespace vending a new token per describe grew the shared Session's object-store registry without bound.
3. `planScan` no longer serializes the pushed Substrait filter (`ec723b4f2e5`, [apache#70827 r4656423962](apache#70827 (comment))): the conversion is lazy.
- **Follow-up plan:** The Lance search table functions, index DDL and inspection, and tag and branch versioning follow in their own PRs (apache#70680).
### Testing
- fe-core: the new `PluginFileFormatTableValuedFunctionTest` (8 cases) drives `s3()`, `file()`, `hdfs()` and `http()` against a mocked plugin: the endpoint gate runs first and a refused endpoint never reaches the plugin, nothing is listed, the plugin gets the normalized location and storage, the columns are its own, the scan and its EXPLAIN go through `PluginDrivenScanNode`, a predicate reaches the plugin while the statement holds an internal table's plan read lock, and the refusals hold. `ConnectorPluginManagerTest` covers the claims. With the other table function tests, the `PluginDrivenScanNode*Test` family and `PluginDrivenMissingTableTest`, 479 fe-core tests in 45 classes pass.
- `fe-connector-spi`: its 166 tests, with the new surface baseline and API 36.0.
- Lance plugin: 264 tests, none skipped (macOS arm64, lance-core 12.0.0 JNI), among them `LanceFileFormatNativeTest`: the pinned version holds after a newer commit, the table function's storage goes into the scan and stays out of EXPLAIN, filter and `COUNT(*)` are pushed, the added types raise the upgrade fence, a missing dataset fails with a message.
- Mutations, run before the rebase: 13 targeted mutations of the feature commit fail their tests, among them the old EXPLAIN code (`NullPointerException`), the unguarded cast (`FunctionGenTable cannot be cast to class PluginDrivenExternalTable`), the endpoint gate skipped, an engine format claimable, and the version pin dropped.
- Regression, locally and before the rebase: the 10 `external_table_p0/lance` suites, the two new ones included, pass on an FE built from this branch and a BE built from apache#70827's head, against a host S3 stand-in and the REST stub instead of MinIO. The 7 result blocks ported from branch-4.2's `.out` are identical; the new blocks (EXPLAIN, pushdown, `COUNT(*)` over three fragments with deletions, `file()`, `INSERT ... SELECT` into an OLAP table, a join with one, the refusals) match what pylance 7.0.0 reads from the same fixtures.
- Carried fixes: their tests are in the plugin run above, and one mutation per changed behavior, run before the rebase, fails each.
- After apache#70830 merged, the three commits were replayed onto master without conflicts and with unchanged patches (`git range-diff` all `=`). The new base changes no file of the plugin, the SPI, the Lance suites or their fixtures; on this path it changes only the generic pipeline-task and TLS code. The unit tests above ran on the rebased branch; the mutations and the regression suites did not run again.
### Notes for Reviewers
- Review commit by commit: the first two are the carried review fixes, the third is the feature.
- `PluginDrivenScanNode` assumed a catalog table in two places that a table function's table (no database, no catalog) broke: EXPLAIN read `getDatabase().getCatalog()`, and `convertPredicate` cast the table to `PluginDrivenExternalTable` whenever the statement also held an internal table (a join, or `INSERT INTO olap_table SELECT ...`).
- `ConnectorFileSource` hands over no other table function properties: they cannot be told apart from storage keys reliably, and passing them would copy the credentials again.
- A format's connector holds nothing to close: every read opens and closes its own Arrow allocator and Lance Session, so one table function's credentials never reach a cache another reads. The statement memo, keyed by URI and version, only spares the scan a second read; every table function resolves its handle with its own storage.
### Release note
`s3()`, and `file()` over S3-compatible storage, read Lance datasets with `"format" = "lance"` as on 4.1 and 4.2, and now push predicates, LIMIT and `COUNT(*)` into the scan.
### Check List (For Author)
- Behavior changed: No
- Does this need documentation: Yes (the `s3()` and `file()` pages need `"format" = "lance"` for releases built from master; a doris-website PR follows)
- Pre-submission status: Partially verified: the regression suites ran before the rebase, on macOS against a local S3 stand-in instead of the MinIO container, with a BE built from apache#70827's head (this PR changes no BE code); the External pipeline runs them in docker
### AI Disclosure
- Tool: Claude Code (Claude Opus 5.5)
- Generated: the code, the tests and this description
- Human review: not stated
- Prompts:
1. Port branch-4.x's `"format" = "lance"` file table function to master as the next Lance task, on a branch stacked on apache#70830.
2. Fix in the same PR the two round-4 review findings on apache#70830 and r4656423962 on apache#70827.
3. The design as approved: plugins declare formats and build a catalog-less connector; only `s3()` and `file()` over S3 hand over a data set; keep the pushdown the catalog scan already has.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…le format SPI (#70903) ### Background A Lance dataset is a directory of versioned manifests that list its fragments (data files) and indexes. branch-4.1 (since 4.1.4) and branch-4.2 read one with `s3("uri" = ..., "format" = "lance")`: the FE opens the dataset, pins its newest version and plans one range per fragment. On master, Lance lives in the `fe-connector-lance` plugin, which serves Lance catalogs (#70681, #70725, #70827). The file table functions (`s3()`, `file()`, `hdfs()`, ...) read only the formats of a closed list in fe-core: the FE lists the files and the BE's file readers read them. ### What problem does this PR solve? Issue Number: #70680 Related PR: #70830 (builds on it), #70827 (the pushdown this scan reuses), #65730, #66805, #67325, #67921, #68078 (the branch-4.x implementation this ports) PR Type: Feature Problem Summary: Users who read Lance datasets with `s3()` on 4.1.4 and 4.2 get an error on master, because fe-core no longer knows the format. This PR lets a connector plugin serve a format to the file table functions: `s3()`, and `file()` over S3-compatible storage, hand the dataset's location and storage to the plugin, which pins the newest version, gives the columns, and plans the scan through the scan node of catalog tables, pushdown included. The Lance plugin serves `lance`. Half of the diff is tests. The branch also carries three review fixes for the Lance plugin, each in its own commit. Other formats and table functions are unchanged. ```sql SELECT count(*), sum(row_id) FROM s3( "uri" = "s3://warehouse/lance/all_types.lance", "s3.endpoint" = "http://127.0.0.1:19001", "s3.access_key" = "<ak>", "s3.secret_key" = "<sk>", "s3.region" = "us-east-1", "use_path_style" = "true", "format" = "lance"); ``` | FE | Result | |---|---| | master before this PR | `ERROR 1105 (HY000): errCode = 2, detailMessage = Can not build s3(): format:lance is not supported.` | | this PR | `12 78` | ### Details - **Change map:** The feature commit is +2043 −69 in 37 files, more than half of it tests: unit tests +613, two regression suites with a fixture builder +341, their generated `.out` +116, and a 5 KB Lance fixture copied from branch-4.2. The production code is +967 −63, in three parts, in reading order: 1. The SPI (+150 −1): `ConnectorProvider#getFileFormats` and `#createFileFormatConnector`, `ConnectorFileSource`, `ConnectorFileSourceOps`; connector plugin API 35.0 -> 36.0 with its surface baseline. 2. fe-core (+310 −12): format claims and one connector per format (`ConnectorPluginManager`, `PluginFileFormat`); `ExternalFileTableValuedFunction` and `S3TableValuedFunction` hand the location to the plugin and scan with `PluginDrivenScanNode`; two small `PluginDrivenScanNode` fixes for a table that belongs to no catalog (Notes for Reviewers). 3. The Lance plugin (+508 −51): `LanceFileFormatConnector`, `LanceFileMetadata`, `LanceFileTableHandle`, and `LanceScanPlanProvider` split by where the metadata comes from (`CatalogSource`, the old behavior; `FileSource`, the new one). The two commits before it hold the carried review fixes (+248 −194); the two after it fix this PR's first two reviews (+105 −13 and +60 −10). - **Scope:** `s3()`, and `file()` over S3-compatible storage. The uri is the dataset root: nothing is listed and no glob applies. The statement reads the version that is newest when it is analyzed. `DESC FUNCTION` shows the columns as a Lance catalog does. Predicates, LIMIT and `COUNT(*)` are pushed as for a catalog table; the 4.x table function pushed none. Read only: `INSERT INTO s3(...)`, `OUTFILE ... FORMAT AS lance` and routine load still fail with `format:lance is not supported.`. `hdfs()` and `http()` refuse the format, as on 4.x, and so do `path_partition_keys` and a streaming job's file list. `local()` is out: master disables it for every format (#69591). - **Design:** A plugin declares its formats (`ConnectorProvider#getFileFormats()`) and builds, for each, a connector that belongs to no catalog (`createFileFormatConnector`). Its metadata implements `ConnectorFileSourceOps#getFileTableHandle(session, ConnectorFileSource)`, which resolves the location and storage to a table handle and pins the version; from there the engine uses the existing interfaces, as the `query()` table function does: `getTableSchema` for the columns, `PluginDrivenScanNode` for the scan. fe-core claims format names when it admits a plugin: case-insensitive, one plugin per name, and the formats the engine reads itself are reserved. A format's connector is built on first use, kept for the life of the FE, and given a negative catalog id, which no catalog has, so its per-statement state stays apart. Rejected: a narrow `TVFScanNode` interface returning a schema and splits, which would duplicate the plugin scan node's range and storage plumbing and lose the pushdown. Not discussed publicly; #70680 lists this as a follow-up. - **Usage:** ```sql DESC FUNCTION s3("uri" = "s3://bucket/path/data.lance", "s3.endpoint" = "...", "s3.access_key" = "...", "s3.secret_key" = "...", "s3.region" = "...", "format" = "lance"); SELECT row_id FROM file("uri" = "s3://bucket/path/data.lance", "s3.endpoint" = "...", "s3.access_key" = "...", "s3.secret_key" = "...", "s3.region" = "...", "format" = "lance") WHERE int64_col > 0; ``` EXPLAIN of the second statement: ``` TABLE: null.null.S3TableValuedFunction CONNECTOR: lance lanceCatalogType=tvf lanceVersion=1 lanceFragments=1 lancePushdownPredicate=(int64_col > 0) ``` - **Default behavior:** Available whenever the Lance plugin is installed, as the FE package does by default. - **Compatibility:** FE only: the ranges carry the same `TLanceFileDesc` and `TLanceScanParams` as a catalog scan, so neither the BE nor thrift changes. A column of the types the BE reader added in 4.2 keeps a smooth-upgrade source BE out of the scan, as for a catalog table. Plugins built for API 35.0 are refused by the version gate, as after every SPI change. Nothing is persisted. - **Security and privileges:** The FE reads the dataset's manifest and fragment list at the endpoint the user names, with the user's credentials: the request `s3()` already makes to list files, behind the same gate, which runs before the plugin opens anything (`s3_load_endpoint_white_list`, and the SSRF check when `security_checker_class_name` is set). The privilege is that of `s3()`: none beyond running the query, USAGE when a `resource` is named. Credentials stay out of EXPLAIN, the handle's `toString` and error messages. - **Carried review fixes:** 1. REFRESH TABLE and REFRESH DATABASE also start a new Lance Session (`535b9085a51`, [#70830 r4661513530](#70830 (comment))). A dataset deleted and written again at the same URI with V1 manifest names kept a stale index list after REFRESH TABLE, and the BE refused filtered scans (`scalar index segment ... is absent from the dataset snapshot`); lance-core 12's Java `Session` cannot drop one URI's entries. Cost: REFRESH TABLE drops the catalog's cached Lance metadata, where branch-4.x rotates the Session only on REFRESH CATALOG. 2. Reads with namespace-vended storage options use a Session of their own (`535b9085a51`, [#70830 r4665616715](#70830 (comment))): a namespace vending a new token per describe grew the shared Session's object-store registry without bound. 3. `planScan` no longer serializes the pushed Substrait filter (`ec723b4f2e5`, [#70827 r4656423962](#70827 (comment))): the conversion is lazy. - **Follow-up plan:** The Lance search table functions, index DDL and inspection, and tag and branch versioning follow in their own PRs (#70680). ### Testing - fe-core: the new `PluginFileFormatTableValuedFunctionTest` (8 cases) drives `s3()`, `file()`, `hdfs()` and `http()` against a mocked plugin: the endpoint gate runs first and a refused endpoint never reaches the plugin, nothing is listed, the plugin gets the normalized location and storage, the columns are its own, the scan and its EXPLAIN go through `PluginDrivenScanNode`, a predicate reaches the plugin while the statement holds an internal table's plan read lock, and the refusals hold. `ConnectorPluginManagerTest` covers the claims. With the other table function tests, the `PluginDrivenScanNode*Test` family and `PluginDrivenMissingTableTest`, 479 fe-core tests in 45 classes pass. - `fe-connector-spi`: its 166 tests, with the new surface baseline and API 36.0. - Lance plugin: 265 tests, none skipped (macOS arm64, lance-core 12.0.0 JNI), among them `LanceFileFormatNativeTest`: the pinned version holds after a newer commit, the table function's storage goes into the scan and stays out of EXPLAIN, filter and `COUNT(*)` are pushed, the added types raise the upgrade fence, a missing dataset fails with a message. - Mutations, run before the rebase: 13 targeted mutations of the feature commit fail their tests, among them the old EXPLAIN code (`NullPointerException`), the unguarded cast (`FunctionGenTable cannot be cast to class PluginDrivenExternalTable`), the endpoint gate skipped, an engine format claimable, and the version pin dropped. - Regression, locally and before the rebase: the 10 `external_table_p0/lance` suites, the two new ones included, pass on an FE built from this branch and a BE built from #70827's head, against a host S3 stand-in and the REST stub instead of MinIO. The 7 result blocks ported from branch-4.2's `.out` are identical; the new blocks (EXPLAIN, pushdown, `COUNT(*)` over three fragments with deletions, `file()`, `INSERT ... SELECT` into an OLAP table, a join with one, the refusals) match what pylance 7.0.0 reads from the same fixtures. - Carried fixes: their tests are in the plugin run above, and one mutation per changed behavior, run before the rebase, fails each. - The fourth commit: `ConnectorPluginManagerTest.classpathProviderWhoseFileFormatsThrowIsSkippedNotFatal` and `pluginWhoseFileFormatsThrowIsSkippedNotFatal` fail on the feature commit with `Unexpected exception thrown: java.lang.IllegalStateException: the connector could not list its file formats` and pass with it; the fe-core tests above, now 481 in 45 classes, pass. - The fifth commit: `LanceScanPlanProviderTest.fileTableFunctionsOfOneUriOnTwoEndpointsCountTheirOwnDatasets` plans `COUNT(*)` for two table functions on one uri at one version with two endpoints, one dataset of 1 row and one of 2. On the fourth commit it fails with `expected: <2> but was: <1>`; with the fifth it passes, and so do the plugin's other 264 tests. - After #70830 merged, the three commits were replayed onto master without conflicts and with unchanged patches (`git range-diff` all `=`). The new base changes no file of the plugin, the SPI, the Lance suites or their fixtures; on this path it changes only the generic pipeline-task and TLS code. The unit tests above ran on the rebased branch; the mutations and the regression suites did not run again. ### Notes for Reviewers - Review commit by commit: the first two are the carried review fixes, the third is the feature, the fourth makes the plugin loaders skip a provider whose `getFileFormats()` throws instead of stopping FE startup (review comment r4668526070), and the fifth gives each table function its own entry in the statement's metadata memo (review comment r4671691836). - `PluginDrivenScanNode` assumed a catalog table in two places that a table function's table (no database, no catalog) broke: EXPLAIN read `getDatabase().getCatalog()`, and `convertPredicate` cast the table to `PluginDrivenExternalTable` whenever the statement also held an internal table (a join, or `INSERT INTO olap_table SELECT ...`). - `ConnectorFileSource` hands over no other table function properties: they cannot be told apart from storage keys reliably, and passing them would copy the credentials again. - A format's connector holds nothing to close: every read opens and closes its own Arrow allocator and Lance Session, so one table function's credentials never reach a cache another reads. The statement memo only spares a table function's scan a second read, and it is kept per resolved handle: a uri names no endpoint, so two table functions can name one uri at one version on two object stores, and every table function resolves its handle with its own storage.
Background
On master,
lancecatalogs are served by thefe-connector-lanceplugin. To plan a scan, FE asks the Lance namespace (a warehouse directory or a REST server) to describe the table, which gives the dataset URI and its storage options, then opens the dataset at the statement's version and reads its schema, fragments and, for a pushed filter, its indexes; BE reads the data through lance-c. Lance keeps the manifests and index metadata it has read in aSession.This is the last of four PRs porting the Lance read path (#70680).
What problem does this PR solve?
Issue Number: close #70680
Related PR: #70827 (pushdown, the third PR; this builds on it), #70725 (REST catalogs and OSS, the second PR), #70681 (the plugin, the first PR), #68078, #68305 (the branch-4.x PRs this ports)
PR Type: Enhancement
Problem Summary:
On master every statement describes the table again and opens each dataset with a Session of its own, so a repeated query repeats the namespace round trip and re-reads the manifest from storage, and its profile shows none of this time. 4.1.5 and 4.2 avoid both (#68078, #68305). This PR ports them: each catalog keeps one Lance Session, a described table is reused for the catalog property
lance.table_access_cache_ttl_seconds(default 60, 0 off; vended credentials are always described again), and each Lance scan's profile gets aLance Metadata Metricsentry. Most of the diff is tests.Ten identical
EXPLAIN SELECT int32_value FROM doris.predicate_pushdown WHERE int32_value = 10on a filesystem catalog over S3, one statement each, with only the plugin swapped:__manifest(the describe), 1 LIST, 1 HEAD + 2 GET of the table's manifest__manifest(the existence check), 1 LIST + 1 HEAD (finding the newest version)A query's profile:
Original authors: @zhangstar333 and @Gabriel39.
Details
Change map: +2313 −147 in 27 files: production code +784 −140 (10 files), tests +1507 −7 (16 files: FE unit tests, two regression checks), build +22 (Caffeine 2.9.3 in the plugin zip, Apache-2.0, the version the other connector plugins bundle). The production code, all in the plugin, in reading order:
LanceCatalogClientopens a generation (Arrow allocator, namespace, Session, namespace client) on the first call, runs each call on one generation from start to end, and retires it onrefresh(); the last call on a retired generation releases it.LanceConnectorroutes the engine'sinvalidateAll/invalidateDb/invalidateTableto it.LanceNamespaceClient(Caffeine, each entry expiring a fixed time after its describe) and the property inLanceCatalogProperties.LanceMetadataMetrics, kept per statement and table in the statement scope and published throughcollectScanProfiles; the timing in the client,LanceIndexMetadataandLanceScanPlanProvider.lance.confwording (+9 −3): the Arrow limit applies per generation, an older generation keeps its limit until its last read ends, and the Sessions' caches are not counted.Before and after:
Lance Metadata Metricsper scanned table:MetadataReadandSplitPlanningtime, calls, failures, and time and calls per stage (TableAccessResolve,DatasetOpen,VersionResolve,SchemaRead,FragmentMetadataRead,FieldIdsRead,IndexMetadataRead)Configs and defaults: catalog property
lance.table_access_cache_ttl_seconds: seconds, default 60, 0 describes on every read, negative or non-integer values rejected by CREATE and ALTER CATALOG, a new value applies at once (ALTER rebuilds the connector). Same key and rules as 4.1.5 and 4.2. The Session's capacities are fixed (64 MiB of metadata, 128 MiB of index metadata), as on 4.x.Impact on existing users: Catalogs upgraded from 4.1.5 or 4.2 keep their caching and their value of the key. Unlike 4.x, the profile group has one child per scan with formatted values, and Lance time is not added to
External Table Get Table Meta Time, which master's other plugin connectors leave empty too. As on 4.x, a moved table is read at its old URI for up to the TTL unless refreshed, a dataset deleted and written again at the same URI needs REFRESH CATALOG (see Notes for Reviewers), and each catalog's Session may hold up to 192 MiB of native memory, plus, after a REFRESH CATALOG, an older generation's Session until its last read ends.Results: The table above, and the eight Lance regression suites on the same cluster: 9,254 S3 requests with [feature](lance) Push predicates, LIMIT and COUNT(*) into Lance scans #70827's plugin, 4,780 with this one (FE and BE together). No latency was measured.
Testing
fe-connector-lanceunit tests, locally on Mac arm64 with the JNI libraries loaded: 255 pass, none skipped (213 before). New:LanceTableAccessCacheTest(TTL from the describe, what is never cached, invalidation during a describe, hits without the namespace lock),LanceCatalogClientTest(close and refresh with a call in flight, failed opening, shared Arrow limit),LanceSharedSessionNativeTest(real Sessions: cache hits, newest version still found, refresh closes the Session, REFRESH CATALOG reads the indexes of a dataset written again at the same URI),LanceMetadataMetricsTest,LanceIndexMetadataTest; and cases inLanceRestCatalogTest(describe requests counted across statements and refreshes),LanceConnectorNativeTest(profile counts end to end) and three more classes. 19 mutations of the new behavior each turn their target tests red, and two more (REFRESH CATALOG dropping only the access cache,refresh()retiring nothing) turn the same-URI test red.Recursive update): the cluster run caught such a loader in an earlier revision of this PR, on which 11 unit tests fail with the stricter scope.external_table_p0/lancesuites pass, with two added checks: the scan profile intest_lance_array_predicate_pushdown(failing against [feature](lance) Push predicates, LIMIT and COUNT(*) into Lance scans #70827's plugin) and a negative TTL intest_lance_catalog_all_types.Notes for Reviewers
MetaCache, which expires entries after their last access: [opt](lance) Cache table access resolution in FE #68305's TTL counts from the describe, so a busy table must still be described again._versions/<n>.manifest) Lance caches the index list of a pinned version without an e-tag, so the kept Session can return the deleted dataset's indexes for the new one. REFRESH CATALOG reads them afresh (LanceSharedSessionNativeTest), and the javadoc ofLanceConnector.invalidateDbsays so.collectScanProfiles, so no SPI change. The test seams (LanceCatalogClient.ResourceFactory, a package-privateLanceConnectorconstructor,LanceIndexMetadata.readover suppliers) stand in for 4.2's Mockito mocks, which connector modules do not allow.Release note
Lance catalogs keep reusing table metadata across queries, as in 4.1 and 4.2, with
lance.table_access_cache_ttl_seconds(default 60 seconds). In the query profile,Lance Metadata Metricsnow has one entry per scanned table, and Lance metadata time is no longer included inExternal Table Get Table Meta Time.Check List (For Author)
AI Disclosure