Skip to content

[feature](lance) Read REST catalogs with OSS and vended credentials - #70725

Merged
morningman merged 7 commits into
apache:masterfrom
morningman:b2m-t38-lance-rest-oss-master
Nov 21, 2026
Merged

morningman merged 7 commits into
apache:masterfrom
morningman:b2m-t38-lance-rest-oss-master

Conversation

@morningman

@morningman morningman commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Background

Lance catalogs expose a namespace as Doris databases and tables. The FE reads dataset manifests through the Lance Java SDK and passes the pinned version and storage options to the BE's lance-c reader. Master now serves filesystem namespaces through the Lance connector plugin; released 4.1/4.2 versions also serve REST namespaces and OSS storage.

What problem does this PR solve?

Issue Number: #70680
Related PR: #70681 (filesystem plugin foundation), #66581 (REST namespace source), #66805 (vended storage options source), #67157 (OSS source), #70338 (property masking), #70364 (endpoint checks with default ports)
PR Type: Feature

Problem Summary:

This ports REST namespaces, namespace-vended credentials and OSS support from branch-4.x to the master Lance plugin. Users can read tables through a namespace service without configuring static dataset credentials in Doris. The change also validates REST authentication and headers, declares the new endpoint and secrets, and adds the REST fixture and behavior tests. Filesystem catalogs keep their existing defaults and checks.

Original authors: @zhangstar333 and @FANNG1.

Details

  • Change map: Production code +585/-76 lines; tests and fixtures +2011/-48; generated regression output +20; pipeline configuration +3. Most changed lines are tests or fixture infrastructure.

    Part Purpose Approximate changed production lines
    REST namespace access Validate properties, select the namespace client, request table credentials, and sanitize errors 330
    OSS storage Adapt OSS properties, refuse OSS-HDFS and unresolved AssumeRole, canonicalize options, and isolate explicit identities 206
    S3 option reconciliation Validate merged credentials, reset a missing replacement token, and reconcile endpoint addressing using native boolean semantics 125
  • Scope: REST authentication supports none, bearer and api_key, plus extra headers; ALTER can switch modes by clearing the inactive credential with ""; namespace-vended options override catalog options for FE metadata and BE scans. OSS uses Lance's OpenDAL provider. Declared-only and namespace-managed-version tables fail explicitly; their version protocol belongs to a later phase.

  • Design: Reuse the namespace and storage-provider contracts from 4.1/4.2 inside the existing plugin, without adding Lance branches to the engine. The four-phase plan is tracked in [Feature][Lance] Serve Lance catalogs on master through a connector plugin #70680. Reading storage-latest for managed tables was rejected because the namespace may not have published that version; this phase refuses them instead. Credential validation follows the catalog/vended merge so an endpoint-only catalog can receive valid credentials. Reconcile inherited S3 endpoints with the final addressing mode using object_store's boolean vocabulary; a namespace value such as on must qualify the bucket just like true.

  • Usage: With the external regression namespace fixture:

    CREATE CATALOG lance_rest PROPERTIES (
        "type" = "lance",
        "lance.catalog.type" = "rest",
        "lance.rest.uri" = "http://127.0.0.1:19102",
        "lance.rest.security.type" = "bearer",
        "lance.rest.bearer-token" = "doris-lance-rest-test-token",
        "s3.endpoint" = "http://127.0.0.1:19001",
        "s3.region" = "us-east-1",
        "use_path_style" = "true"
    );
    SELECT count(*), sum(row_id) FROM lance_rest.`default`.all_types;

    The committed fixture returns 12, 78 without a static access key or secret key in the catalog.

  • Default behavior: lance.catalog.type remains filesystem; REST authentication defaults to none. REST requires lance.rest.uri and rejects warehouse. No new FE configuration or session variable is introduced.

  • Compatibility: Preserve the 4.1/4.2 property names and raw catalog map. Catalog reconstruction and replay perform no native connection; first use opens the namespace. No shared SPI, Thrift, Protobuf or storage-format change; the plugin API stays at master's 34.0. Reads retain the foundation's FE/BE compatibility checks. A downgrade needs a version that already supports the chosen Lance namespace and storage provider.

  • Security and privileges: lance.rest.uri is a user-controlled outbound HTTP/SSRF surface. Catalog creation requires scoped CREATE_PRIV, endpoint changes require ALTER_PRIV, and reads require SELECT_PRIV. Declare REST alongside all existing S3-compatible endpoint aliases so the configured engine gate covers CREATE and ALTER. Mask bearer/API-key values and credential-bearing extra headers; strip them from provider errors. Existing engine audit handling is reused.

  • Follow-up plan: Predicate/LIMIT/COUNT pushdown and caches remain later phases of [Feature][Lance] Serve Lance catalogs on master through a connector plugin #70680; namespace-managed versioning remains a separate follow-up.

Testing

  • With the review fixes, run-fe-ut.sh --run 'org.apache.doris.connector.lance.*Test' passed all 149 Lance tests locally on macOS aarch64/JDK 17.0.19, with zero failures, errors or skips. This includes pass-through credential redaction, merged OSS credential-pair validation, REST authentication/header checks and actual JNI REST/S3/OSS tests.
  • On unchanged production at 5471c9ebe0e, the three new tests failed on the intended assertions: an echoed vended token remained visible and incomplete OSS identities were accepted. Zero errors or skips. The fixed cases also cover case variants, catalog-completed pairs and clearing just one credential.
  • At ccbffd65cd3, four control-byte tests ran through run-fe-ut.sh: both rejection tests failed on missing exceptions; both legal-value controls passed. Zero errors or skips. They cover CREATE/merged ALTER, leading/interior/trailing controls, extra headers and both credentials.
  • At 1365c0a4849, 77 engine tests for catalog privileges, endpoint gating, plugin registration and 4.1.5 replay passed; thirteen SPI tests passed. Those engine and SPI paths have no later production changes in this PR.
  • At 1365c0a4849, test_lance_catalog_all_types and test_lance_rest_catalog passed on freshly built FE/ASAN BE using the committed dataset and a local S3 substitute that validated SigV4. The runner generated the REST output, whose shared blocks matched branch-4.2; scoped CREATE/ALTER/SELECT privileges and SHOW CREATE masking were verified there.
  • The SQL regression now covers all six authentication transitions, conflicting header-name case variants, and SQL control escapes in extra headers and both credentials. These later SQL additions have not been run against a local cluster; expected-output files are unchanged. The External pipeline enables this suite and its fixture.

Notes for Reviewers

  • Mask runtime credentials including Azure/GCS aliases; validate OSS pairs after merging and before authentication inference.
  • The SSRF gate checks literal CREATE/ALTER endpoint properties at statement time. Namespace-returned destinations remain trusted external metadata under threat-model.md; this port adds no runtime FE/BE egress policy. Both credential-handling defects also exist in the inspected 4.1/4.2 implementations and need separate adaptation.
  • Reject C0 controls except HTAB, and DEL, in headers and both credentials before Lance silently omits the header, potentially selecting a server default. Preserve valid values. The CR/LF-only 4.1/4.2 validators need separate adaptation.
  • Case-equivalent custom header names must agree; validation emits one lowercase SDK header while preserving raw catalog properties. ALTER can update the original spelling or all retained aliases together.
  • An empty inactive REST credential clears its value during ALTER; whitespace-only inactive credentials remain invalid.
  • Keep the filesystem AssumeRole rejection and all endpoint aliases added during the foundation review. Only the obsolete REST-rejection regression assertion is removed.
  • A complete vended S3 pair without a token clears the inherited catalog/environment token; an explicitly vended token is preserved. The 4.x maintainers need the same fix.
  • S3 reconciliation accepts the pinned object_store true/false spellings and case variants, preserves namespace option values, and rejects invalid booleans. OSS keeps its separate native grammar.
  • Docker cannot read cached image blobs here. Full MinIO/Compose, remote OSS and Linux runs are unverified; the External pipeline enables the fixture.

Release note

Lance catalogs support REST namespace services, namespace-vended credentials and OSS storage through the connector plugin. Existing 4.1/4.2 catalog property names remain supported; namespace-managed-version tables report an explicit unsupported error until that protocol is added.

Check List (For Author)

  • Behavior changed: No
  • Does this need documentation: Yes (extend the Lance catalog documentation in apache/doris-website with REST authentication, credential-clearing ALTER examples, header case/value rules, OSS, vended credentials and the managed-versioning limitation alongside the plugin port)
  • Pre-submission status: Partially verified: the later SQL authentication/header cases have no current cluster regression run; full MinIO/Compose, remote OSS, Linux and the complete FE unit suite were not run locally

AI Disclosure

  • Tool: Claude Code (Claude Opus 5.5) for the original port; Codex (GPT-6) for the current-master adaptation and REST/storage-option review fixes
  • Generated: code, tests, REST fixture, validation helpers and this description
  • Human review: not stated

### Background

Lance catalogs expose a namespace as Doris databases and tables. The FE reads dataset manifests through the Lance Java SDK and passes the pinned version and storage options to the BE's lance-c reader. Master now serves filesystem namespaces through the Lance connector plugin; released 4.1/4.2 versions also serve REST namespaces and OSS storage.

### What problem does this PR solve?

Issue Number: apache#70680
Related PR: apache#70681 (filesystem plugin foundation), apache#66581 (REST namespace source), apache#66805 (vended storage options source), apache#67157 (OSS source), apache#70338 (property masking), apache#70364 (endpoint checks with default ports)
PR Type: Feature

Problem Summary:

This ports REST namespaces, namespace-vended credentials and OSS support from branch-4.x to the master Lance plugin. Users can read tables through a namespace service without configuring static dataset credentials in Doris. The change also validates REST authentication and headers, declares the new endpoint and secrets, and adds the REST fixture and behavior tests. Filesystem catalogs keep their existing defaults and checks.

Original authors: @zhangstar333 and @FANNG1.

### Details

- **Change map:** Production code +465/-58 lines; tests and fixtures +1351/-47; generated regression output +20; pipeline configuration +3. Most changed lines are tests or fixture infrastructure.

  | Part | Purpose | Approximate changed production lines |
  | --- | --- | --- |
  | REST namespace access | Validate properties, select the namespace client, request table credentials, and sanitize errors | 290 |
  | OSS storage | Adapt the engine's OSS binding and normalize provider options; refuse OSS-HDFS and unresolved AssumeRole | 200 |
  | Vended S3 identity | Validate after the merge and prevent an independent vended key pair inheriting another identity's session token | 30 |

- **Scope:** REST authentication supports `none`, `bearer` and `api_key`, plus extra headers; namespace-vended options override catalog options for FE metadata and BE scans. OSS uses Lance's OpenDAL provider. Declared-only and namespace-managed-version tables fail explicitly; their version protocol belongs to a later phase.
- **Design:** Reuse the namespace and storage-provider contracts from 4.1/4.2 inside the existing plugin, without adding Lance branches to the engine. The four-phase plan is tracked in apache#70680. Reading storage-latest for managed tables was rejected because the namespace may not have published that version; this phase refuses them instead. Credential validation follows the catalog/vended merge so an endpoint-only catalog can receive valid credentials.
- **Usage:** With the external regression namespace fixture:

  ```sql
  CREATE CATALOG lance_rest PROPERTIES (
      "type" = "lance",
      "lance.catalog.type" = "rest",
      "lance.rest.uri" = "http://127.0.0.1:19102",
      "lance.rest.security.type" = "bearer",
      "lance.rest.bearer-token" = "doris-lance-rest-test-token",
      "s3.endpoint" = "http://127.0.0.1:19001",
      "s3.region" = "us-east-1",
      "use_path_style" = "true"
  );
  SELECT count(*), sum(row_id) FROM lance_rest.`default`.all_types;
  ```

  The committed fixture returns `12, 78` without a static access key or secret key in the catalog.
- **Default behavior:** `lance.catalog.type` remains `filesystem`; REST authentication defaults to `none`. REST requires `lance.rest.uri` and rejects `warehouse`. No new FE configuration or session variable is introduced.
- **Compatibility:** Preserve the 4.1/4.2 property names and raw catalog map. Catalog reconstruction and replay perform no native connection; first use opens the namespace. No shared SPI, Thrift, Protobuf or storage-format change; the plugin API stays at master's 34.0. Reads retain the foundation's FE/BE compatibility checks. A downgrade needs a version that already supports the chosen Lance namespace and storage provider.
- **Security and privileges:** `lance.rest.uri` is a user-controlled outbound HTTP/SSRF surface. Catalog creation requires scoped `CREATE_PRIV`, endpoint changes require `ALTER_PRIV`, and reads require `SELECT_PRIV`. Declare REST alongside all existing S3-compatible endpoint aliases so the configured engine gate covers CREATE and ALTER. Mask bearer/API-key values and credential-bearing extra headers; strip them from provider errors. Existing engine audit handling is reused.
- **Follow-up plan:** Predicate/LIMIT/COUNT pushdown and caches remain later phases of apache#70680; namespace-managed versioning remains a separate follow-up.

### Testing

- Locally, 118 Lance unit tests and 13 SPI security/surface tests passed, with zero failures or skips. The Lance tests include real JNI, REST authentication/failures, provider options, and native subprocess checks with unrelated AWS credentials and endpoints in the environment.
- `run-fe-ut.sh` passed all 118 Lance tests plus 77 engine tests for catalog privileges/endpoint gating, plugin registration and 4.1.5 image replay.
- Eleven targeted mutations failed on their intended cases after a passing 62-test control, covering credential merge/identity, vending, managed tables, OSS routing, endpoint declarations, masking and error sanitizing.
- The new missing-session-token test failed before the identity fix and passed afterward; a complete vended key pair must not inherit a catalog or ambient session token.
- `test_lance_catalog_all_types` and `test_lance_rest_catalog` passed together on freshly built FE/ASAN BE. The REST output was generated with the regression runner; all four shared result blocks match the independent branch-4.2 output. The local S3 service validates SigV4 and serves the exact committed dataset; the shipped REST stub ran on the host.
- A non-SUPER user was denied CREATE/ALTER without scoped grants, succeeded after grants, and read the REST schema and all 12 rows with SELECT permission. SHOW CREATE masked the bearer token and credential-bearing extra header.

### Notes for Reviewers

- Keep the filesystem AssumeRole rejection and all endpoint aliases added during the foundation review. Only the obsolete REST-rejection regression assertion is removed.
- A complete namespace-vended S3 key pair without a token explicitly sets an empty token before merging. This blocks a catalog STS token and native environment fallback; an explicitly vended token is preserved. The same issue is recorded for the 4.x maintainers.
- The Docker daemon cannot read cached image blobs on this host. Full MinIO/Compose, remote OSS and Linux execution are not claimed; the External pipeline enables the new suite and its Compose fixture.

### Release note

Lance catalogs support REST namespace services, namespace-vended credentials and OSS storage through the connector plugin. Existing 4.1/4.2 catalog property names remain supported; namespace-managed-version tables report an explicit unsupported error until that protocol is added.

### Check List (For Author)

- Behavior changed: No
- Does this need documentation: Yes (extend the Lance catalog documentation in apache/doris-website with REST authentication, OSS, vended credentials and the managed-versioning limitation alongside the plugin port)
- Pre-submission status: Partially verified: full MinIO/Compose, remote OSS, Linux and the complete FE unit suite were not run locally

### AI Disclosure

- Tool: Claude Code (Claude Opus 5.5) for the original port; Codex (GPT-6) for the current-master adaptation
- Generated: code, tests, REST fixture, validation helpers and this description
- Human review: not stated

Co-authored-by: zhangstar333 <zhangsida@selectdb.com>
Co-authored-by: FANNG <fanng@apache.org>
@morningman

Copy link
Copy Markdown
Contributor Author

run buildall

@morningman

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Completed a static review of all 27 changed paths at head 1365c0a, including the upstream/downstream FE/BE read path and pinned native provider sources. Four P2 findings need attention: S3 endpoint/addressing-mode reconciliation, OSS token replacement, ambient OSS authentication selectors, and OSS addressing-option canonicalization. The ambient-selector finding groups two related native overrides. No existing inline threads were present and no P0/P1 finding is carried forward. No additional user focus was supplied.

Critical checkpoint conclusions:

  1. Goal and proof: REST discovery/authentication, credential vending and OSS routing are implemented, but the inline storage cases prevent the advertised behavior for valid inputs. Unit/native/regression tests were inspected; they miss these cases.
  2. Scope and reuse: focused connector changes reuse the provider abstraction and shared engine contracts; no connector-specific engine branching or shared SPI API change.
  3. Concurrency and locks: stateless adapters and immutable access maps; existing initialization/in-flight accounting and namespace listing locks preserve ownership. No new lock-order issue found; remote table describes remain outside the listing lock.
  4. Lifecycle and memory: lazy JNI/network setup preserves replay; in-flight leases delay native cleanup, per-read allocators/Datasets close deterministically, and TCCL is restored. No new cross-TU/static initialization dependency.
  5. Configuration: catalog properties and fixture ports only; same-mode credentials/URI/header ALTER triggers existing connector rebuild. Auth-mode switching restrictions match the released REST property contract. No FE/BE configuration or session variable added.
  6. Compatibility: released REST property names and replay maps retained; no storage-format or symbol change. Native interpretations were checked against FE Lance 12.0.0/OpenDAL 0.59.1 and the pinned BE Lance/OpenDAL 0.59.2, rather than the stale version comment. Existing reader compatibility checks remain.
  7. Thrift/protobuf: no definitions changed; no field-id or enum migration applies.
  8. Parallel paths: filesystem/REST, S3/OSS/pass-through and catalog/vended options were checked. Filesystem AssumeRole rejection remains, OSS-HDFS fails explicitly, and unrelated storage providers retain pass-through behavior.
  9. Conditions and errors: not-found is distinguished from service/auth errors; declared and managed-version tables fail explicitly before dataset open. Null/NUL/conflicting options fail loudly. The inline findings concern valid combinations not covered by these guards.
  10. Tests and results: REST auth/failures, managed-table refusal and prefixed/unprefixed credentials are covered in the changed tests. Ordered listings and predicate rows, and single-row aggregates, are deterministic; 12 rows/IDs 1..12/sum 78 match the existing fixture. Public MinIO alone cannot prove signed identity; the native S3 test observes signing but omits these mode changes. Output generation and author-reported test passes were not independently reproduced.
  11. Observability: operation/table-context errors and existing connectivity warnings are appropriate; no new high-volume logging or metrics are needed for pure option translation.
  12. Persistence and failover: no new EditLog or transaction state; raw-property persistence/replay remains on the existing path and constructors perform no native connection.
  13. Writes and atomicity: this remains a read-only connector feature; no data-write or commit protocol changes.
  14. FE/BE passing: one resolved URI/options/version/schema/fragment set is retained in the statement memo; merged options reach Dataset.open and TLanceScanParams, then BE's checked C-string boundary. Native/environment interpretation is the problem described inline, not a missing transport field.
  15. Performance: small map rewrites are proportional to property count; statement memo avoids repeated metadata loads, and listing pagination retains repeated-token detection. No additional performance defect substantiated.
  16. Other invariants: namespace-managed versions are rejected rather than reading unpublished storage-latest data; internal transaction visibility, MoW/delete bitmaps and BE row-loop memory accounting are unchanged.

Validation was static only: no builds, tests, benchmarks, source edits or runtime checks were performed. Remote OSS, full Compose and platform execution remain unexecuted. No changed path or candidate remains uncovered/unresolved after the final challenge; convergence is reported separately by the delivery helper.

Review converged after 2 round(s).

// with an empty string, so it cannot introduce a NUL missed by validation above.
normalizedVended = provider.normalizeVendedStorageOptions(vendedOptions);
}
result.putAll(normalizedVended);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Reconcile the inherited S3 endpoint after merging the addressing mode

A REST catalog with s3.endpoint=http://minio:9000 and use_path_style=true can now receive virtual_hosted_style_request=true from DescribeTable while retaining the catalog endpoint. The merge produces a virtual-hosted request with a bucketless endpoint: the pinned object_store builder uses an explicit endpoint verbatim in that mode, so s3://warehouse/... requests go to the service root instead of the warehouse bucket. The reverse style change duplicates the bucket in host and path. vendedCredentialsSupersedeTheCatalogsOnS3 currently asserts the first inconsistent map. Convert an inherited catalog endpoint using the final merged addressing mode, and verify the resulting native host/path for both style changes.


@Override
public Map<String, String> normalizeVendedStorageOptions(Map<String, String> options) {
return LanceStorageOptions.normalizeAliases(options, PUBLIC_BY_ALIAS);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Clear the previous OSS token when replacing its key pair

When the catalog has OSS session credentials and DescribeTable vends a complete permanent key pair without security_token, this normalizer replaces only the keys. The merged map retains the catalog's oss_security_token, so OpenDAL signs the new identity with the previous identity's token and otherwise valid reads fail authentication. With no catalog token, Lance can also import an unrelated OSS_SECURITY_TOKEN or ALIBABA_CLOUD_SECURITY_TOKEN from the FE/BE environment. Apply the same identity reset as the S3 normalizer: explicitly clear a missing token for a complete replacement pair, and prevent a permanent catalog pair from inheriting an ambient token.

}
return inferred;
}
inferred.put(ALLOW_ANONYMOUS, String.valueOf(!hasSigningConfiguration));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep ambient OSS authentication selectors from overriding explicit keys

Lance imports the process's OSS/AWS/Alibaba options before overlaying this map. On the native versions actually pinned here, skip_signature and allow_anonymous are separate fields combined with OR, so emitting only allow_anonymous=false leaves OSS_SKIP_SIGNATURE=true effective and sends private-bucket reads unsigned. Likewise, an ambient OSS_ROLE_ARN or ALIBABA_CLOUD_ROLE_ARN survives and makes OpenDAL wrap the complete configured/vended key pair in an STS AssumeRole provider; keys allowed to read the bucket but not assume that unrelated role then fail. A BE-only export can let FE planning succeed while execution fails. Explicit identities need to neutralize both ambient signing and role selectors, while preserving any deliberately supplied namespace options.

// OpenDAL 0.57 renamed this option to skip_signature, but lance-c 0.1.6 still uses
// OpenDAL 0.56. Emit the old spelling, which newer OpenDAL keeps as an alias.
Map.entry(SKIP_SIGNATURE, ALLOW_ANONYMOUS),
Map.entry(ALLOW_ANONYMOUS, ALLOW_ANONYMOUS));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Canonicalize the OSS addressing-style option before merging

ADDRESSING_STYLE=path is a valid case-insensitive OpenDAL option, but addressing_style is missing from this alias table. With an OSS catalog binding, normalization has already emitted lowercase addressing_style=virtual; the vended uppercase spelling therefore survives beside it instead of overriding it. OpenDAL lowercases both keys during its derived config deserialization and rejects the duplicate addressing_style field, so this valid namespace override cannot open the table. Include ADDRESSING_STYLE -> ADDRESSING_STYLE in the canonical map and cover a mixed-case override/conflict.

### Background

Lance catalogs combine catalog storage settings with per-table options returned by a namespace. The FE and BE open the dataset with the same merged map, while their native providers can also import process environment settings.

### What problem does this PR solve?

Issue Number: apache#70680
Related PR: apache#70725 (review follow-up), apache#70681 (filesystem plugin foundation)
PR Type: Bugfix

Problem Summary:

A namespace override could leave an inherited S3 endpoint inconsistent with the requested addressing mode. OSS reads could retain another identity's token or process authentication selectors, and mixed-case addressing overrides could produce duplicate native fields. Reconcile S3 endpoints after merging and make explicit OSS identities override ambient authentication settings while retaining namespace-supplied values.

### Details

- **Change map:** Production code +76/-27 lines; tests +246/-12 lines. The production changes cover S3 endpoint reconciliation and OSS authentication/canonicalization; most additions exercise the native providers against local HTTP fixtures.
- **Frequency:** Always for the reproduced combinations: a vended S3 addressing-mode switch, OSS permanent keys with an unrelated token/anonymous flag/role in the environment, or an uppercase OSS addressing override.
- **Root cause:** S3 bucket qualification ran before the namespace selected the final style. OSS cleared neither missing replacement tokens nor both native signing selectors and the ambient role; its canonical map omitted addressing_style. The pinned OpenDAL versions read skip_signature and allow_anonymous as separate fields combined with OR.
- **Why existing tests missed it:** LanceStorageOptionsTest asserted an inconsistent S3 map and omitted the OSS combinations. LanceS3StorageNativeTest covered only an unchanged path-style endpoint. test_lance_rest_catalog uses one path-style fixture without OSS process settings. Correct the old assertions and add native subprocess tests; run-fe-ut.sh explicitly includes the Lance module in CI.
- **Fix:** Keep the catalog S3 endpoint as a service endpoint until the final addressing mode is known. Clear absent tokens for complete OSS identities, default both signing selectors and the role after merging, canonicalize addressing/role keys, and preserve explicit namespace options.
- **Other paths and branches:** Both readers receive the final map through the existing scan parameters; shared SPI, Thrift and storage formats are unchanged. Other providers retain their pass-through behavior. The master OSS code originates in unmerged apache#70725. Inspected branch-4.1 and branch-4.2 refs contain analogous OSS patterns in fe-core and require a separate adaptation; branch-3.1 and branch-4.0 have no Lance provider. These release refs were not freshly fetched.

### Testing

- On unchanged production code, the four targeted unit cases and both S3 native addressing transitions failed. With the corrected OSS fixture expectation, all four OSS native cases failed for the intended reasons: an unrelated token, unsigned requests, an unintended STS request, and duplicate addressing_style.
- After the fix, run-fe-ut.sh --run 'org.apache.doris.connector.lance.*Test' ran all 129 Lance tests with zero failures, errors or skips on macOS aarch64/JDK 17.0.19. This includes real JNI requests for both S3 style transitions and OSS catalog/vended identities with poisoned environments.
- Maven validate for fe-connector-lance and its upstream modules passed with zero Checkstyle violations and the connector architecture gate enabled. git diff --check passed.
- No new cluster regression run, remote OSS service or Linux/BE runtime execution is claimed for this follow-up.

### Notes for Reviewers

Namespace endpoints retain their native meaning. Only inherited Doris S3 endpoints are bucket-qualified. An empty OSS role blocks the imported role because OpenDAL deserializes empty optional strings as None; explicit namespace roles and tokens remain authoritative.

### Release note

Lance namespace reads honor S3 addressing overrides and OSS credentials without inheriting unrelated process tokens or authentication selectors. Mixed-case OSS addressing options override the catalog correctly.

### Check List (For Author)

- Behavior changed: No
- Does this need documentation: No
- Pre-submission status: Partially verified: remote OSS, Linux/BE runtime and a new cluster regression run were not executed for this follow-up

### AI Disclosure

- Tool: Codex (GPT-6)
- Generated: code, tests and this description
- Human review: not stated
@morningman

Copy link
Copy Markdown
Contributor Author

run buildall

@morningman

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Static review of all 28 changed files at 328ec75. One new P2 finding: the new S3 endpoint reconciliation parses a narrower boolean vocabulary than both pinned native readers. The four existing P2 findings are addressed at this head; no existing P0/P1 finding remains applicable and none is duplicated.

Flow inspected: CREATE/ALTER properties -> lazy REST/directory namespace -> DescribeTable and merged storage options -> statement-pinned dataset version/schema/fragments -> TLanceScanParams and fragment ranges -> BE lance-c open.

Critical checkpoint conclusions:

  • Goal and evidence: REST namespaces, vended credentials and OSS adapters are implemented, with explicit rejection of declared and namespace-managed-version tables. Unit/native/regression coverage was inspected; the new parser case is missing.
  • Scope and reuse: changes stay within the Lance plugin and its fixtures/configuration; existing storage contracts, metadata memo and scan transport are reused.
  • Concurrency: in-flight leases protect namespace/allocator lifetime through concurrent catalog retirement; namespace listing locks and independent describes retain their existing arrangement. No new lock cycle found.
  • Lifecycle/static initialization: native resources open lazily, per-read datasets/allocators close deterministically, TCCL restores in finally, and no C++ static initializer changes.
  • Configuration: per-catalog REST/auth/header options and OSS warehouses are enabled; ALTER rebuilds connector state. No global FE configuration or session variable is added.
  • Compatibility: property vocabulary matches the released REST implementation; catalog reconstruction remains free of native connections. Existing backend compatibility checks remain. No shared SPI, incompatible public interface or storage-format change.
  • Thrift/Protobuf IDs: no definitions changed; existing fields carry the option map and version.
  • Parallel paths: filesystem/REST and S3/OSS/pass-through paths were traced; existing AssumeRole and OSS-HDFS restrictions remain explicit.
  • Conditions and errors: managed/declared tables, alias conflicts and null/NUL transport fail explicitly. Alternate valid S3 booleans are mishandled by the new condition, as reported inline.
  • Test coverage: positive REST/auth/vending, service errors, identity reset, endpoint addressing, aliases and native environment cases are represented. Native subprocess tests exercise FE JNI; BE ambient OSS cases and real remote OSS are not covered by those tests.
  • Changed results: fixture names, ordered output and aggregate expectations are internally consistent. Runtime results and automatic generation provenance were not independently established by this static review.
  • Observability: sanitized connector failures and existing version/fragment EXPLAIN data remain; no new per-row logging or demonstrated need for additional metrics found.
  • Persistence/failover: existing raw catalog properties persist; no EditLog format or transaction processing change. Initialization remains lazy after reconstruction.
  • Data writes/atomicity: no new data-writing or transaction path; review concerns read metadata and scan configuration.
  • FE/BE variables: merged credentials remain with the pinned metadata and pass through existing scan-level options; URI/version/fragments are preserved in range descriptors.
  • Performance: statement memoization avoids repeated metadata opens; no new shared-state or demonstrated hot-path regression found.
  • Additional issues: native boolean semantics and the four prior findings were independently rechecked; no other substantiated candidate remains.

User focus: no additional focus points were supplied. Validation was static only: no builds, tests, benchmarks, Compose deployment or runtime/remote OSS checks were performed. The fixture's public MinIO bucket means regression scans alone do not prove credential signing; FE native signer assertions provide complementary coverage. These are validation limits, not unreviewed changed files or unresolved code candidates.

Review converged after 2 round(s).

// Only Doris endpoints need bucket qualification. Namespace endpoints already use
// object_store's native vocabulary and must keep the meaning the namespace assigned.
LanceStorageOptions.putIfNotEmpty(merged, ENDPOINT, endpointForDataset(datasetUri,
catalogOptions.get(ENDPOINT), Boolean.parseBoolean(merged.get(VIRTUAL_HOSTED_STYLE))));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Match Lance's boolean grammar when reconciling the endpoint

The new parser treats valid namespace values such as virtual_hosted_style_request=on, 1, or yes as false, while the pinned FE/BE object_store readers parse them as true. For s3://warehouse/table.lance with an inherited s3.endpoint=http://storage.example:9000, this leaves both endpoint options bucketless; the native virtual-hosted builder then uses that endpoint verbatim, so the table request omits warehouse and fails. The existing endpoint-merge fix handles literal true/false; this is a separate mismatch in its newly added parser. Parse the final flag with the native vocabulary and cover an alternate true spelling in the native host/path test.

### Background

Lance namespaces return per-table storage options that override catalog defaults. Doris reconciles an inherited S3 endpoint with the final addressing mode before the FE and BE open the dataset.

### What problem does this PR solve?

Issue Number: apache#70680
Related PR: apache#70725 (introduces the endpoint reconciliation)
PR Type: Bugfix

Problem Summary:

A namespace value such as virtual_hosted_style_request=on is true to the native reader but false to Java Boolean.parseBoolean. The inherited endpoint then lacks the bucket, so requests target the service host instead of the table's bucket. Parse the final flag with the pinned object_store boolean grammar.

### Details

- **Frequency:** Always when a namespace supplies an alternate true spelling and retains a catalog service endpoint.
- **Root cause:** Endpoint reconciliation uses Java's true-only parser while object_store accepts 1/true/on/yes/y and 0/false/off/no/n, ignoring ASCII case.
- **Why existing tests missed it:** LanceStorageOptionsTest and the native Host/path tests generated only literal true/false. The REST regression uses one fixed path-style fixture.
- **Fix:** Match the native vocabulary, preserve the default false and raw namespace values, and reject invalid flags. Extend existing map and JNI Host/path tests.
- **Other paths and branches:** Both readers receive the reconciled map through existing scan parameters. OSS keeps its different grammar. The affected parser was added in this unmerged feature PR; no release branch or shared protocol is changed.

### Testing

- On unchanged production at 328ec75, four added tests ran: three failed on the intended endpoint/Host/invalid-value assertions, and the native off control passed. Zero skips or setup errors.
- With the fix, run-fe-ut.sh --run 'org.apache.doris.connector.lance.*Test' ran 133 Lance tests with zero failures, errors or skips on macOS aarch64/JDK 17.0.19. This includes actual JNI Host/path checks for on/off and the existing S3/OSS and REST tests.
- A new cluster regression run, remote storage and Linux/BE runtime were not exercised for this targeted follow-up.

### Release note

None

### Check List (For Author)

- Behavior changed: No
- Does this need documentation: No
- Pre-submission status: Ready

### AI Disclosure

- Tool: Codex (GPT-6)
- Generated: code, tests and this description
- Human review: not stated
@morningman

Copy link
Copy Markdown
Contributor Author

run buildall

@morningman

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed all 28 changed files at e5e73886c85d4b468004b0f7a7ec25edbd68f5d3, including REST namespace access, storage adapters, native consumers, Docker fixtures, regression configuration and expected output. One new P2 finding: the REST validator prevents changing an existing catalog's authentication mode through ALTER, even when the inactive credential is explicitly cleared. No new P0/P1 finding was verified.

flowchart LR
  N[Namespace describe] --> M[Catalog and vended options merge]
  M --> F[FE pins dataset version and fragments]
  F --> T[Existing scan parameters]
  T --> B[BE opens same URI, version and options]
Loading
Critical checkpoint Conclusion from static inspection
Goal and correctness REST namespaces, vended credentials and OSS are integrated into the plugin. Snapshot pinning is retained; declared-only and namespace-managed-version tables fail before dataset opening. Authentication reconfiguration has the inline defect.
Scope and clarity Changes remain in the Lance connector and its fixtures/tests; provider-specific logic uses the existing abstractions. No unrelated production subsystem change found.
Concurrency and locks Existing in-flight call leases protect namespace/allocator closure. Listings retain namespace serialization; storage adapters use fresh maps and immutable singleton state. No introduced lock-order defect found.
Lifecycle and initialization Native initialization remains lazy, plugin TCCL is pinned, and datasets/read allocators use existing cleanup paths. No new static initialization dependency found.
Configuration and dynamic updates No global FE setting or session variable added. New REST catalog properties validate without I/O. ALTER merges the previous map, exposing the inactive-credential issue.
Compatibility and rolling upgrades Existing property names and scan transport remain. No shared plugin SPI or storage-format change. Exact FE/BE native option readers were inspected; no additional compatibility defect verified.
Thrift and Protobuf IDs Not applicable: no definition changed.
Parallel paths Filesystem/REST and S3/OSS/pass-through paths checked, including BE schema and normal scan opens. OSS-HDFS and catalog AssumeRole remain explicit unsupported cases.
Conditions and error handling Missing-table results are distinguished from service/authentication failures; alias conflicts, untransportable options and invalid flags fail explicitly. Credential-key presence during ALTER is the reported exception.
Test coverage Added unit/native test sources cover REST auth/headers/errors, existence/describe, version guards, alias precedence, token reset, ambient selectors and endpoint styles. Regression sources cover FE-to-BE reads. Merged ALTER authentication transitions are missing.
Changed test results New table listings and result blocks align with the fixture and existing all-types dataset expectations by inspection. Output generation and execution were not independently verified.
Observability Existing contextual errors and secret sanitization are reused; storage options are omitted from EXPLAIN. No separate metric requirement identified for these adapter changes.
Persistence and failover No new persisted record or EditLog path. Reconstruction remains free of native connections; existing catalog property journaling is reused.
Data writes and atomicity Not applicable: the connector change is read-only; no transaction, rowset, delete-bitmap or write-atomicity change.
FE-to-BE variables The complete merged map travels once per scan through existing TLanceScanParams; schema and execution consumers preserve the same options, URI and pinned version.
Performance and memory No new shared cache or worker pool. Option processing is linear in the small option maps; existing allocator limits and resource ownership remain. No material new hot-path issue verified.
Additional issues Native backend selection, optional token parsing and role/signature interactions were rechecked. No further supported-configuration defect substantiated.

The five prior P2 reports are addressed on this head and were not reposted: inherited S3 endpoint reconciliation (4617241505), OSS replacement-token reset (4617241986), ambient OSS signing/role selectors (4617242437), OSS addressing-style canonicalization (4617242901), and native S3 boolean grammar (4623303142). No existing P0/P1 finding remains to carry forward.

There was no additional user-provided review focus. All initial risk items and candidates have an explicit disposition; no changed-file coverage gap or unresolved static candidate remains. This was a static review only: no builds, tests, benchmarks, cluster startup or native runtime validation were executed. Linux/remote-cloud execution and credential-expiry behavior were not validated by this invocation.

Review converged after 2 round(s).

}
validateRestUri(restUri);

boolean bearerTokenConfigured = raw.containsKey(REST_BEARER_TOKEN);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Allow cleared credentials when changing REST authentication

ALTER CATALOG merges updates into the existing property map and cannot remove a key. For a bearer catalog, changing to api_key while setting lance.rest.bearer-token to "" still leaves bearerTokenConfigured=true, so the API-key branch rejects the change. The reverse transition and switching either mode to none fail for the same reason. This forces catalog recreation when a namespace changes its authentication method. Treat an explicitly cleared inactive credential as unset, while continuing to require a nonblank active credential, and cover these merged-map ALTER transitions.

### Background

Lance REST catalogs send namespace requests using bearer or API-key authentication, or no authentication. ALTER CATALOG validates a candidate formed by merging updates into the existing property map; it cannot remove property keys.

### What problem does this PR solve?

Issue Number: apache#70680
Related PR: apache#70725 (introduces the REST validator)
PR Type: Bugfix

Problem Summary:

Changing an existing REST catalog's authentication mode fails even when the old credential is explicitly set to an empty string. The validator treats the retained key as configured. Treat an exact empty inactive credential as unset while retaining nonblank active credentials and rejecting nonempty inactive credentials.

### Details

- **Frequency:** Every mode change that clears an existing bearer or API-key credential still retains its key in the merged property map and hits the incorrect rejection.
- **Root cause:** The REST validator uses key presence rather than nonempty credential values to reject credentials belonging to another authentication mode.
- **Why existing tests missed it:** The property tests cover standalone CREATE-style maps, and the REST regression creates one bearer catalog. Neither covers merged ALTER candidates carrying explicitly emptied credentials.
- **Fix:** Check inactive credentials by value, preserve the raw property map and existing active-credential/header checks, and cover both authenticated-mode switches, disabling/re-enabling authentication and invalid transitions. Extend the existing SQL regression with all six directed transitions before its reads.
- **Other paths and branches:** CREATE, ALTER and connector reconstruction share the same property holder. Filesystem validation is unchanged. The faulty validator is introduced in the unmerged feature PR apache#70725; no release branch, shared SPI or wire format is modified.

### Testing

- On unchanged production at e5e7388, run-fe-ut.sh ran the four new authentication tests: three expected-valid transitions were rejected by the reported validation errors and the negative test passed, with zero skips.
- With the fix, run-fe-ut.sh --run 'org.apache.doris.connector.lance.*Test' passed 137 Lance tests with zero failures, errors or skips on macOS aarch64/JDK 17.0.19.
- Module-scoped Maven validate passed Checkstyle and connector architecture gates. git diff --check passed.
- The added SQL ALTER regression has not been run against a cluster locally. Its existing expected-output blocks are unchanged.

### Release note

Lance REST catalog authentication can be changed with ALTER CATALOG by setting the inactive credential property to an empty string.

### Check List (For Author)

- Behavior changed: No
- Does this need documentation: Yes (include credential-clearing ALTER examples in the feature PR's Lance REST documentation plan)
- Pre-submission status: Partially verified: the added SQL authentication transitions have not been run against a local cluster

### AI Disclosure

- Tool: Codex (GPT-6)
- Generated: code, tests, review analysis and this description
- Human review: not stated
@morningman

Copy link
Copy Markdown
Contributor Author

/review

@morningman

Copy link
Copy Markdown
Contributor Author

run buildall

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Static review of #70725 at c8f4e8d. One new P2 finding: conflicting case variants of a custom REST header survive catalog ALTER, and native header insertion can keep the previous value. See the inline finding. No P0/P1 finding was independently confirmed.

Reviewed flow: CREATE/ALTER properties -> lazy REST or directory namespace -> DescribeTable with vended credentials -> provider normalization/merge -> FE version/schema/fragment pin -> TLanceScanParams options -> BE lance-c read of that version.

Critical checkpoints:

  • Goal and evidence: the implementation adds REST namespaces, namespace-vended storage credentials and OSS to the existing plugin. Managed-version and declared-only tables fail explicitly. Java property/HTTP/native tests and SQL regression coverage are present; the custom-header conflict is missing coverage.
  • Scope and reuse: production changes stay in the Lance plugin and reuse its existing storage, snapshot and scan infrastructure. Fixture and test additions account for most of the diff; no connector-specific engine branch or shared SPI change was introduced.
  • Concurrency and locking: concurrent statements lease the shared namespace/allocator through synchronized enter/leave. Listing/existence serialization is retained; describes remain concurrent. No new lock-order issue was found; one-time initialization is serialized, while final close occurs outside the lifetime monitor.
  • Lifecycle and initialization: namespace/native loading stays lazy, per-read datasets and child allocators close on failure, and retirement waits for active calls. Plugin TCCL is restored in finally. Property binding/rebuild does no native connection.
  • Configuration and dynamic changes: new catalog properties and fixture ports introduce no FE/BE configuration variable. Detached merged-map validation precedes ALTER journaling; catalog reset makes accepted changes effective on next access. Authentication-mode clearing is corrected; custom-header casing is the remaining issue.
  • Compatibility and generated protocols: no function-symbol, persisted data-format, shared plugin API, Thrift or Protobuf definition changes. Existing 4.x property names and filesystem defaults remain. The existing pinned-version/options payload is reused, and the relevant FE/BE native option semantics were inspected.
  • Parallel paths and special conditions: REST/filesystem, S3/OSS and pass-through storage paths were checked. OSS-HDFS and unresolved catalog AssumeRole fail explicitly; declared/managed-version guards prevent unsupported reads. Endpoint/style reconciliation follows the final merged native boolean value; namespace option precedence is preserved.
  • Tests and results: inspected all changed Java tests, fixture startup/provisioning, four regression configs, SQL and all output blocks. Sorted lists/ordered rows and aggregate outputs agree with the shared dataset. No build, unit test, regression test, native execution, benchmark or cluster was run during this review. Author run claims and output-generation provenance were not independently verified; Linux/Compose/remote OSS execution remains outside this static review.
  • Observability and errors: failures retain operation/table context and known credentials are sanitized; scan explanations omit option values. No additional metric is required by the changed read-only path, and no concrete new loss of failure information was found.
  • Persistence and failover: catalog property persistence uses the existing journal/replay/reset path. No new EditLog record or transaction algorithm; native connection remains deferred during rebuild. Internal partition versions and MoW/delete bitmaps are outside this change.
  • Writes and atomicity: the connector and fixture additions are read-only. No new data-write, commit, crash-recovery or remote mutation path is introduced.
  • FE/BE values: one option map is retained with pinned metadata and serialized once per scan; BE receives exact key/value strings and the pinned dataset version. Embedded NULs fail explicitly at both boundaries.
  • Performance and further issues: statement memoization and per-scan option transport are retained; no new unbounded retry, cross-statement authorization cache or redundant per-fragment metadata load was found. No further verified issue after the final recheck.

Existing review context: all six prior P2 concerns are addressed at this head: inactive REST credential clearing, native S3 boolean grammar, final S3 endpoint reconciliation, OSS session-token replacement, ambient OSS signing/role selectors and case-insensitive OSS addressing-style aliases. They are not duplicated. There are no existing P0/P1 comments to carry as blocking IDs. User focus: no additional focus was supplied.

Convergence: yes, after two review rounds. All three reviewers returned NO_NEW_VALUABLE_FINDINGS in the final round; all 28 changed paths, initial risks and candidate dispositions were covered, and the main final sweep found no unresolved review question. Validation is static-only.

Review converged after 2 round(s).

properties.put("delimiter", namespaceDelimiter);
raw.forEach((key, value) -> {
if (key.startsWith(REST_HEADER_PREFIX)) {
properties.put("header." + key.substring(REST_HEADER_PREFIX.length()), value);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Reject conflicting case variants of REST headers

A catalog created with lance.rest.header.X-Tenant=old accepts an ALTER setting lance.rest.header.x-tenant=new. Catalog property keys remain case-sensitive, so the merged map retains both and this loop forwards both to Lance. The pinned SDK keeps these names in a Rust HashMap, then inserts them into the same case-insensitive HTTP HeaderMap in unspecified iteration order (rest.rs, from_properties / apply_headers). Consequently the accepted tenant update can continue sending old, and reopening the client can change which value wins. Detect case-equivalent header names with conflicting values while validating the merged properties and emit one normalized header; cover this CREATE/ALTER case as well as the authentication-mode transitions.

### Background

Lance REST catalogs attach custom HTTP headers to namespace requests. Catalog property keys are case-sensitive, while HTTP header names are case-insensitive. ALTER validates a candidate formed by merging updates into the existing property map.

### What problem does this PR solve?

Issue Number: apache#70680
Related PR: apache#70725 (introduces the REST property validator)
PR Type: Bugfix

Problem Summary:

A catalog with `lance.rest.header.X-Tenant=old` accepts an ALTER adding `lance.rest.header.x-tenant=new`. Both values reach the SDK, whose HTTP header insertion can keep the old value. Reject conflicting case-equivalent names during validation and emit one lowercase custom header when the values agree.

### Details

- **Frequency:** Always accepts the conflicting property combination before the fix; the value selected by the native SDK depends on HashMap iteration order.
- **Root cause:** REST validation checks each header separately, and namespace parameter construction forwards the original case-sensitive names. ALTER cannot remove the retained property key.
- **Why existing tests missed it:** LanceCatalogPropertiesTest and LanceRestCatalogTest use one spelling per custom header. test_lance_rest_catalog covers authentication transitions without header aliases. Add provider validation cases, HTTP assertions across all six authentication transitions, and SQL CREATE/ALTER cases. The FE unit runner includes the Lance module; the External pipeline enables the SQL suite.
- **Fix:** Normalize validated custom header names with Locale.ROOT, reject unequal values without exposing them, and reuse the normalized map for SDK parameters. Keep the raw catalog map and header values unchanged. Users can update the original spelling, or update all retained aliases to the same value.
- **Other paths and branches:** All REST authentication modes share this path; filesystem properties and BE parameters are unchanged. This validator was introduced in unmerged apache#70725. Freshly fetched 4.1/4.2 sources contain analogous forwarding in LanceRestMetastoreProperties and need a separate adaptation. 3.1/4.0 have no Lance REST headers. No shared SPI or protocol change.

### Testing

- On unchanged production at c8f4e8d, run-fe-ut.sh ran the five new tests: all four property tests failed on the missing rejection/normalization assertions, while the native HTTP control passed. Zero errors or skips.
- With the fix, run-fe-ut.sh --run 'org.apache.doris.connector.lance.*Test' completed successfully: 142 Lance tests with zero failures, errors or skips, including actual JNI HTTP requests, S3/OSS and authentication transitions, on macOS aarch64/JDK 17.0.19.
- Module-scoped Maven validate passed Checkstyle and connector architecture gates. git diff --check passed.
- The added SQL CREATE/ALTER regression cases have not been run against a cluster locally. Expected-output files are unchanged.

### Release note

None

### Check List (For Author)

- Behavior changed: No
- Does this need documentation: Yes (include case-insensitive header names and original-spelling/all-alias ALTER examples in the feature PR's Lance REST documentation plan)
- Pre-submission status: Partially verified: the added SQL CREATE/ALTER cases were not run against a local cluster

### AI Disclosure

- Tool: Codex (GPT-6)
- Generated: code, tests, review analysis and this description
- Human review: not stated
@morningman

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Static review of all 28 changed paths at ccbffd6 found one new P2 issue: REST validation accepts control bytes that the pinned SDK silently drops along with their entire header. See the inline finding. No existing P0/P1 finding remains to carry forward. Review converged in two rounds; no unresolved candidate or uncovered changed-file scope remains.

Critical checkpoint conclusions:

  1. Goal and correctness: REST namespace access, vended credentials and OSS routing are implemented through the Lance plugin. Managed-version and declared-only tables fail before dataset open; ordinary reads retain one pinned version. The new header-value finding is the remaining verified correctness issue. Unit/native/regression tests were inspected as evidence of intended behavior.
  2. Scope and reuse: changes are focused on Lance plus its fixture/tests/configuration; provider merge hooks reuse the existing scan path. No engine connector-type branch or shared SPI change.
  3. Concurrency and locking: provider maps are per call, headers are fixed at construction, namespace entry uses the existing synchronized lease/in-flight counter, and retirement defers release until active calls finish. No new production thread, lock order or deadlock path identified.
  4. Lifecycle and initialization: native namespace/allocator construction remains lazy, plugin TCCL is restored, per-read allocators and datasets close deterministically, and catalog retirement uses existing cleanup. No new cross-translation-unit static dependency.
  5. Configuration and updates: REST properties validate the full merged ALTER candidate; accepted updates rebuild the client. Filesystem remains the default. Only regression fixture ports are added; no FE configuration/session-variable change.
  6. Compatibility: raw catalog properties and existing scan option transport are retained. Both pinned native consumers were inspected for credential aliases, empty-token resets, addressing and boolean grammar. No storage-format or public function-symbol change.
  7. Thrift/Protobuf IDs: not applicable; no generated definition changes.
  8. Parallel paths: filesystem/REST, S3/OSS/pass-through, catalog/vended options, FE metadata and BE opens were traced. Existing AssumeRole/OSS-HDFS limits stay explicit.
  9. Special conditions and failures: managed-version, alias-conflict, authentication-transition, missing-table versus service-error and untransportable-option checks have concrete failure paths. Header-value validation needs the inline correction.
  10. Test coverage: property/ALTER negatives, actual native host/path/signature/token checks, REST fixture scans and prefixed/unprefixed credentials are covered in added tests. Invalid control-byte headers are not covered. No builds, tests, benchmarks or runtime checks were executed in this static-only review.
  11. Expected results: added regression rows/order and aggregates agree with the committed 12-row fixture; Compose dependency, healthcheck, ports and suite enablement are coherent. Result generation was not rerun.
  12. Observability: provider failures retain operation context and sanitize declared catalog/runtime secrets. Existing reader profiles remain available; no additional critical metrics requirement identified.
  13. Persistence and failover: catalog updates use existing merged properties and journal/reset/rebuild machinery; construction performs no native connection. No new edit-log record or transaction state.
  14. Data writes and atomicity: not applicable; the feature reads external data and adds a read-only fixture.
  15. FE/BE variables: the same merged table storage map feeds FE ReadOptions and existing TLanceScanParams; BE preserves empty values and includes options with URI/version in its dataset key. No omitted send path identified.
  16. Performance: small maps are normalized per dataset access and transported once per scan; statement memoization reuses pinned metadata. No new row-loop work or material performance regression identified.

Existing review context: all seven earlier P2 threads were independently rechecked and are addressed at this head: inherited S3 endpoint/style and boolean grammar, OSS token reset, ambient signing/role selectors, mixed-case addressing, cleared inactive REST credentials and conflicting header-name case variants. None is duplicated. The new finding concerns invalid header-value bytes, a distinct mechanism.

User focus: no additional focus was supplied. Coverage limits: static evidence only; full MinIO/Compose, remote OSS, Linux/native execution and the added SQL ALTER transitions were not run here. Namespace-managed versions and credential refresh during a long-running statement remain explicit unsupported/limited scope; no runtime or rollout certification is claimed.

Review converged after 2 round(s).

throw new IllegalArgumentException("Authentication header '" + headerName
+ "' must be configured through '" + REST_SECURITY_TYPE + "'");
}
if (headerValue == null || headerValue.indexOf('\r') >= 0 || headerValue.indexOf('\n') >= 0) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Reject HTTP control bytes before Lance silently drops the header

With default SQL escaping, lance.rest.header.X-Tenant = "tenant\b" contains a backspace and passes this check. The pinned Lance 12.0.0 RestClient::apply_headers inserts a header only when HeaderValue::from_str succeeds and silently skips it otherwise. That parser rejects backspace, NUL, SUB and DEL as well as CR/LF, so every request loses the entire configured tenant header. A namespace service with a default tenant can then successfully list/read that default instead of reporting the invalid configuration. The bearer/API-key guard below has the same gap. Validate the full native header-value byte domain for extra headers and both credentials, retaining legal HTAB, and cover these control-byte values in negative tests.

### Background

Lance REST catalogs pass custom headers and authentication credentials from catalog properties to the native namespace client. The client silently omits a header when its value cannot be parsed as an HTTP header value. CREATE and merged ALTER validate these properties before opening the client.

### What problem does this PR solve?

Issue Number: apache#70680
Related PR: apache#70725 (adds REST validation to the master Lance connector)
PR Type: Bugfix

Problem Summary:

Values containing backspace, NUL, SUB or DEL pass the CR/LF-only validation, then disappear with their entire header in Lance. For example, a tenant header containing a backspace is accepted instead of reporting invalid configuration; omitting that header can select a server's default tenant. Reject invalid native header-value characters for extra headers and both credentials while preserving legal HTAB and non-ASCII text.

### Details

- **Frequency:** Always accepts the invalid control-byte inputs before the fix; any subsequent effect of a missing header depends on the namespace service.
- **Root cause:** Both REST value validators reject only CR/LF. Lance 12.0.0 uses HeaderValue::from_str and inserts only successfully parsed headers without propagating failures.
- **Why existing tests missed it:** LanceCatalogPropertiesTest covers CR/LF but no other C0/DEL characters. LanceRestCatalogTest checks ordinary headers; test_lance_rest_catalog covers authentication transitions and header aliases without SQL control escapes. Add CREATE/ALTER negatives, legal-value controls, native HTTP HTAB assertions and SQL escape cases. The FE runner and External pipeline include these suites.
- **Fix:** Share one local predicate rejecting C0 controls except HTAB, and DEL. Preserve the existing null/nonblank checks, error messages and raw values; never strip bytes or include credential values in errors.
- **Other paths and branches:** Extra headers, bearer tokens and API keys are covered here. Filesystem catalogs, BE options and protocols are unchanged. The equivalent CR/LF-only validators on branch-4.1/4.2 need a separate fe-core adaptation; branch-3.1/4.0 have no Lance REST header properties.

### Testing

- Four new tests ran against unchanged production at ccbffd6 through run-fe-ut.sh: the two rejection tests failed on missing exceptions, while both legal-value controls passed, with zero errors or skips.
- With the fix, `run-fe-ut.sh --run 'org.apache.doris.connector.lance.*Test'` passed all 146 Lance tests locally on macOS aarch64/JDK 17.0.19, with zero failures, errors or skips. Coverage includes the new CREATE/ALTER negatives, unchanged legal tabs/spaces/non-ASCII property values, actual JNI HTTP headers in both credential modes, and the existing REST/S3/OSS tests.
- Added SQL control-escape negatives have not been run against a local cluster; expected-output files are unchanged.

### Release note

None

### Check List (For Author)

- Behavior changed: No
- Does this need documentation: Yes (include the HTTP header-value restriction in the feature PR's Lance REST documentation plan)
- Pre-submission status: Partially verified: the added SQL control-escape cases have not run against a local cluster

### AI Disclosure

- Tool: Codex (GPT-6)
- Generated: code, tests and this description
- Human review: not stated
@morningman

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Static review of all 28 changed paths at exact PR head 5471c9e. Three new findings are included inline: response-controlled REST table URIs/storage endpoints bypass the catalog-only SSRF gate; REST-vended pass-through credentials are omitted from Lance error sanitization; and one-sided OSS credentials can be inferred as anonymous or late-failing signing.

Critical checkpoints: the REST/vended/OSS goal is implemented through the existing lazy namespace, snapshot, option-merge, FE-to-BE scan, and native reader paths, but the three inline defects affect security and correctness. Scope remains focused in the Lance connector and its Docker/regression fixtures. Existing close/lease synchronization, namespace listing locks, TCCL/resource cleanup, statement memoization, managed-version refusal, and error classification were traced without another concrete defect. No Thrift/Protobuf, shared SPI, storage format, transaction, write, or global configuration change is present. Filesystem/REST, S3/OSS/pass-through, catalog/vended, FE metadata, and BE scan paths were checked for parallel behavior and option parity.

Tests, fixtures, deterministic outputs, and negative cases were inspected statically; no builds, tests, benchmarks, Compose startup, or runtime/cloud validation was executed. No additional user focus was supplied. Existing inline P2 threads were rechecked at this head and are not duplicated; no existing P0/P1 finding remains applicable, so existing_blocking_comment_ids is empty.

Review converged after 2 rounds: all assigned reviewers returned NO_NEW_VALUABLE_FINDINGS in the challenge round, every risk/candidate has an explicit disposition, and all changed-file scope was covered.

Review converged after 2 round(s).

new DescribeTableRequest().id(tableId).withTableUri(true).vendCredentials(vendCredentials));
if (Boolean.TRUE.equals(table.getIsOnlyDeclared())) {
throw new DorisConnectorException("Lance table is declared in the namespace but has no data yet");
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Apply the SSRF policy to namespace-vended destinations

vendCredentials(true) lets the REST DescribeTable response choose both table_uri and storage_options. The S3/OSS normalizers preserve vended endpoint values, and this map is used by FE Dataset.open and sent to BE in TLanceScanParams, but PluginDrivenExternalCatalog only SSRF-checks literal catalog properties during CREATE/ALTER. A non-SUPER catalog owner can therefore use a controllable or allowed namespace response such as s3://bucket/... with endpoint=http://127.0.0.1:... (or a local/HTTP URI) to make FE/BE connect to an unpoliced destination. Validate every response-controlled URI/endpoint through the operator SSRF policy, or restrict them to trusted bindings, on both FE and BE before opening it.

this.catalogSecrets = properties.secretValues();
}

List<String> listDatabaseNames() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Mask vended pass-through credentials in Lance errors

REST DescribeTable storage options are copied into LanceTableAccess; for Azure/GCS and other pass-through schemes, LancePassThroughStorageProvider leaves credential keys such as token or azure_storage_sas_token unchanged. readTable then calls LanceErrorMessages.sanitize with those options, but its runtime sensitive-key list only masks AWS and OSS names, while catalogSecrets here covers only static catalog properties. If the native provider includes the token/SAS in a failed open, the connector returns it in the user-facing error/log. Mask credential-bearing vended option values, including pass-through aliases, before exposing provider errors and add a failure case for one.

private static boolean hasSigningConfiguration(Map<String, String> options) {
return StringUtils.isNotEmpty(options.get(ACCESS_KEY_ID));
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Reject incomplete OSS credential pairs before inferring anonymous access

hasSigningConfiguration only tests oss_access_key_id. When a REST namespace vends just access_key_secret, normalization leaves that secret in the map, but this code infers allow_anonymous=true and skip_signature=true, so the request silently becomes unsigned. A map with only an access key takes the opposite path without a secret and fails later in the native provider. Validate the merged OSS options as an all-or-none access/secret pair before deriving authentication flags, and cover both one-sided responses.

### Background

Lance REST namespaces return dataset locations and storage options. Doris merges those options with catalog settings before opening a dataset, and the FE and BE use the resulting map. Provider failures pass through a sanitizer before reaching the user or the FE log.

### What problem does this PR solve?

Issue Number: apache#70680
Related PR: apache#70725 (ports REST namespaces and OSS to the master connector)
PR Type: Bugfix

Problem Summary:

Vended pass-through credentials such as `token` and `azure_storage_sas_token` remain visible when a provider error echoes them. OSS also accepts an incomplete final access/secret pair: a secret-only response becomes anonymous, while an access-only response fails later in the native signer. Recognize credential-bearing runtime option names and reject incomplete OSS identities after merging, while preserving valid anonymous and signed access.

### Details

- **Frequency:** Always for the reproduced sanitizer input and incomplete merged OSS pairs. Actual disclosure depends on whether the provider includes a credential in its error; no remote cloud disclosure is claimed.
- **Root cause:** The sanitizer enumerates only six AWS/OSS option keys. OSS has no merged-option validation and infers signing solely from the access key.
- **Why existing tests missed it:** `LanceErrorMessagesTest` covers AWS/OSS and REST secrets, while `LanceStorageOptionsTest` covers complete and empty OSS pairs. `test_lance_rest_catalog` uses complete vended S3 credentials and REST authentication errors. The new unit cases run through the option merge and sanitizer; `run-fe-ut.sh` includes the Lance module.
- **Fix:** Reuse the SPI's case-insensitive sensitive-key matcher for runtime credentials. Implement the existing post-merge validation hook for OSS, before inferring authentication flags. Catalog-completed pairs and both-empty credentials retain their existing behavior.
- **Other paths and branches:** The sanitizer still covers AWS/OSS and now covers pass-through aliases without modifying storage options. No SPI, BE, IDL or persistence change. Both patterns also exist in the old fe-core Lance implementation on the inspected `branch-4.1` and `branch-4.2` refs and need separate adaptation; `branch-3.1` and `branch-4.0` have no Lance datasource directory. The defects entered this master port in apache#70725.

### Testing

- Three new tests ran through `run-fe-ut.sh` on unchanged production at `5471c9ebe0e`: all three failed on the target assertions, with zero errors or skips. The failures were an exposed token and two accepted incomplete OSS identities.
- With the fix, all 149 Lance tests passed locally through `run-fe-ut.sh --run 'org.apache.doris.connector.lance.*Test'` on macOS aarch64/JDK 17.0.19, with zero failures, errors or skips, including actual JNI REST/S3/OSS tests. No new SQL cluster regression or remote Azure/GCS/OSS run was performed.

### Notes for Reviewers

Runtime destinations returned by a connected namespace retain the repository's trusted-metadata contract. The catalog gate explicitly checks literal CREATE/ALTER endpoints at statement time; a transitive runtime FE/BE policy is a separate scope.

### Release note

None

### Check List (For Author)

- Behavior changed: No
- Does this need documentation: No
- Pre-submission status: Partially verified: no new cluster regression or remote cloud run

### AI Disclosure

- Tool: Codex (GPT-6)
- Generated: code, tests and this description
- Human review: not stated
@morningman

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Static review of all 30 changed paths in #70725 at bf576cd. No additional actionable findings. Review converged after two rounds, including independent REST, storage/fixture, and credential-risk review and a final challenge of the frozen payload.

Applicable code-review checkpoints:

  • Goal and evidence: REST namespace access, vended storage options, and OSS support are implemented through the connector. Property, native REST/signer, and SQL tests cover the main positive and negative paths by inspection; none were executed for this review.
  • Scope and clarity: production changes stay within Lance; the remaining changes provide its tests, fixture, port settings, and expected output. No connector-specific engine branch or shared SPI expansion was added.
  • Concurrency: provider singletons are stateless and option maps are per read. Existing namespace synchronization and call leases protect initialization and close; no new thread or lock order was introduced.
  • Lifecycle: lazy initialization preserves replay behavior, TCCL is restored, per-read allocators/datasets close deterministically, and catalog resources wait for admitted reads. Native tests stop servers and terminate timed-out child processes.
  • Configuration: new REST catalog properties are validated on CREATE and the merged ALTER candidate. Authentication transitions can clear inactive credentials, header case conflicts fail, and illegal header controls fail. No new global FE setting or session variable needs dynamic propagation.
  • Compatibility: existing filesystem defaults remain. No shared API, function-symbol contract, Thrift/Protobuf field, or storage format changes. The same option vocabulary was checked against the pinned FE and BE native readers; this is source evidence, not a rolling-upgrade execution result.
  • Parallel paths and special conditions: filesystem/REST, S3/OSS, and pass-through providers preserve separate semantics. Alias conflicts, merged credential pairs, token replacement, addressing changes, anonymous selectors, unsupported AssumeRole, OSS-HDFS, and managed/declared table admission were checked. Managed-version tables fail before storage-latest can be read.
  • Test coverage: unit/native cases exercise credential replacement, ambient selectors, actual signature/token headers, endpoint host/path, authentication transitions, error masking, and invalid inputs. SQL cases cover namespace listing, prefixed/unprefixed credentials, scans, and managed-version rejection. Native-library skips explicitly report unverified coverage.
  • Changed results: ordered listing/predicate blocks and single-row aggregates are consistent with the fixture by inspection, including 12 rows and sum(row_id)=78. Output generation and author-reported test runs were not independently executed.
  • Observability: FE errors retain operation/table context with sanitized causes, and the changes add no high-volume logging. Existing native BE diagnostic behavior is unchanged; no additional metrics are needed for these small adapters.
  • Persistence and transactions: raw catalog properties reuse the engine's persistence/rebuild path. No transaction, EditLog schema, or data-write behavior changes.
  • FE/BE propagation and correctness: the statement memo retains one dataset version, schema, fragments, URI, and immutable option map; scan-level options reach TLanceScanParams and the BE opens the pinned version. No new MoW/delete-bitmap or internal transaction-visibility path is involved.
  • Performance and memory: normalization/merging use bounded passes over small maps; no new query-data buffering, unbounded cache, or BE allocation path was added. Existing allocator ownership remains intact.

Existing-thread dispositions: the header-control, header-case, authentication-transition, S3 endpoint/boolean, OSS token/selector/addressing/pair, and pass-through FE masking findings are addressed at this head. In particular, P1 comment 4628300986 is fixed. P1 comment 4628300730 concerns destinations supplied by external namespace metadata, which the repository threat model treats as trusted; it is not retained as a confirmed blocking finding. No existing P0/P1 finding is independently confirmed as an in-scope blocker, and no duplicate inline comments are posted.

User focus: no additional focus was supplied. Static review coverage is complete with no unresolved candidates. Validation limits remain: no builds, tests, containers, JNI calls, or remote OSS/Linux/cluster checks were run. The public MinIO bucket means SQL scan success alone does not prove signing enforcement; native signer tests provide the more specific assertions, inspected only here. Long-running credential refresh remains outside the documented static-option design.

Review converged after 2 round(s).

@morningman

Copy link
Copy Markdown
Contributor Author

run buildall

1 similar comment
@morningman

Copy link
Copy Markdown
Contributor Author

run buildall

@morningman

Copy link
Copy Markdown
Contributor Author

run buildall

@morningman

Copy link
Copy Markdown
Contributor Author

run compile

@morningman
morningman merged commit 16bbdb8 into apache:master Nov 21, 2026
69 of 70 checks passed
morningman added a commit to morningman/doris that referenced this pull request Nov 21, 2026
### Background

On master, `lance` catalogs are served by the `fe-connector-lance` plugin: FE lists the fragments (data files) of the pinned dataset version and plans one scan range per fragment, and BE reads them through lance-c. A dataset may carry scalar indexes (BTREE, BITMAP, LABEL_LIST) split into segments, each covering some fragments. lance-c can apply a Substrait filter, a row limit and one index segment per scan, and master's BE reader (apache#69581) passes them on from `TLanceScanParams` and `TLanceFileDesc`, but the plugin sends none of them yet.

This is the third of four PRs porting the Lance read path (apache#70680).

### What problem does this PR solve?

Issue Number: apache#70680
Related PR: apache#70725 (REST catalogs and OSS, the second PR; this builds on it), apache#70681 (the plugin, the first PR), apache#70369 (ARRAY literals as element lists, which `arrays_overlap` needs), apache#70372 (marks UDF calls, which this keeps in Doris), apache#69581 (the BE Lance reader, which applies what this PR sends), apache#65730, apache#66608, apache#66999, apache#67051, apache#67650, apache#68687 (the branch-4.x PRs this ports)
PR Type: Feature

Problem Summary:

On master, a Lance catalog scan leaves Lance all the work it could skip: filters run in Doris after lance-c has read every row, lance-c never sees the LIMIT, and COUNT(*) reads every fragment, while 4.1 and 4.2 push all three into Lance. This PR ports 4.2's pushdown to the plugin. Conjuncts that Lance evaluates exactly as Doris does go to lance-c as one Substrait filter and leave the Doris plan; LIMIT reaches every range when no conjunct stays in Doris; COUNT(*) without a filter comes from the manifest's row counts; and a pushed filter that one scalar index can drive gets one range per index segment. For example, on the regression table `doris.predicate_pushdown` (11 rows in 2 fragments), measured on this branch:

| Query | EXPLAIN of the Lance scan |
| --- | --- |
| `... WHERE int32_value = 10 LIMIT 1` | `lancePushdownPredicate=(int32_value = 10)`, `lanceLimit=1`, no `PREDICATES:` line |
| `... WHERE CAST(int32_value AS STRING) = '10' LIMIT 1` | `PREDICATES: (CAST(int32_value[#4] AS text) = '10')`, no `lanceLimit`: Doris still filters, as it filtered every conjunct before this PR |
| `SELECT count(*) ...` | `pushdown agg=COUNT (11)` |
 Most of the diff is tests and their results (68% of the added lines). Query results do not change.

Original authors: @zhangstar333, @Jay-ju and @Gabriel39.

### Details

- **Change map:** +8036 −66 in 115 files: production code +2568 −45, tests +3290 −21 (FE unit tests +1786, regression suites +1177, fixture builders +320, and 73 dataset files of 144 KiB, mostly binary), generated `.out` +2159, build +19. The production code, all in the plugin except one session variable, in reading order:
  1. Predicate translation (+1,135): `LancePredicateConverter` (4.2's rules, rewritten for `ConnectorExpression`), `LanceSubstraitSerializer` and `lance_functions.yaml` (4.2's).
  2. Index metadata (+493 −5): `LanceDatasetIndexDiscovery`, `LanceIndexSegmentInfo` and `LanceIndexSegmentGroup` (4.2's, without the vector and full-text parts), and `LanceIndexMetadata`, read once per statement through `LanceCatalogClient` and `LanceStatementScope`.
  3. Planning (+727): `LanceScalarIndexPlanner` (which index segment can drive the filter), `LanceScanPlanner` and `LanceSplitBuilder` (ranges, COUNT carriers, debug grouping), `LanceScanPlan` (what EXPLAIN prints).
  4. Ranges and the provider (+197 −40): `LanceScanRange` (index segment, `use_scalar_index`, limit, COUNT carrier) and `LanceScanPlanProvider` (which conjuncts were pushed, the filter in `TLanceScanParams`, EXPLAIN).
  5. fe-core (+16): the session variable `lance_fragments_per_split`, declared there as the Fluss connector's `fluss_union_read_mode` is. Build: `io.substrait:core` 0.40.0 (Apache-2.0, the version 4.x pins).
- **Scope:** Pushed, as on 4.2: comparisons (`<=>` included) between a column and a literal, `[NOT] IN` lists without NULL, `IS [NOT] NULL`, `LIKE` without a backslash, `starts_with`, `ends_with`, boolean columns, `AND` / `OR` / `NOT` whose operands all convert, and `array_contains` / `arrays_overlap` on string arrays with non-NULL needles; on bool, integer, float32/64, decimal128, utf8, date32 and zone-less timestamp(s/ms/us) columns. Only builtin calls are translated: a Java or Python UDF with one of these names stays in Doris, as on 4.2. The rest stays in Doris under `PREDICATES:`, such as CASTs, comparisons with NULL and other column types. Index segments: BTREE, BITMAP and LABEL_LIST, for a positive predicate within lance-c's bounds (128 nodes, depth 32).
- **Design:** A conjunct is translated whole or not at all, and only exact translations are reported pushed (`ScanNodePropertiesResult.withPushdownTracking`, as the Elasticsearch connector does), so the engine drops exactly those from the Doris residuals, as 4.2 did. Where the SPI forces a different shape from 4.2:
  - CASTs stay in Doris (`supportsCastPredicatePushdown` returns false), as on 4.2: the SPI default strips the CAST and would let Lance compare in the column's own type.
  - UDFs: 4.2 checked `TFunctionBinaryType.BUILTIN`; here the converter refuses a `ConnectorFunctionCall` whose `isBuiltin()` is false (apache#70372).
  - No plan state on the provider: the engine memoizes it by table handle, which the snapshot pin replaces, so EXPLAIN (`getScanNodePropertiesResult`) and the ranges (`planScan`) are planned deterministically from the same inputs.
  - COUNT(*) carriers: 4.2 makes min(fragments, instances × backends), and the SPI gives neither count, so 10,000 rows or more get one carrier per fragment and fewer get one. Each carrier keeps its fragments for a BE that falls back to scanning.
  - Index metadata is read only when a segment could be planned (4.2 reads it for every scan), so `DESC` and plain scans don't fail on an unreadable index.
- **Usage:** Nothing to enable:

  ```sql
  EXPLAIN SELECT row_id FROM lance_s3.db.items WHERE row_id >= 2 AND label = 'a' LIMIT 10;
  --   lanceFragmentGrouping=FRAGMENT
  --   lanceLimit=10
  --   lancePushdownPredicate=(row_id >= 2) AND (label = 'a')
  -- and no PREDICATES: line, since nothing is left for Doris. When one scalar index drives the
  -- filter, lanceFragmentGrouping=INDEX_SEGMENT and lanceGroupingIndex=<index> appear instead.

  EXPLAIN SELECT COUNT(*) FROM lance_s3.db.items;  -- pushdown agg=COUNT (<rows>)

  SET lance_fragments_per_split = 2;  -- debugging: two fragments per range, no index segments
  ```

- **Default behavior:** On for every Lance catalog scan; `lance_fragments_per_split` defaults to 0 (automatic grouping) and rejects negative values.
- **Compatibility:** No Thrift, Protobuf or persisted-metadata change, and no connector SPI change, so the plugin API version stays as it is: the plugin fills fields that master's BE has read since apache#69581 and 4.2's FE sends (`lance_substrait_filter`; `limit`, `index_segment_uuids` and `use_scalar_index` in `TLanceFileDesc`; the generic `table_level_row_count`). `lance_fragments_per_split` keeps 4.2's name, default and checker, but is visible: the engine hands connectors only visible session variables (`VariableMgr.toMap`).
- **Follow-up plan:** PR 4 adds the session and table-access caches and the profile counters; vector and full-text search, index inspection and the file TVF follow, in the same issue. Later 4.2 changes to these files (apache#68813, apache#69625 and the search work) are ported with the next batch.

### Testing

- `fe-connector-lance` unit tests, 213, locally on this commit with lance-core's JNI library loaded (none skipped): 4.2's converter cases on `ConnectorExpression` input, its two Java-UDF cases included, plus new ones for DECIMAL exactness, integer ranges and UDFs named like each translated builtin (34); all 9 of 4.2's scalar-index planner cases; 13 of its scan-node cases (the non-search planning ones; one now expects a COUNT carrier per fragment); its two Thrift contract cases; and the provider's residual, LIMIT and COUNT rules.
- 9 mutations, each run against the unchanged tests: every one fails its target tests (a UDF translated by name, a truncated DECIMAL, NULL needles dropped, `<=>` without `IS NOT NULL`, an escaped LIKE pushed, no integer range check, a LIMIT past a residual, every conjunct claimed pushed, COUNT despite a filter).
- fe-core, 55 tests: `SessionVariablesTest` (the variable reaches connectors and rejects negative values), `ExprToConnectorExpressionConverterTest`, `ExprToConnectorFunctionCallTest` and `PluginDrivenScanNodeCastPredicateTest`. The FE build ran checkstyle and the connector import gate.
- Regression, locally, with FE and an ASAN BE built from this commit, the committed REST stub, and a host S3 endpoint that verifies SigV4 and serves the committed fixture: the six new suites, PR 1's `test_lance_catalog_all_types` and PR 2's `test_lance_rest_catalog` pass against the committed `.out` files (8 suites, 0 failed, 0 skipped). The new `.out` files are branch-4.2's results block for block: int 176/176, scalar 178/178, optimize_count 10/10, runtime_filter 1/1 (its two vector-search blocks come with search). In CI, the External pipeline runs them.

### Notes for Reviewers

- Master's plugin scan node prints Doris residuals as `PREDICATES:`, not 4.x's `predicates:`, so the 12 ported checks use that spelling (`notContains "predicates:"` would always pass); `test_lance_runtime_filter_pushdown` keeps only 4.2's non-search case and asserts `CONNECTOR: lance`.
- DECIMAL: 4.2 relies on `ExpressionCreator.decimal` throwing, but it truncates to the column's scale (`12.505` becomes `12.50`), so a literal is pushed only when the column's type holds it exactly; the unit test fails without the check.
- `arrays_overlap` also requires a string element type: LARGEINT, IPv4 and JSON elements arrive as Strings too (apache#70369).
- The fixture is committed instead of built by Spark: the `doris` namespace's `__manifest`, `predicate_pushdown` (4.2's rows, two appends), and 4.2's `vs_ivf_pq_f32` (read by `test_lance_fragment_grouping`), `multi_frag.lance` and `predicate_arrays/` unchanged. `lance_build_predicate_pushdown.py` rebuilds or `--check`s it with 4.2's pinned writer.
- The extension URI of `array_has` names the plugin's `lance_functions.yaml`; lance-c resolves functions by name.

### Release note

The session variable `lance_fragments_per_split` (default 0) is a debugging override for Lance catalog scans: a positive value groups that many fragments into each scan range and turns index-segment ranges off. Unlike 4.1 and 4.2, `SHOW VARIABLES` lists it.

### Check List (For Author)

- Behavior changed: No
- Does this need documentation: No
- Pre-submission status: Partially verified: the regression suites ran locally against a host S3 substitute and the REST stub, not yet in the External pipeline

### AI Disclosure

- Tool: Claude Code (Claude Opus 5.5)
- Generated: code, tests, the fixture builder, this description
- Human review: The author reviewed part of the changes.
- Prompts: The author asked to port the branch-4.2 Lance FE read path to master as a connector plugin in four PRs, of which this is the third; approved handing ARRAY literals to connectors as element lists (apache#70369) and marking UDF calls (apache#70372) in separate PRs first; had the regression fixture committed as a dataset rather than built by Spark; and asked to build this PR on apache#70725 before it merged and to rebase it onto master once it did.

Co-authored-by: zhangstar333 <zhangsida@selectdb.com>
Co-authored-by: jay <qingfengyouchen@163.com>
Co-authored-by: Gabriel <liwenqiang@selectdb.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
morningman added a commit that referenced this pull request Nov 23, 2026
…#70827)

### Background

On master, `lance` catalogs are served by the `fe-connector-lance`
plugin: FE lists the fragments (data files) of the pinned dataset
version and plans one scan range per fragment, and BE reads them through
lance-c. A dataset may carry scalar indexes (BTREE, BITMAP, LABEL_LIST)
split into segments, each covering some fragments. lance-c can apply a
Substrait filter, a row limit and one index segment per scan, and
master's BE reader (#69581) passes them on from `TLanceScanParams` and
`TLanceFileDesc`, but the plugin sends none of them yet.

This is the third of four PRs porting the Lance read path (#70680).

### What problem does this PR solve?

Issue Number: #70680
Related PR: #70725 (REST catalogs and OSS, the second PR; this builds on
it), #70681 (the plugin, the first PR), #70369 (ARRAY literals as
element lists, which `arrays_overlap` needs), #70372 (marks UDF calls,
which this keeps in Doris), #69581 (the BE Lance reader, which applies
what this PR sends), #65730, #66608, #66999, #67051, #67650, #68687 (the
branch-4.x PRs this ports)
PR Type: Feature

Problem Summary:

On master, a Lance catalog scan leaves Lance all the work it could skip:
filters run in Doris after lance-c has read every row, lance-c never
sees the LIMIT, and COUNT(*) reads every fragment, while 4.1 and 4.2
push all three into Lance. This PR ports 4.2's pushdown to the plugin.
Conjuncts that Lance evaluates exactly as Doris does go to lance-c as
one Substrait filter and leave the Doris plan; LIMIT reaches every range
when no conjunct stays in Doris; COUNT(*) without a filter comes from
the manifest's row counts; and a pushed filter that one scalar index can
drive gets one range per index segment. For example, on the regression
table `doris.predicate_pushdown` (11 rows in 2 fragments), measured on
this branch:

| Query | EXPLAIN of the Lance scan |
| --- | --- |
| `... WHERE int32_value = 10 LIMIT 1` |
`lancePushdownPredicate=(int32_value = 10)`, `lanceLimit=1`, no
`PREDICATES:` line |
| `... WHERE CAST(int32_value AS STRING) = '10' LIMIT 1` | `PREDICATES:
(CAST(int32_value[#4] AS text) = '10')`, no `lanceLimit`: Doris still
filters, as it filtered every conjunct before this PR |
| `SELECT count(*) ...` | `pushdown agg=COUNT (11)` |
Most of the diff is tests and their results (68% of the added lines).
Query results do not change.

Original authors: @zhangstar333, @Jay-ju and @Gabriel39.

### Details

- **Change map:** +8036 −66 in 115 files: production code +2568 −45,
tests +3290 −21 (FE unit tests +1786, regression suites +1177, fixture
builders +320, and 73 dataset files of 144 KiB, mostly binary),
generated `.out` +2159, build +19. The production code, all in the
plugin except one session variable, in reading order:
1. Predicate translation (+1,135): `LancePredicateConverter` (4.2's
rules, rewritten for `ConnectorExpression`), `LanceSubstraitSerializer`
and `lance_functions.yaml` (4.2's).
2. Index metadata (+493 −5): `LanceDatasetIndexDiscovery`,
`LanceIndexSegmentInfo` and `LanceIndexSegmentGroup` (4.2's, without the
vector and full-text parts), and `LanceIndexMetadata`, read once per
statement through `LanceCatalogClient` and `LanceStatementScope`.
3. Planning (+727): `LanceScalarIndexPlanner` (which index segment can
drive the filter), `LanceScanPlanner` and `LanceSplitBuilder` (ranges,
COUNT carriers, debug grouping), `LanceScanPlan` (what EXPLAIN prints).
4. Ranges and the provider (+197 −40): `LanceScanRange` (index segment,
`use_scalar_index`, limit, COUNT carrier) and `LanceScanPlanProvider`
(which conjuncts were pushed, the filter in `TLanceScanParams`,
EXPLAIN).
5. fe-core (+16): the session variable `lance_fragments_per_split`,
declared there as the Fluss connector's `fluss_union_read_mode` is.
Build: `io.substrait:core` 0.40.0 (Apache-2.0, the version 4.x pins).
- **Scope:** Pushed, as on 4.2: comparisons (`<=>` included) between a
column and a literal, `[NOT] IN` lists without NULL, `IS [NOT] NULL`,
`LIKE` without a backslash, `starts_with`, `ends_with`, boolean columns,
`AND` / `OR` / `NOT` whose operands all convert, and `array_contains` /
`arrays_overlap` on string arrays with non-NULL needles; on bool,
integer, float32/64, decimal128, utf8, date32 and zone-less
timestamp(s/ms/us) columns. Only builtin calls are translated: a Java or
Python UDF with one of these names stays in Doris, as on 4.2. The rest
stays in Doris under `PREDICATES:`, such as CASTs, comparisons with NULL
and other column types. Index segments: BTREE, BITMAP and LABEL_LIST,
for a positive predicate within lance-c's bounds (128 nodes, depth 32).
- **Design:** A conjunct is translated whole or not at all, and only
exact translations are reported pushed
(`ScanNodePropertiesResult.withPushdownTracking`, as the Elasticsearch
connector does), so the engine drops exactly those from the Doris
residuals, as 4.2 did. Where the SPI forces a different shape from 4.2:
- CASTs stay in Doris (`supportsCastPredicatePushdown` returns false),
as on 4.2: the SPI default strips the CAST and would let Lance compare
in the column's own type.
- UDFs: 4.2 checked `TFunctionBinaryType.BUILTIN`; here the converter
refuses a `ConnectorFunctionCall` whose `isBuiltin()` is false (#70372).
- No plan state on the provider: the engine memoizes it by table handle,
which the snapshot pin replaces, so EXPLAIN
(`getScanNodePropertiesResult`) and the ranges (`planScan`) are planned
deterministically from the same inputs.
- COUNT(*) carriers: 4.2 makes min(fragments, instances × backends), and
the SPI gives neither count, so 10,000 rows or more get one carrier per
fragment and fewer get one. Each carrier keeps its fragments for a BE
that falls back to scanning.
- Index metadata is read only when a segment could be planned (4.2 reads
it for every scan), so `DESC` and plain scans don't fail on an
unreadable index.
- **Usage:** Nothing to enable:

  ```sql
EXPLAIN SELECT row_id FROM lance_s3.db.items WHERE row_id >= 2 AND label
= 'a' LIMIT 10;
  --   lanceFragmentGrouping=FRAGMENT
  --   lanceLimit=10
  --   lancePushdownPredicate=(row_id >= 2) AND (label = 'a')
-- and no PREDICATES: line, since nothing is left for Doris. When one
scalar index drives the
-- filter, lanceFragmentGrouping=INDEX_SEGMENT and
lanceGroupingIndex=<index> appear instead.

EXPLAIN SELECT COUNT(*) FROM lance_s3.db.items; -- pushdown agg=COUNT
(<rows>)

SET lance_fragments_per_split = 2; -- debugging: two fragments per
range, no index segments
  ```

- **Default behavior:** On for every Lance catalog scan;
`lance_fragments_per_split` defaults to 0 (automatic grouping) and
rejects negative values.
- **Compatibility:** No Thrift, Protobuf or persisted-metadata change,
and no connector SPI change, so the plugin API version stays as it is:
the plugin fills fields that master's BE has read since #69581 and 4.2's
FE sends (`lance_substrait_filter`; `limit`, `index_segment_uuids` and
`use_scalar_index` in `TLanceFileDesc`; the generic
`table_level_row_count`). `lance_fragments_per_split` keeps 4.2's name,
default and checker, but is visible: the engine hands connectors only
visible session variables (`VariableMgr.toMap`).
- **Follow-up plan:** PR 4 adds the session and table-access caches and
the profile counters; vector and full-text search, index inspection and
the file TVF follow, in the same issue. Later 4.2 changes to these files
(#68813, #69625 and the search work) are ported with the next batch.

### Testing

- `fe-connector-lance` unit tests, 213, locally on this commit with
lance-core's JNI library loaded (none skipped): 4.2's converter cases on
`ConnectorExpression` input, its two Java-UDF cases included, plus new
ones for DECIMAL exactness, integer ranges and UDFs named like each
translated builtin (34); all 9 of 4.2's scalar-index planner cases; 13
of its scan-node cases (the non-search planning ones; one now expects a
COUNT carrier per fragment); its two Thrift contract cases; and the
provider's residual, LIMIT and COUNT rules.
- 9 mutations, each run against the unchanged tests: every one fails its
target tests (a UDF translated by name, a truncated DECIMAL, NULL
needles dropped, `<=>` without `IS NOT NULL`, an escaped LIKE pushed, no
integer range check, a LIMIT past a residual, every conjunct claimed
pushed, COUNT despite a filter).
- fe-core, 55 tests: `SessionVariablesTest` (the variable reaches
connectors and rejects negative values),
`ExprToConnectorExpressionConverterTest`,
`ExprToConnectorFunctionCallTest` and
`PluginDrivenScanNodeCastPredicateTest`. The FE build ran checkstyle and
the connector import gate.
- Regression, locally, with FE and an ASAN BE built from this commit,
the committed REST stub, and a host S3 endpoint that verifies SigV4 and
serves the committed fixture: the six new suites, PR 1's
`test_lance_catalog_all_types` and PR 2's `test_lance_rest_catalog` pass
against the committed `.out` files (8 suites, 0 failed, 0 skipped). The
new `.out` files are branch-4.2's results block for block: int 176/176,
scalar 178/178, optimize_count 10/10, runtime_filter 1/1 (its two
vector-search blocks come with search). In CI, the External pipeline
runs them.

### Notes for Reviewers

- Master's plugin scan node prints Doris residuals as `PREDICATES:`, not
4.x's `predicates:`, so the 12 ported checks use that spelling
(`notContains "predicates:"` would always pass);
`test_lance_runtime_filter_pushdown` keeps only 4.2's non-search case
and asserts `CONNECTOR: lance`.
- DECIMAL: 4.2 relies on `ExpressionCreator.decimal` throwing, but it
truncates to the column's scale (`12.505` becomes `12.50`), so a literal
is pushed only when the column's type holds it exactly; the unit test
fails without the check.
- `arrays_overlap` also requires a string element type: LARGEINT, IPv4
and JSON elements arrive as Strings too (#70369).
- The fixture is committed instead of built by Spark: the `doris`
namespace's `__manifest`, `predicate_pushdown` (4.2's rows, two
appends), and 4.2's `vs_ivf_pq_f32` (read by
`test_lance_fragment_grouping`), `multi_frag.lance` and
`predicate_arrays/` unchanged. `lance_build_predicate_pushdown.py`
rebuilds or `--check`s it with 4.2's pinned writer.
- The extension URI of `array_has` names the plugin's
`lance_functions.yaml`; lance-c resolves functions by name.

Co-authored-by: zhangstar333 <zhangsida@selectdb.com>
Co-authored-by: jay <qingfengyouchen@163.com>
Co-authored-by: Gabriel <liwenqiang@selectdb.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
morningman added a commit to morningman/doris that referenced this pull request Nov 23, 2026
… 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>
morningman added a commit that referenced this pull request Nov 23, 2026
… FE time in the profile (#70830)

### 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 (#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 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 (#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:** +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:
1. Catalog generations and the shared Session (+302 −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 (+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:**

  | | 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 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 #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: 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 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, and two more (REFRESH CATALOG dropping only the access
cache, `refresh()` retiring nothing) turn the same-URI test 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 #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 #70827's plugin) and a negative TTL in
`test_lance_catalog_all_types`.
- After #70827 merged, this PR's commit was replayed onto master without
conflicts and with the same patch. Master's commits since #70827's base
change none of the plugin's modules, its dependencies or the Lance
suites. The unit tests ran again on the new base (254 before the second
commit, 255 with it); the regression suites and the request counts were
not re-run.

### Notes for Reviewers

- Caffeine rather than fe-connector-cache's `MetaCache`, which expires
entries after their last access: #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.
- REFRESH TABLE and DATABASE keep the Session, as on 4.2, which is safe
while a dataset lives: manifests, schemas and fragment lists are cached
by version and the manifest's e-tag. A dataset deleted and written again
at the same URI starts its versions over, though, and with V1 manifest
names (`_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 of
`LanceConnector.invalidateDb` says so.
- 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.

Co-authored-by: zhangstar333 <zhangsida@selectdb.com>
Co-authored-by: Gabriel <liwenqiang@selectdb.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
morningman added a commit to morningman/doris that referenced this pull request Nov 23, 2026
…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>
morningman added a commit that referenced this pull request Nov 24, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants