Skip to content

[improvement](lance) Balance fragment splits by row count - #66597

Merged
yiguolei merged 2 commits into
apache:branch-4.1from
Jay-ju:jay-ju/lance-distributed-scan-pr1
Aug 11, 2026
Merged

yiguolei merged 2 commits into
apache:branch-4.1from
Jay-ju:jay-ju/lance-distributed-scan-pr1

Conversation

@Jay-ju

@Jay-ju Jay-ju commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Lance fragment metadata already carries the visible row count, and LanceSplit stores it as selfSplitWeight. However, FileSplit#getSplitWeight only uses that value when a common targetSplitSize is set. As a result, all Lance fragments currently have the same standard scheduling weight regardless of row count, which can cause uneven scan work across BEs when fragment sizes differ.

This PR uses the largest fragment row count as one standard split and assigns smaller fragments a proportional weight. It changes only FE scheduling metadata:

  • split count and fragment order are unchanged;
  • dataset version and fragment IDs are unchanged;
  • BE scan and query result semantics are unchanged.

Verification

  • Added LanceScanNodeTest covering fragment row counts 1000, 250, and 0, which map to raw split weights 100, 25, and the minimum 1.
  • mvn validate -pl fe-core -am -DskipTests passed for all 15 FE reactor modules with zero Checkstyle violations.
  • The targeted unit test is included for standard Doris CI. The local machine only has JDK 11 and lacks the project-pinned Thrift 0.16 generated sources, while this branch requires JDK 17.

Check List

  • Unit test
  • No protocol change
  • No query result behavior change
  • No documentation change required

@Jay-ju
Jay-ju requested a review from yiguolei as a code owner August 10, 2026 03:37
@Jay-ju

Jay-ju commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

run buildall

@hello-stephen

Copy link
Copy Markdown
Contributor

FE Regression Coverage Report

Increment line coverage 4.86% (9/185) 🎉
Increment coverage report
Complete coverage report

zhangstar333
zhangstar333 previously approved these changes Aug 10, 2026
@github-actions github-actions Bot added the approved Indicates a PR has been approved by one committer. label Aug 10, 2026
@github-actions

Copy link
Copy Markdown
Contributor

PR approved by at least one committer and no changes requested.

@github-actions

Copy link
Copy Markdown
Contributor

PR approved by anyone and no changes requested.

@yiguolei

Copy link
Copy Markdown
Contributor

/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.

Automated code review: changes requested.

Critical checkpoints:

  • Scheduling correctness: the catalog path now produces bounded weights that reach FederationBackendPolicy, but S3/file Lance TVFs still discard fragment row counts and remain equally weighted.
  • Compatibility and performance: FE uses logical rows after deletions, while the pinned BE Lance legacy reader applies deletions only after reading and merging physical batches, so tombstone-heavy legacy fragments can be severely underweighted.
  • Query semantics and protocol: split count/order, pinned version and fragment IDs, scan-range serialization, and the intentional single-split local-TVF/vector-search modes remain unchanged; no query-result or protocol defect was found.
  • Tests: the new unit test covers standard, proportional, and minimum raw weights, but does not cover S3/file TVF parity or deletion-heavy legacy fragments.
  • User focus: no additional focus was supplied; the full PR was reviewed.
  • Completion: the review converged in two rounds with every candidate accepted, deduplicated, or dismissed; two inline issues are attached.

}
splits.add(new LanceSplit(metadata.getDatasetUri(), metadata.getVersion(),
fragment.getId(), fragment.getRowCount()));
targetRows = Math.max(targetRows, Math.max(fragment.getRowCount(), 1));

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] Base legacy-fragment weights on physical scan work

fragment.getRowCount() comes from Java FragmentMetadata#getNumRows(), which is physical rows minus deletions. However, the BE links lance-c 0.1.2/Lance 4.0.1, whose legacy fragment reader reads and merges the projected physical batches before applying the deletion vector. A legacy fragment with 1,000,000 physical rows and 990,000 tombstones can therefore receive only a 1 percent weight even though its scan still does close to a full fragment's I/O/decoding work; compared with the previous equal weights, this can actively co-locate expensive tombstone-heavy fragments. Please use physical rows or another format-aware scan-cost metric for this normalization and cover a deletion-heavy legacy fragment.

for (LanceTableMetadata.LanceFragmentInfo fragment : metadata.getFragments()) {
LanceSplit split = new LanceSplit(metadata.getDatasetUri(), metadata.getVersion(),
fragment.getId(), fragment.getRowCount());
split.setTargetSplitSize(targetRows);

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 S3/file TVF fragment weights in sync

This sets the common target only for catalog-backed LanceScanNode splits. The S3 Lance TVF path loads the same fragment row counts via loadLatestForTvf(), but setLanceTableMetadata() retains only IDs; TVFScanNode#getLanceSplits() then passes rowCount=1 and never sets a target. The file(...) TVF delegates S3 Lance scans to this same path, so both entry points still give every fragment the standard scheduling weight and keep the skew this change is intended to remove. Please retain row counts through the TVF metadata boundary, apply the same normalization there, and add a parity test for that split path.

@hello-stephen

Copy link
Copy Markdown
Contributor

FE Regression Coverage Report

Increment line coverage 4.86% (9/185) 🎉
Increment coverage report
Complete coverage report

… TVF

Address review feedback on fragment split balancing:

- Weight splits by physical rows instead of post-deletion logical rows.
  The pinned BE legacy reader scans and merges physical batches before
  applying the deletion vector, so a tombstone-heavy fragment does close
  to a full fragment's I/O; logical rows underweighted it. LanceFragmentInfo
  now carries physicalRows (rowCount kept for statistics) and both the
  target and per-split weight use it.
- Keep S3/file Lance TVF splits in sync. The TVF path retained only fragment
  ids and passed rowCount=1, leaving every fragment equally weighted.
  ExternalFileTableValuedFunction now retains full fragment info and
  TVFScanNode applies the same physical-row normalization.
- Add a deletion-heavy fragment case and an S3 TVF weight-parity assertion.
@github-actions github-actions Bot removed the approved Indicates a PR has been approved by one committer. label Aug 10, 2026
@Jay-ju

Jay-ju commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

@yiguolei @zhangstar333 mind taking a look when you have a sec? 🙏

@yiguolei

Copy link
Copy Markdown
Contributor

/review

@yiguolei

Copy link
Copy Markdown
Contributor

run buildall

@github-actions github-actions Bot added the approved Indicates a PR has been approved by one committer. label Aug 11, 2026
@github-actions

Copy link
Copy Markdown
Contributor

PR approved by at least one committer and no changes requested.

@yiguolei

Copy link
Copy Markdown
Contributor

@Jay-ju Sure. And you can add more features to doris lance catalog for example hybrid search.

@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.

Requesting changes for two P2 scheduling correctness gaps that remain after the legacy-row and S3/file parity fixes.

  1. The new loader consumes raw cached physical_rows for a supported broken v0.8.0 migration case even though the pinned Lance implementation deliberately distrusts that value.
  2. The unconditional physical-row metric fixes legacy fragments but overweights deletion-heavy stable-format fragments, whose reader plans valid ranges before data I/O.

I reviewed all nine changed files and traced catalog, S3, delegated file(...), local, and external-search paths through fixed-version fragment serialization and the BE reader. Catalog/S3/file(...) now share the same immutable fragment snapshot and normalization; local/search exclusions are intentional. Split count/order, thrift identifiers, query protocol, zero/extreme normalization, and the generic scheduler's one-standard-split tolerance did not reveal another defect. The new unit tests verify handcrafted DTO weights but do not exercise either raw-versus-trusted migration metadata or a real stable reader. No build or test was run, as required by the supplied review constraints.

The prior two inline threads were rechecked live: S3/file parity is addressed, and legacy underweighting is addressed when physical metadata is trustworthy. The two comments below are distinct follow-up failures. Review converged after two rounds; all other candidates were dismissed with evidence or duplicate-covered.

fragments.add(new LanceTableMetadata.LanceFragmentInfo(
fragment.getId(), fragment.metadata().getNumRows()));
fragment.getId(), fragment.metadata().getNumRows(),
fragment.metadata().getPhysicalRows()));

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] Fence broken migration metadata before trusting physicalRows

The pinned Lance implementation does not trust cached physical_rows when manifest.writer_version is absent: it opens a data file instead because the v0.8.0 migration from older deletion-bearing datasets could store a post-deletion count there. Java Dataset#getFragments() exports raw fragment metadata, so getPhysicalRows() here bypasses that fence. For that supported migrated dataset class, a deletion-heavy fragment can remain severely underweighted even though the BE derives and reads its actual physical rows. This is distinct from the earlier logical-row thread: switching from getNumRows() to this raw field still fails when the populated cache is unvouched. Please use a trust-aware SDK/JNI count or retain standard weights for such manifests, and cover the broken migration fixture.

List<Split> splits = new ArrayList<>(plannedFragments);
for (LanceTableMetadata.LanceFragmentInfo fragment : metadata.getFragments()) {
LanceSplit split = new LanceSplit(metadata.getDatasetUri(), metadata.getVersion(),
fragment.getId(), fragment.getPhysicalRows());

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 stable-format fragments on a deletion-aware weight

Physical rows match the legacy reader, but Lance 4.0.1 dispatches stable storage to a different read path. Its FilteredReadExec turns the deletion vector into valid ranges and passes those ranges to read_ranges() before data I/O. For a multi-page stable fragment with 1,000,000 physical rows and 990,000 contiguous tombstones, the reader can skip pages wholly covered by the deleted region and read/decode only the live ranges plus boundary-page and deletion-metadata overhead, yet this assigns the same weight as a fully live fragment. The earlier thread covered legacy underweighting; this is the opposite failure in the separate stable path. Please carry a format-aware work metric through both catalog and TVF builders and cover a deletion-heavy stable fixture.

@hello-stephen

Copy link
Copy Markdown
Contributor

FE Regression Coverage Report

Increment line coverage 19.50% (31/159) 🎉
Increment coverage report
Complete coverage report

@yiguolei

Copy link
Copy Markdown
Contributor

skip buildall

morningman added a commit that referenced this pull request Nov 18, 2026
…ogs and basic reads (#70681)

### Background

Lance datasets store schemas, versions and fragment lists in manifests.
FE reads those manifests to plan a query, and BE reads the fragments
through lance-c. Doris 4.1/4.2 provide Lance catalogs in fe-core; master
uses connector plugins and already has the BE reader (#69581) and legacy
image migration (#69575).

### What problem does this PR solve?

Issue Number: #70680
Related PR: #65730, #66581, #66597, #66805 (source read-path changes);
#70338 (secret masking), #70351 (TIMEV2 precision), #69581 (BE reader),
#69575 (legacy images)
PR Type: Feature

Problem Summary:

Master has no plugin serving the `lance` catalog type, so users cannot
query Lance catalogs after upgrading from 4.1/4.2. This ports the first
part of that read path: filesystem catalogs, static S3 credentials,
Arrow type mapping, basic scans and main-chain time travel. The plugin
also needs JNI packaging and resource management; other catalog types
keep their existing behavior.

### Details

- **Change map:** 57 files, +6732/-2: production code +3377, tests
+2974, generated test output +75, build/CI +306/-2. Production has four
parts: property binding and namespace lifetime; schema and version
resolution; S3 storage-option translation shared by FE/BE; fragment scan
planning. Tests cover those contracts, native datasets and a regression
suite. Packaging registers the module, plugin distribution, JNI
replacement and MinIO fixture.
- **Scope:** Local/file and S3 filesystem catalogs; `SHOW
DATABASES/TABLES`, `DESC`, `SELECT`, `FOR VERSION AS OF n`, and `FOR
TIME AS OF 'yyyy-MM-dd HH:mm:ss[.SSS]'`. REST catalogs fail explicitly
until the next PR, including first access to replayed REST catalogs.
Tags, branches, OSS warehouses, pushdown and writes are outside this PR.
S3 access without static AK/SK, including anonymous and credential-chain
access, fails explicitly. AssumeRole is also rejected, even when source
AK/SK are provided.
- **Design:** Follow the existing connector plugins, rather than add
Lance catalog classes to fe-core. The plugin opts into MVCC and memoizes
metadata per statement, so schema, fragments, statistics and BE ranges
use one immutable dataset version. Ordinary query pins retain their
schema across the engine schema-cache boundary; historical statistics
also apply the snapshot to unpinned handles. Time travel compares
manifest commit times at their original precision in the session time
zone. The final S3 endpoint fills both native endpoint coordinates after
namespace options are merged, preventing ambient AWS endpoint overrides
while preserving namespace service-endpoint precedence. Each fragment
becomes one scan range. An in-flight call count delays native resource
disposal after catalog retirement. Proposed in #70680, opened with this
PR; no community design discussion has taken place yet.
- **Usage:**

  ```sql
  CREATE CATALOG lance_s3 PROPERTIES (
      "type" = "lance",
      "warehouse" = "s3://warehouse/lance",
      "s3.endpoint" = "http://127.0.0.1:9000",
      "s3.access_key" = "admin",
      "s3.secret_key" = "password",
      "s3.region" = "us-east-1",
      "use_path_style" = "true"
  );
  SELECT count(*) FROM lance_s3.`default`.all_types FOR VERSION AS OF 1;
  SELECT count(*) FROM lance_s3.`default`.all_types
      FOR TIME AS OF '2026-07-30 10:11:50';
  ```

- **Default behavior:** Enabled by creating a Lance catalog.
`lance.conf` contains the optional
`lance_catalog_arrow_memory_limit_bytes`, default 256 MiB per catalog;
changes require an FE restart.
- **Compatibility:** Preserve the 4.1/4.2 property map and names. Legacy
catalogs use the existing image migration. The Arrow memory setting
moves from fe.conf to lance.conf; copy any customized value. `SHOW
CREATE TABLE` uses `ENGINE=lance`, as other plugins do. No Thrift or
persisted-metadata format changes. BE needs #69581; projecting Arrow
Null, Duration, JSON or bfloat16 fences out smooth-upgrade source BEs.
Newer catalog features remain unsupported during this staged port. Both
cloud and shared-nothing use this planning path; a cloud deployment was
not tested locally.
- **Persistence and failure handling:** Catalog metadata uses the
existing plugin catalog journal/image path; dataset contents are
read-only. The namespace opens lazily, avoiding storage I/O and JNI
loading during replay. Missing versions and unavailable native libraries
fail explicitly. Statement cleanup releases its metadata memo; dropping
or altering a catalog retires its client and closes resources after
active calls finish.
- **Security and privileges:** CREATE_PRIV permits catalog creation;
ALTER_PRIV is required to change its properties. FE and BE make outbound
HTTP requests to the configured S3 endpoint, an SSRF surface. The
provider declares S3-compatible endpoint aliases for the existing
CREATE/ALTER gate when `security_checker_class_name` is configured. REST
credential keys are declared for masking even though REST reads are
deferred. Build-time JNI replacement downloads fixed, checksum-pinned
Lance JNI and Apache Arrow Java source assets.
- **Follow-up plan:** REST/OSS and namespace-vended credentials;
predicate/LIMIT/COUNT pushdown, fragment grouping and scalar indexes;
then session/table caches and profile counters. Search TVFs, index
operations and tag/branch/managed versioning follow separately under
#70680.

### Testing

- Storage/JNI fixes at `536982b`, macOS arm64/JDK 17: all 81 Lance tests
in 14 classes passed, with no skips, through `run-fe-ut.sh --run` and a
scoped `CUSTOM_MVN` wrapper. Checkstyle was enabled and Maven build
cache disabled. Cases include role plus source keys, generic/service
endpoint precedence, explicit HTTP policy, and native HTTP requests
under unrelated AWS endpoint and credential variables.
- On the unfixed `b62c94c`, the same targeted Java tests produced 5
assertion failures across 14 tests with no skips. The native child
actually requested the unrelated endpoint at port 1. The real shell
helper also failed with JAVA_HOME unset; all three JDK-selection cases
pass with the fix.
- Shell packaging tests cover JAVA_HOME, selected JAVA, PATH-only
discovery, jar/platform isolation, checksum/version/runtime gates and
failure atomicity. The real Arrow JNI helper compiled with JAVA_HOME
unset, and the native HTTP test passed using that rebuilt library; JVM
library logs confirmed its path.
- External CI at `536982b` passed 809 of 810 tests. The AssumeRole
negative case failed because its private endpoint selected the MinIO
provider, whose HMAC-only validation ran before Lance. The fixture now
sets `provider=S3` for that catalog and keeps the exact Lance exception
assertion.
- Provider fixture fix, macOS arm64/JDK 17: `run-fe-ut.sh --run` with a
scoped `CUSTOM_MVN` wrapper passed 54 tests in
`LanceStorageOptionsTest`, `S3FileSystemProviderTest`,
`MinioFileSystemProviderTest` and `MinioFileSystemPropertiesTest`, with
no skips, Checkstyle enabled and Maven build cache disabled. A probe
extracted the baseline and candidate catalog properties from the Groovy
suite and used freshly compiled production providers and Lance options:
the baseline reproduced the MinIO rejection; the candidate retained the
role and reached the exact Lance AssumeRole rejection. Groovy parsing
and `git diff --check` passed. The complete SQL suite and full External
rerun remain pending at the new head.
- Earlier validation at `b62c94c` reported 78 Lance tests, 162 Connector
SPI tests and 16 foundation binding tests passing. Initial feature
validation reported 507 related FE tests, `build.sh --fe`, and the MinIO
regression with this worktree's compatible BE `33d48fcf6da`. Those runs
predate this follow-up and are not current cluster verification. A full
External rerun, cloud, current-master BE and Linux/glibc 2.17 execution
remain unverified at the new head.

### Notes for Reviewers

- The BE Lance reader does not consume `history_schema_info`. Omitting
it retains FileScannerV2's exact-name matching, which the reader tests
exercise.
- Native FE tests skip explicitly on hosts unable to load Lance or Arrow
C Data JNI. The External pipeline enables the MinIO fixture and runs the
new regression suite. Linux x86_64 deployment rebuilds Arrow C Data JNI
with the Doris C++ toolchain, statically links its C++ runtimes and
replaces only that jar entry. This build step needs a JDK, C++ compiler
and `readelf`; it honors JAVA_HOME or discovers java.home from the JVM
selected by env.sh, including PATH-only JDK installations; releases
targeting glibc 2.17 must use the corresponding Doris build environment.
Linux/CentOS 7 execution of this new build step remains untested
locally.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved Indicates a PR has been approved by one committer. reviewed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants