Skip to content

[VL] Add Velox offload for Lance scans via Arrow C stream - #12958

Merged
zhouyuan merged 6 commits into
apache:mainfrom
sezruby:feat/velox-lance-scan
Oct 19, 2026
Merged

zhouyuan merged 6 commits into
apache:mainfrom
sezruby:feat/velox-lance-scan

Conversation

@sezruby

@sezruby sezruby commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

What changes are proposed in this pull request?

Offloads read-only Lance BatchScanExec to the Velox backend through the Arrow C Data Interface. This is the Gluten consumer side of the three-step Lance integration; both upstream pieces are released:

How it works

  • A new OffloadLanceScan rule matches a Lance BatchScanExec and rewrites it to LanceScanTransformer, which produces an ArrowJavaBatchType columnar RDD.
  • Per fragment, LanceArrowStreamScanner.export(...) hands back an Arrow C stream; Gluten wraps the stream address with ArrowArrayStream.wrap(...) / Data.importArrayStream(...) and loads the batches into ArrowWritableColumnVector. Only the Arrow C-struct address crosses the classloader boundary, so Gluten's Arrow version stays decoupled from lance-spark's.
  • Offload is gated: it engages only for a plain columnar Lance scan (no pushed aggregation, no full-text query). Anything else falls back to vanilla Spark.
  • A velox-lance Component registers the rule and activates only when lance-spark is on the classpath (org.lance.spark.read.LanceScan present).

Relationship to the Iceberg scan transformer

LanceScanTransformer is intentionally different in shape from IcebergScanTransformer. Iceberg extends BatchScanExecTransformerBase and is a native Velox scan: it emits Substrait, pushes filters into Velox, and reports scan-level SQL metrics. Lance instead extends LeafExecNode with ValidatablePlan and bridges an already-produced Arrow stream into Velox: filters and projection are pushed into the Lance reader by lance-spark before export, not into Velox, and there is an Arrow-Java → Velox conversion at import. Consequences of this boundary:

  • No native Velox scan pushdown for Lance; the Lance reader does the pruning.
  • No scan-level SQL metrics on the Lance node.
  • Schemas that require JVM post-processing (_rowid / _rowaddr / blob columns) are not offloaded.

These are follow-up opportunities, not blockers for the read-only offload. (See also #13140 for the more general "Spark Arrow batch → Velox" direction.)

Where the code lives / build

The read path is entirely Velox-specific (ArrowWritableColumnVector, ArrowBufferAllocators, ValidatablePlan), so it is placed under backends-velox/src-lance behind a new lance Maven profile — mirroring the src-iceberg Velox-integration layout rather than adding a top-level module.

  • lance.version (root pom.xml) = 0.8.0.
  • -Plance: compiles against lance-spark-base (provided). lance-core declares a newer Arrow than Gluten, so lance's transitive Arrow / jackson-jaxrs are excluded and Gluten's Arrow is kept (arrow-dataset is added at ${arrow.version}). This matches the published lance-spark-bundle-3.5, which ships Arrow 15. With these exclusions -Plance only adds jars to the classpath; it does not change any existing dependency version.
  • -Plance-test: adds the Spark-version-specific lance-spark-${sparkbundle.version} runtime (registers the lance data source) and the test sources.

Build: -Pbackends-velox -Pspark-3.5 -Plance. docs/get-started/VeloxLance.md documents scope, build, and requirements.

Open question for reviewers: a top-level gluten-lance module (like gluten-iceberg) makes sense once there is engine-agnostic code to host — e.g. a write path. The read-only offload has none today, so this PR keeps it Velox-local. Happy to restructure if you'd prefer the module up front.

How was this patch tested?

VeloxLanceSuite (-Plance -Plance-test) asserts:

  1. a columnar Lance scan offloads to LanceScanTransformer; with no Velox consumer its Arrow batches go straight to vanilla ColumnarToRowExec (no Velox round trip),
  2. with a Velox consumer (grouped aggregation) the scan feeds ArrowColumnarToVeloxColumnarExec(OffloadArrowDataExec(scan)) into a Velox aggregate, with no row conversion off the scan,
  3. projection + a pushed filter stay offloaded and return correct results,
  4. a multi-fragment dataset reads correctly across partitions, including a LIMIT that stops early (native scans are released per fragment on exhaustion, with a task-completion listener as the safety net),
  5. a pushed-down aggregation falls back to a vanilla BatchScanExec.

CI: the Spark 3.5 and Spark 4.0 x86 jobs (group 1, which runs the org.apache.gluten suites) now build with -Plance -Plance-test, so the suite runs on every PR. The suite sets spark.sql.ansi.enabled=false because Spark 4 defaults to ANSI mode.

Locally, the suite passes (5/5) on linux-aarch64 (apache/gluten:centos-8-jdk8, JDK 17, Spark 3.5 and Spark 4.0 / Scala 2.13) against lance-spark 0.8.0 and the current nightly Velox native libs:

./build/mvn test -Pspark-3.5 -Pjava-17 -Pbackends-velox -Plance -Plance-test -pl backends-velox -am \
  -Dtest=none -DwildcardSuites=org.apache.gluten.execution.VeloxLanceSuite

Was this patch authored or co-authored using generative AI tooling?

Generated-by: Claude Code; GitHub Copilot CLI 1.0.93 (Claude Opus 5.5)

Relates to #12263.

@github-actions github-actions Bot added CORE works for Gluten Core VELOX labels Sep 2, 2026
@github-actions

github-actions Bot commented Sep 2, 2026

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@github-actions github-actions Bot added the DOCS label Sep 3, 2026
@github-actions

github-actions Bot commented Sep 3, 2026

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@zhouyuan

Copy link
Copy Markdown
Member

@sezruby the coding style issue can be fixed by running this tool:
https://github.com/apache/gluten/blob/main/docs/developers/NewToGluten.md?plain=1#L94

@sezruby
sezruby force-pushed the feat/velox-lance-scan branch from 0a7569f to 5080d2f Compare September 21, 2026 19:41
@sezruby

sezruby commented Sep 21, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @zhouyuan! Ran ./dev/format-scala-code.sh and pushed the fix (also rebased on latest main) — spotless:check is clean now.

Heads up on the rest of CI: this is still a draft because the lance-spark release carrying lance-format/lance-spark#778 isn't out yet, so the -Plance dependency (the 0.8.0-beta.2 placeholder) won't resolve until that beta ships. I'll bump lance.version and take it out of draft once it's published.

@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@FelixYBW

FelixYBW commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

#13140
#12276

just link, no followup needed

This is the scan-side version of the same problem. With the Spark changes proposed in #13140, a connector-specific scan wouldn't be needed:

  • lance-spark's own BatchScanExec already produces columnar batches, and I expect they are Arrow-backed; I haven't checked lance-spark's reader.
  • If Spark let that node declare an Arrow batch type (SPARK-57468), Gluten would only need one general "Spark Arrow batch → Velox" conversion. Lance and every other Arrow data source would then work with no connector code, and would keep DPP, storage-partitioned join and metrics, because BatchScanExec stays in the plan.
  • The classloader/Arrow-version isolation this PR gets from the C stream could become a small optional Spark DSv2 interface, e.g. a PartitionReader that can exportArrowStream(address). The general conversion would use it when present and wrap the Java vectors otherwise.

@sezruby
sezruby force-pushed the feat/velox-lance-scan branch from 5080d2f to 5b47a2b Compare October 8, 2026 05:27
@github-actions github-actions Bot added the INFRA label Oct 8, 2026
@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@sezruby
sezruby marked this pull request as ready for review October 8, 2026 06:04
@sezruby
sezruby force-pushed the feat/velox-lance-scan branch from 5b47a2b to 10d5502 Compare October 8, 2026 18:19
@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@zhouyuan
zhouyuan requested a balanced review from Copilot October 9, 2026 10:36

@zhouyuan zhouyuan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks.

TAGS_EXCLUDE="org.apache.spark.tags.ExtendedSQLTest,org.apache.spark.tags.SlowHiveTest,org.apache.gluten.tags.UDFTest,org.apache.gluten.tags.EnhancedFeaturesTest,org.apache.gluten.tags.CudfTest,org.apache.gluten.tags.SkipTest"
if [ "${{ matrix.group }}" = "1" ]; then
$MVN_CMD clean test -Pspark-3.5 -Pjava-17 -Pbackends-velox -Piceberg -Pdelta -Phudi -Ppaimon -Pspark-ut \
$MVN_CMD clean test -Pspark-3.5 -Pjava-17 -Pbackends-velox -Piceberg -Pdelta -Phudi -Ppaimon -Plance -Plance-test -Pspark-ut \

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

could also enable the 4.0 test for lance if it's available?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks! lance-spark 0.8.0 publishes lance-spark-4.0_2.13, so I enabled -Plance -Plance-test in the Spark 4.0 job (group 1, which runs org.apache.gluten.*). VeloxLanceSuite passes 5/5 locally on Spark 3.5 and 4.0. I also pinned spark.sql.ansi.enabled=false in the suite, since Spark 4 defaults to ANSI. Docs updated.

Copilot AI 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.

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Copilot review overview

4 open findings
What changed in this PR

Adds Velox-side offload support for read-only Lance BatchScanExec by importing Lance-exported Arrow C streams into Gluten’s Arrow-Java columnar batches, with opt-in build/test profiles and CI validation.

Changes:

  • Introduces a new Velox “lance” component + rule to rewrite exportable Lance scans to LanceScanTransformer.
  • Implements LanceScanTransformer that imports per-fragment Arrow C streams and emits ArrowJavaBatchType columnar batches.
  • Adds Maven profiles, documentation, CI wiring, and a new VeloxLanceSuite covering offload vs fallback cases.
File Description
pom.xml Adds lance / lance-test profiles to include Lance-specific sources/resources.
backends-velox/​pom.xml Adds Lance dependencies (provided/test) with Arrow/Jackson exclusions and Arrow dataset API.
backends-velox/​src-lance/​main/​.../​OffloadLanceScan.scala Adds heuristic rule to rewrite exportable Lance scans to LanceScanTransformer.
backends-velox/​src-lance/​main/​.../​LanceScanTransformer.scala Implements Arrow C stream import path into Arrow-Java columnar batches.
backends-velox/​src-lance/​main/​.../​VeloxLanceComponent.scala Registers the Lance offload component, gated by runtime class presence.
backends-velox/​src-lance/​test/​.../​VeloxLanceSuite.scala Adds execution-plan and correctness tests for offload/fallback behavior.
docs/​get-started/​VeloxLance.md Documents requirements, build flags, behavior, and limitations.
.github/​workflows/​velox_backend_x86.yml Enables Lance profiles in CI group 1 so new suite runs.

🧠 Review effort: Lite


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +142 to +152
val stream = ArrowArrayStream.wrap(handle.streamAddress())
val reader = Data.importArrayStream(allocator, stream)
context.addTaskCompletionListener[Unit] {
_ =>
try {
// Drains + runs the C release callback, tearing down the native scan.
reader.close()
} finally {
// Frees the caller-owned stream struct and closes the scanner + dataset.
handle.close()
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in d017739. Per-fragment reading is now in LanceFragmentIterator. If wrap/importArrayStream throws, the handle is closed before rethrowing, and any close failure is added as suppressed.

Comment on lines +141 to +168
val handle = LanceArrowStreamScanner.export(fragId.intValue(), lancePartition)
val stream = ArrowArrayStream.wrap(handle.streamAddress())
val reader = Data.importArrayStream(allocator, stream)
context.addTaskCompletionListener[Unit] {
_ =>
try {
// Drains + runs the C release callback, tearing down the native scan.
reader.close()
} finally {
// Frees the caller-owned stream struct and closes the scanner + dataset.
handle.close()
}
}

new Iterator[ColumnarBatch] {
private var advanced = false
private var hasMore = false

private def advance(): Unit =
if (!advanced) {
hasMore = reader.loadNextBatch()
advanced = true
}

override def hasNext: Boolean = {
advance()
hasMore
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in d017739. Reader + handle are closed as soon as loadNextBatch() returns false, so a multi-fragment partition holds at most one open scan. close() is idempotent, and the task-completion listener stays as a safety net for early termination. Emitted batches own their transferred buffers, so closing early doesn't affect them. Added a multi-fragment test (including a LIMIT query that stops early and relies on the listener).

Comment thread pom.xml
Comment on lines +1972 to +2049
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add-lance-sources</id>
<goals>
<goal>add-source</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<sources>
<source>${project.basedir}/src-lance/main/scala</source>
</sources>
</configuration>
</execution>
<execution>
<id>add-lance-resources</id>
<goals>
<goal>add-resource</goal>
</goals>
<phase>generate-resources</phase>
<configuration>
<resources>
<resource>
<directory>${project.basedir}/src-lance/main/resources</directory>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>lance-test</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add-lance-test-sources</id>
<goals>
<goal>add-test-source</goal>
</goals>
<phase>generate-test-sources</phase>
<configuration>
<sources>
<source>${project.basedir}/src-lance/test/scala</source>
</sources>
</configuration>
</execution>
<execution>
<id>add-lance-test-resources</id>
<goals>
<goal>add-test-resource</goal>
</goals>
<phase>generate-test-resources</phase>
<configuration>
<resources>
<resource>
<directory>${project.basedir}/src-lance/test/resources</directory>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is intentional and mirrors the existing delta/iceberg/hudi/paimon profiles in the root pom, which add src-<format> roots the same way. build-helper skips non-existent directories, so other modules are unaffected.

Comment thread docs/get-started/VeloxLance.md Outdated

## Reading

Offload / Fallback.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Removed, thanks.

@github-actions

github-actions Bot commented Oct 9, 2026

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

sezruby and others added 6 commits October 14, 2026 11:46
Offloads read-only Lance BatchScanExec to the Velox backend through the
Arrow C Data Interface, using lance-spark's LanceArrowStreamScanner
(lance-spark#778). Only the Arrow C-struct address crosses the classloader
boundary, so Gluten's Arrow version stays decoupled from lance-spark's.

The offload is gated on being a plain columnar Lance scan (no pushed
aggregation, no full-text query); anything else falls back to vanilla
Spark. A velox-lance Component registers the rule and only engages when
lance-spark is on the classpath.

Code lives under backends-velox/src-lance behind a new `lance` Maven
profile, mirroring the src-iceberg velox-integration layout. The read path
is entirely velox-specific (ArrowWritableColumnVector, ArrowBufferAllocators,
ValidatablePlan), so no top-level gluten-lance module is added yet; one can
be introduced when an engine-agnostic write path lands.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Supportability follow-ups to the Lance Velox offload:

- lance-test profile (root pom): add-test-source/add-test-resource for
  backends-velox/src-lance/test, activated alongside -Plance.
- VeloxLanceSuite: asserts a columnar Lance scan offloads to
  LanceScanTransformer, that projection + pushed filter stay offloaded with
  correct results, and that a pushed-down aggregation falls back to a vanilla
  BatchScanExec. API-grounded against VeloxWholeStageTransformerSuite
  (checkGlutenPlan/checkSparkPlan/runQueryAndCompare, Iceberg-suite parity).
- docs/get-started/VeloxLance.md: read-only scope, -Plance build, lance-spark
  version + linux-x86-64 platform requirements, offload/fallback conditions,
  and the Arrow C stream topology note.

The suite requires the lance-spark native runtime, published for linux-x86-64
only, so it executes in that environment; the offload/fallback behavior it
encodes was validated under linux-x86-64.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Ran ./dev/format-scala-code.sh (spotless:apply) so the Lance offload
sources conform to Gluten's scalafmt config -- wraps javadoc lines over
the 100-column limit and drops a stray import-group blank line.
spotless:check is now clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Pin lance.version to the released lance-spark 0.8.0 (first release with
  LanceArrowStreamScanner) in the root pom.
- lance-test: add the Spark-version-specific lance-spark artifact, which
  registers the "lance" data source used by the suite.
- Keep Gluten's Arrow on the classpath: exclude lance-core's newer Arrow and
  jackson-jaxrs, and add arrow-dataset at ${arrow.version}.
- Fix an executor-side NPE: LanceScanTransformer.output was read through the
  transient batchScan after serialization (e.g. by DeserializeToObjectExec on
  collect()); capture it eagerly.
- Enable -Plance -Plance-test in the Spark 3.5 x86 CI job.
- Docs: lance-spark 0.8.0 requirement, supported native platforms, test command.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Plain scan: the Lance scan's Arrow Java batches go straight to vanilla
  ColumnarToRowExec (no Velox round trip).
- New test: with a Velox consumer (grouped aggregation), the scan feeds
  ArrowColumnarToVeloxColumnarExec(OffloadArrowDataExec(scan)) and is never
  converted to rows first.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…ark 4.0

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@sezruby
sezruby force-pushed the feat/velox-lance-scan branch from d017739 to 0f9b38a Compare October 14, 2026 18:48
@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@FelixYBW

FelixYBW commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

For the record: longer term, Gluten should reuse lance-spark's own columnar scan, with at most a thin LanceScanTransformer, instead of having its own execution path.

Proposal. lance-spark keeps the standard BatchScanExec → DataSourceRDD → createColumnarReader path and adds an option to emit plain Arrow batches. Spark's native data source PR (apache/spark#59313) works the same way: it imports an ArrowArrayStream into ArrowColumnVectors with supportColumnarReads = true. Gluten then only has to recognize the batches as Arrow, and LanceScanTransformer / LanceColumnarRDD / LanceFragmentIterator are no longer needed. Staying on DataSourceRDD also keeps what this PR's custom RDD skips today: Lance custom metrics, runtime filtering of partitions, the scan's output partitioning, and the OpenTelemetry setup.

Three pieces are needed:

1. lance-spark: an Arrow output mode in the columnar reader

Today LanceFragmentColumnarBatchScanner.buildSparkOrderedVectors doesn't produce plain Arrow batches:

  • It wraps each column in lance's own LanceArrowColumnVector.
  • It adds JVM-only virtual columns: ConstantColumnVector for _fragid, and BlobPositionColumnVector / BlobSizeColumnVector for blob columns.

An Arrow mode would:

  • Emit Spark's ArrowColumnVector in Spark schema order. The reader already reorders columns, so this also covers the reordered-column case that LanceArrowStreamScanner.export() rejects today.
  • Build _fragid as a real Arrow vector (a filled IntVector).
  • For blob position/size columns, either build real Arrow vectors or mark the partition as not Arrow-capable. Gluten could then leave the scan on vanilla Spark at planning time instead of failing at runtime in export().
  • Document the batch lifetime. ArrowReader reuses one VectorSchemaRoot, so a batch is valid only until the next next(), and consumers must transfer the vectors to keep them. [SPARK-60101][SQL] Support native data sources implemented in Rust or C++ spark#59313 has the same reuse behavior.

2. lance-spark: solve the Arrow version/classloader mismatch on its side

This mismatch is why this PR passes a C-struct address. If lance-spark's batches carry lance's own (newer or relocated) Arrow classes, Gluten can't use them as Arrow. Two options:

  • lance-spark builds the Arrow-mode output vectors with Spark's Arrow, doing the C Data import itself from the stream it already exports.
  • Or the batch exposes only a C Data export hook, and Gluten does the import.

The first is cleaner and matches apache/spark#59313.

3. Gluten: declare the batch type and accept Spark's ArrowColumnVector

  • Batch type. On Spark 3.5/4.0, Spark treats BatchScanExec output as vanilla columnar. Gluten needs a small rule that marks BatchScanExec(LanceScan) in Arrow mode as ArrowJavaBatchType while still calling vanilla doExecuteColumnar(). With SPARK-57468 (Spark 4.2+), the scan can declare ArrowBatchType itself and the rule isn't needed.
  • Offload input. ColumnarBatches.offload currently requires ArrowWritableColumnVector (isHeavyBatch). It needs to accept Spark's ArrowColumnVector and export from its FieldVector through C Data. [GLUTEN-13140][VL] Replace ArrowWritableColumnVector with Spark's ArrowColumnVector and ArrowWriter #13280 is doing this.

With these in place, the plan becomes BatchScanExec(Lance) → OffloadArrowDataExec → ArrowColumnarToVeloxColumnarExec → Velox, using only existing transitions. Fixed-width columns are zero-copy, and the only Lance-specific Gluten code left is the batch-type rule. The same rule would also work for apache/spark#59313 native sources and any other DSv2 source that emits Arrow.

@sezruby

sezruby commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

@FelixYBW following up on your plan above (#12958 (comment)):

  • lance-spark side: feat(read): emit Arrow batches from the columnar reader lance-format/lance-spark#908 (in review). The new arrow_batch_reads option makes the standard columnar reader emit Spark ArrowColumnVector batches. Vectors become Lists and row metadata becomes signed 64-bit, without copying values. LanceScan.arrowBatchSchema() reports at planning time whether a scan can do this, and withArrowBatches() turns it on. Batches are valid until the next next() and are allocated under ArrowUtils.rootAllocator(), matching your SPARK-57468 branch.
  • Gluten side: a local prototype. It's a rule that calls withArrowBatches(), plus a convFuncOverride marking the BatchScanExec as ArrowJavaBatchType. On 52 Arrow types every query matched vanilla Spark except one, and vectors and metadata columns went straight to Velox.

Gluten issues found on this path:

  1. ArrowColumnVectors.adopt throws for NullVector (no allocator).
  2. adopt copies every batch until Gluten's allocator is under Spark's root.
  3. There are "unreleased native columnar batches" warnings at task end.

Questions:

  1. Does Import more datasource tests #908 match what you had in mind?
  2. Should the Gluten change go in now as a rule, or wait for SPARK-57468?
  3. Is your allocator change planned for main?

#13488 stays the short-term vector fix for 1.8 until then.

malinjawi added a commit to malinjawi/incubator-gluten that referenced this pull request Nov 5, 2026
Since the Lance scan offload was added in apache#12958, isExportable has only
rejected a pushed aggregation and a full-text query. Other scans that
the Arrow C stream cannot serve are offloaded and then fail on their
first batch (apache#13487). apache#13488 makes vector columns readable; this covers
the rest.

isExportable now also checks the scan's columns at plan time, following
what LanceArrowStreamScanner.export and LanceFragmentScanner do:

- Columns that lance-spark's own reader fixes up after the native scan
  fall back. Blob (v1 and v2) and JSON columns come back in their stored
  form. The _rowid, _rowaddr, _fragid, row-version, _score and blob
  position and size columns are left out of the native projection.
- A scan that reads no columns falls back: the native scan returns
  _rowid instead.
- Every other column is mapped to Arrow with lance-spark's
  LanceArrowUtils, the mapping the export enforces, with vectors
  rewritten as lists as the scan emits them. An empty vector of that
  type is wrapped in ArrowColumnVector, as the scan will. FixedSizeBinary,
  Date(MILLISECOND) and Float16 vector columns fall back this way. Other
  vector columns stay offloaded.

With lance-spark 0.8.0, unsigned integer, LargeList, time and
non-microsecond timestamp columns still fail at execution: its Spark
schema does not record these Arrow types, so they cannot be told apart
at plan time.
LuciferYang pushed a commit to lance-format/lance-spark that referenced this pull request Nov 9, 2026
## What

Adds an `arrow_batch_reads` read option that makes the columnar reader emit Arrow batches: every column of a batch is a Spark `ArrowColumnVector`, in the read schema's order. `LanceScan.arrowBatchSchema()` tells at planning time whether a scan can emit them and with which Arrow types, and `LanceScan.withArrowBatches()` turns them on for a planned scan.

## Why

An engine that processes Arrow data can then take Lance batches as Arrow from Spark's standard `BatchScanExec` → `DataSourceRDD` path. Apache Gluten currently reads Lance through its own scan node over `LanceArrowStreamScanner.export` (apache/gluten#12958), which skips lance-spark's custom metrics and the scan's output partitioning, and fails at runtime on scans `export` rejects (apache/gluten#13487). With Arrow batches, the Lance-specific code left in Gluten is a rule that marks such a scan's batches as Arrow (outlined in apache/gluten#12958 (comment)).

## How

- **Arrow C stream import in lance-spark.** With Arrow batch reads, `LanceFragmentColumnarBatchScanner` imports the fragment scan's Arrow C stream itself (`exportArrowStream` + `Data.importArrayStream`) instead of reading it through lance-core's reader, so only the C-struct address crosses from lance-core and the vectors use the Arrow classes lance-spark runs with. The batches are allocated from `LanceRuntime.arrowBatchAllocator()`, a process-wide child of Spark's root allocator (`ArrowUtils.rootAllocator()`) that is capped at `LANCE_ALLOCATOR_SIZE` and never closed. A consumer whose allocator is under that root moves them without copying and can keep them after the reader closes; their memory, including the imported C structs, is released with the last reference to it.
- **Columns.** Most columns are the native scan's vectors as they are. Columns Spark's `ArrowColumnVector` does not read as declared are rebuilt without copying values:
  - `FixedSizeList` vectors become `List`s over the same child values, also inside structs, lists, and maps. Only an offsets buffer is new: element `i` of a FixedSizeList of size `n` is child range `[i * n, (i + 1) * n)`, also for null entries.
  - `_rowid`, `_rowaddr`, and the row version columns, unsigned 64-bit natively, become signed 64-bit integers over the same buffers, as the Spark reader reads them.
  - `_fragid` is a filled 32-bit integer vector.
- **Planning.** `LanceScanBuilder` plans the Arrow batches from the dataset schema it already loads (`ArrowBatchAdapter.plan`). For each column it builds an empty vector of the batch's Arrow type and checks that Spark's `ArrowColumnVector` reads it as the declared Spark type, with struct fields in the same order. This follows whatever the running Spark version supports and allocates nothing. Blob columns, also a blob nested in a struct or list (which Lance reads as its descriptor), JSON columns (converted on the JVM), the full-text `_score`, and other types (unsigned integers, `FixedSizeBinary`, non-microsecond timestamps, ...) make the scan read as usual, also when the option asks for Arrow batches. A pushed aggregation has no Arrow batches. A `LanceScan` without a supported plan, such as one built through the constructor without one, reads as usual whatever its read options say. Each built column is checked again against the declared type at runtime. Planning adds a `dataset.getSchema()` call to `LanceScanBuilder.build()` and runs also when the option is off, so `arrowBatchSchema()` is available to consumers.
- **Batch lifetime.** A batch is valid until the reader's next `next()` or `close()` call: the vectors the reader builds for a batch are released when the next batch is loaded, and the root's vectors are reused. A consumer that keeps a batch longer transfers its vectors.
- The option is copied by `withRef` (through a new `LanceSparkReadOptions.toBuilder()`) and included in `equals` / `hashCode`, so scans with and without Arrow batches are not reused for each other. `withArrowBatches()` keeps the planned partitioning. The existing public `LanceScan` constructor is kept. Documented in `docs/src/config.md`.

## Testing

- `ArrowBatchAdapterTest` (8 tests): planning keeps plain columns, turns vectors into Lists at any depth, maps metadata columns to signed integers, handles an empty projection, and rejects unsigned, `FixedSizeBinary`, nanosecond timestamps, structs whose fields do not line up (either way), blob, JSON, `_score`, and missing columns.
- `BaseArrowBatchReadTest` (12 tests, per Spark version through `ArrowBatchReadTest`): each test compares rows with and without Arrow batches and checks the batches through the scan's columnar reader: vector, struct, list and map columns with nulls; metadata columns; int8 vectors and vectors of vectors; scans without an Arrow batch form reading as usual, including columns with a blob nested in a struct or a list of structs and scans built without a supported plan; struct fields; `withArrowBatches()` on a planned scan, keeping its partitioning; and many fragments read in several batches, where the previous batch's vectors are released when the next one is loaded and the Arrow batch allocator returns to its starting level. Every Arrow batch vector is checked to come from the Arrow batch allocator, under Spark's root allocator, whose limit is the Lance allocator's, and a consumer that transfers vectors of a batch (a native one and one the reader built) into its own allocator keeps them readable after the reader closes, with Spark's root returning to its starting level once it closes them.
- `BlobUtilsTest`: `isLanceBlobArrowField` matches lance-core's `Field::is_blob`.
- The new tests pass on Spark 3.4/Scala 2.12, 3.5/2.12, 4.0/2.13, and 4.1/2.13; the full Spark 3.5/2.12 suite passes (1711 tests, 0 failures); `spotless:check` is clean. With `LANCE_ALLOCATOR_SIZE` set below a batch's size, Arrow batch reads fail on the cap like the regular reader.
- End to end with a Gluten build that, instead of its own Lance scan, turns on Arrow batches for scans whose Arrow types Velox reads and marks their batches as Arrow: on 52 Arrow types written with pylance 12.0.0, the five metadata columns, and an empty projection, every query matches vanilla Spark except one, and scans with an Arrow batch form feed Velox directly through `BatchScanExec`. The exception is a column of Arrow `Null` type, which fails in Gluten when it adopts the batch (`NullVector` has no allocator); that is a Gluten-side fix.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@sezruby

sezruby commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

@FelixYBW an update on the Arrow-batch path, with measurements.

I measured this with the 2026-11-08 nightly (gluten-velox-bundle-spark3.5_2.12-linux_amd64-1.9.0-SNAPSHOT) on Spark 3.5: a 20M-row Lance fact table in 200 fragments, joined with a filtered Lance date dimension, best of 7. It ran in an emulated amd64 container, so compare the times only with each other; the fragment counts are exact.

Query LanceScanTransformer Arrow batches, no runtime filter Arrow batches + runtime filter
join, 1 month 641 ms, 200 fragments 769 ms, 200 218 ms, 4
join, 2 months 565 ms, 200 642 ms, 200 188 ms, 8
full scan aggregate 442 ms 535 ms —

Without pruning, the Arrow-batch path is up to 21% slower here because of the copy in ArrowColumnVectors.adopt (issue 2 in my last comment). Gluten's ArrowBufferAllocators are separate RootAllocators, so every batch is copied rather than transferred.

The Gluten side in this run is the prototype from my last comment: a convFuncOverride that marks a Lance BatchScanExec with Arrow batch reads as ArrowJavaBatchType, with OffloadLanceScan not injected.

Is your allocator change planned for main? With it, this path wouldn't need the copy.

@sezruby

sezruby commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor Author

@FelixYBW a follow-up on the copy in ArrowColumnVectors.adopt (issue 2 in my earlier comments), now that #13648 moves the Lance scan onto lance-spark's Arrow batches.

lance-spark allocates those batches under Spark's root allocator. lance-format/lance-spark#908 settled on that in review, so that consumers under Spark's root can transfer the vectors and keep them after the reader closes. Gluten's task allocator is its own RootAllocator, so adopt copies every batch. Without pruning, that makes the Arrow-batch path up to 21% slower than LanceScanTransformer in my emulated benchmark.

The "Ongoing work" section of ArrowColumnarConversion.md suggests making Gluten's task allocator a child of Spark's root, which would turn that copy into a move. That breaks Gluten's memory accounting, though. Arrow charges a transfer to the target allocator with forceAllocate, which doesn't call its AllocationListener, but releasing the buffer later calls onRelease on the listener of whichever allocator owns it last. With Arrow 15 and two child allocators of one root, a 1 MiB buffer moved from one to the other and then released:

target listener: onPreAllocation=0 onAllocation=0 onRelease=1048576
source listener: onAllocation=1048576 onRelease=0

Reserving the moved bytes on the target listener in adopt doesn't fix it. When the source still references the memory, as the vectors lance-spark builds over a native batch do, Arrow hands ownership back to the source when Gluten releases its batch, and the final onRelease goes to the source's listener. I tried it: with Gluten's task allocator under Spark's root and that reservation, VeloxLanceSuite's vector tests fail with Managed memory leak detected; size = 8388608.

So nothing should be transferred at all. Instead, lance-spark imports its Arrow batches into an allocator Gluten supplies for the task, and every allocation and release goes through Gluten's listener:

  • lance-spark: feat: let a consumer supply the allocator of Arrow batch reads lance-format/lance-spark#966 adds LanceRuntime.setArrowBatchAllocatorProvider. A columnar reader asks the provider for its allocator once, on the task's thread, when the reader is created. It imports the Arrow C stream there and builds every vector it adds there too.
  • Gluten: VeloxLanceComponent.onExecutorStart sets the provider to ArrowBufferAllocators.contextInstance() (null outside a task), and onExecutorShutdown clears it.
    • That's the allocator OffloadArrowDataExec already offloads with, so adopt becomes a transfer within one allocator. Nothing moves between allocators and ManagedAllocationListener stays balanced, with no change to adopt or ArrowBufferAllocators.
    • TaskResources registers its completion listener at task start, before DataSourceRDD registers the reader's close, so the reader closes before the allocator is released.

Validated on amd64 Linux against a local build of lance-format/lance-spark#966:

  • VeloxLanceSuite passes 13/13, including a new test that every vector of a Lance task's batches is in the task's Arrow allocator. ArrowColumnVectorTest, ColumnarBatchTest and VeloxTransitionSuite also pass.
  • No "Detected leaked Arrow allocator", "Managed memory leak" or unreleased-native-batch warnings.
  • On 400k rows of 768-d float vectors over 8 partitions, vector queries were 1.10–1.34× faster than with the copy (emulated amd64, so treat these as ratios only).

One caveat before Gluten enables it: Gluten's task allocator throws when Spark has no memory left, so with this change a refusal can come inside Arrow Java's C Data import. Arrow Java leaks the batch being imported when that happens while importing its buffers or while allocating the struct the batch moves into. The first is apache/arrow-java#1239, fixed on main after 19.0.0. The second is apache/arrow-java#1491, with a fix in apache/arrow-java#1492. lance-format/lance-spark#966 releases everything before that point:

  • if the import is refused before it takes the exported stream, the stream is released;
  • the schema is read before the first batch, so a refused schema struct can't strand one.

Gluten's Arrow Java has both leaks: the 15.0.0 source build and the 18.x / 19.0 artifacts used for Spark 4.x. The copy path in #13648 doesn't hit them, because lance-spark imports into its own allocator, which never refuses.

So the plan:

Does this fit what you have in mind for the allocator?

Edited: I first proposed the reservation in adopt here; it leaks, as described above. Updated with the implementation in lance-format/lance-spark#966, its results, the Arrow Java caveat and the plan.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CORE works for Gluten Core DOCS INFRA VELOX

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants