Skip to content

[GLUTEN-13806][VL] Offload Lance table writes to Velox - #13595

Open
malinjawi wants to merge 11 commits into
apache:mainfrom
malinjawi:feat/lance-native-writer
Open

malinjawi wants to merge 11 commits into
apache:mainfrom
malinjawi:feat/lance-native-writer

Conversation

@malinjawi

@malinjawi malinjawi commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

What changes are proposed in this pull request?

This is the write side of #12263, tracked in #13806, following the approach we agreed on in the issue. Instead of converting Velox batches back to rows, each task streams them to Lance through the Arrow C Data Interface, and lance-spark commits on the driver like it always does. It replaces #13515.

It's off by default for now (spark.gluten.sql.columnar.backend.velox.lance.enableNativeWrite). With it on, appends and overwrites run natively, and so do CTAS on every Spark version and RTAS on Spark 3.5 and up. Vector columns are written natively too: Velox has no fixed-size list type, so it exports them as plain lists and the writer turns them back.

This needs lance-spark 0.9.0-beta.2, the first release with the two hooks we need (lance-format/lance-spark#715 and lance-format/lance-spark#892), so the PR bumps it. #13527 tracks moving to a stable release before Gluten's next one. It also turns on the Lance tests in the Spark 4.1 and 4.2 CI jobs.

A couple of things surprised me along the way. Velox can leave garbage under null values, and Lance looks at those values when it picks an encoding, so the files came out bigger than lance-spark's until I zeroed them. I also check every batch against the table's schema, so if Velox ever exports a type differently, the task fails instead of writing bad data. And if a task fails, Lance cleans up the files it wrote.

What I left out on purpose: UPDATE, DELETE and MERGE, sharded tables, blobs, TimestampNTZ, nested fixed-size lists, and a few Arrow types Velox exports differently, like large strings and unsigned ints. Those all fall back to lance-spark's writer, and VeloxLance.md has the full list. WriteFragmentBuilder.schema(...) from the issue also has to wait until Lance's Java API lets us build a LanceSchema. And as with lance-spark's writer, Lance's own encoder memory isn't counted as Spark memory.

How was this patch tested?

I added VeloxLanceWriteSuite (34 tests) and three small unit suites. They pass on Spark 3.5, 4.0, 4.1 and 4.2, locally and in CI. I also ran lance-spark's own 1,673 tests with the native write on and got the same results as without it, and compared written tables to their input with EXCEPT ALL on a few large datasets.

I benchmarked it on 8 x r6id.4xlarge with Spark 3.5, median of 5 runs. These numbers are from before the null zeroing went in; a local re-run with it in (12 cores) showed no slowdown from it (60M lineitem rows: 2.93 s native, 2.86 s before), and the files are now the same size as lance-spark's writer's.

Data Native Gluten + lance-spark writer Vanilla Spark
TPC-DS store_sales, 1.44B rows 39.2 s 72.4 s 89.4 s
60M x 768-float vectors 26.9 s 35.6 s 43.7 s
30M rows, vectors and nine strings 67.2 s 83.6 s 125.3 s

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

Generated-by: Claude Code (claude-opus-5-5)

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@github-actions github-actions Bot added CORE works for Gluten Core VELOX DOCS labels Nov 9, 2026
@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

1 similar comment
@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@malinjawi
malinjawi force-pushed the feat/lance-native-writer branch from ff5e64d to 024e574 Compare November 15, 2026 12:48
@github-actions github-actions Bot added the INFRA label Nov 15, 2026
@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@malinjawi
malinjawi force-pushed the feat/lance-native-writer branch from 024e574 to 59f4ccf Compare November 16, 2026 11:49
@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@malinjawi
malinjawi force-pushed the feat/lance-native-writer branch from 59f4ccf to dfe8a25 Compare November 16, 2026 12:08
@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@malinjawi
malinjawi marked this pull request as ready for review November 16, 2026 20:01
@malinjawi

Copy link
Copy Markdown
Contributor Author

cc: @zhouyuan @FelixYBW @sezruby @zhztheplayer

Here's the Lance writer. I've tested and benchmarked it, and the numbers are in the description. There are a few exclusions for now. Please have a look, happy to hear your insights.

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.

🟡 Changes recommended

Allocation-failure paths leak Arrow resources, and the zero-copy fixed-size-list path unnecessarily allocates a full child vector, increasing peak memory and allocation-failure risk.

3 open issues
What changed in this PR

Adds experimental Lance write offloading to the Velox backend, extending the existing read integration. Tasks stream columnar batches through the Arrow C Data Interface while lance-spark retains driver-side commits.

Changes:

  • Adds opt-in native append and overwrite support, including CTAS/RTAS on Spark 3.5+, with fallback for unsupported writes.
  • Adds schema validation, fixed-size-list conversion, null-slot normalization, and write metrics.
  • Updates lance-spark, documents support boundaries, and expands tests and CI coverage.
File Description
pom.xml Bumps lance-spark to the release providing required write hooks.
docs/​backends/​velox/​get-started/​VeloxLance.md Documents native writes, configuration, and limitations.
backends-velox/​src/​main/​scala/​org/​apache/​gluten/​backendsapi/​velox/​VeloxMetricsApi.scala Uses shared write metric names.
backends-velox/​src/​main/​java/​org/​apache/​gluten/​metrics/​BatchWriteMetrics.java Defines shared write metric constants.
backends-velox/​src-lance/​test/​scala/​org/​apache/​spark/​sql/​gluten/​LanceTestUtils.scala Adds listener synchronization for tests.
backends-velox/​src-lance/​test/​scala/​org/​apache/​gluten/​execution/​VeloxLanceWriteSuite.scala Tests write offloading, correctness, fallback, and failures.
backends-velox/​src-lance/​test/​scala/​org/​apache/​gluten/​connector/​write/​LanceNullSlotsSuite.scala Tests null-slot zeroing and buffer preservation.
backends-velox/​src-lance/​test/​scala/​org/​apache/​gluten/​connector/​write/​LanceFixedSizeListsSuite.scala Tests list conversion and size validation.
backends-velox/​src-lance/​test/​scala/​org/​apache/​gluten/​connector/​write/​LanceColumnarBatchDataWriterSuite.scala Tests Arrow schema compatibility checks.
backends-velox/​src-lance/​main/​scala/​org/​apache/​gluten/​extension/​OffloadLanceWrite.scala Registers append and overwrite offload rules.
backends-velox/​src-lance/​main/​scala/​org/​apache/​gluten/​execution/​VeloxLanceOverwriteByExpressionExec.scala Adds the native overwrite execution node.
backends-velox/​src-lance/​main/​scala/​org/​apache/​gluten/​execution/​VeloxLanceAppendDataExec.scala Adds the native append execution node.
backends-velox/​src-lance/​main/​scala/​org/​apache/​gluten/​execution/​LanceWriteExec.scala Shares write validation and batch-write lifecycle handling.
backends-velox/​src-lance/​main/​scala/​org/​apache/​gluten/​connector/​write/​LanceNullSlots.scala Zeroes unused fixed-width values for compact encoding.
backends-velox/​src-lance/​main/​scala/​org/​apache/​gluten/​connector/​write/​LanceFixedSizeLists.scala Converts exported lists into Lance fixed-size lists.
backends-velox/​src-lance/​main/​scala/​org/​apache/​gluten/​connector/​write/​LanceColumnarBatchDataWriterFactory.scala Creates task writers using resolved Lance write settings.
backends-velox/​src-lance/​main/​scala/​org/​apache/​gluten/​connector/​write/​LanceColumnarBatchDataWriter.scala Streams batches to Lance and handles task lifecycle and metrics.
backends-velox/​src-lance/​main/​scala/​org/​apache/​gluten/​config/​VeloxLanceConfig.scala Adds the disabled-by-default native-write setting.
backends-velox/​src-lance/​main/​scala/​org/​apache/​gluten/​component/​VeloxLanceComponent.scala Enables write rules when required Lance APIs are present.
.github/​workflows/​velox_backend_x86.yml Enables Lance tests in Spark 4.1 and 4.2 CI jobs.

Review effort: Balanced

private def exportBatch(batch: ColumnarBatch): ExportedBatch = {
val handle = ColumnarBatches.getNativeHandle(BackendsApiManager.getBackendName, batch)
val exported = new ExportedBatch(ArrowArray.allocateNew(allocator))
val cSchema = ArrowSchema.allocateNew(allocator)

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.

Good catch, fixed. The schema struct is now allocated inside the array's cleanup block, so if that allocation fails the array is released.

Comment on lines +68 to +69
target.setInitialCapacity(rows)
target.allocateNew()

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. When no row is null it now allocates only the validity bitmap and moves the elements over. I added a check to the test that no element buffer gets allocated on that path.

val copy = vector.getField.createVector(allocator).asInstanceOf[BaseFixedWidthVector]
// Raw buffers rather than allocateNew(), which would zero the data only for it to be copied over.
val validity = allocator.buffer(bitmapBytes)
val data = allocator.buffer(rows * width)

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, the validity buffer is freed if the data buffer can't be allocated. There's a new test that forces that allocation to fail and checks nothing is leaked.

malinjawi added a commit to malinjawi/incubator-gluten that referenced this pull request Nov 18, 2026
…sts without allocating elements

Addresses the Copilot review on apache#13595:
- exportBatch allocates the ArrowSchema struct inside the cleanup scope of
  the ArrowArray, so a failed allocation no longer leaks the array struct.
- LanceNullSlots frees the validity buffer of a copy when its data buffer
  cannot be allocated.
- LanceFixedSizeLists allocates only the validity of a fixed-size list
  column whose rows are all lists, as their elements are transferred, not
  copied.

Co-Authored-By: Claude <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

malinjawi added a commit to malinjawi/incubator-gluten that referenced this pull request Nov 18, 2026
…sts without allocating elements

Addresses the Copilot review on apache#13595:
- exportBatch allocates the ArrowSchema struct inside the cleanup scope of
  the ArrowArray, so a failed allocation no longer leaks the array struct.
- LanceNullSlots frees the validity buffer of a copy when its data buffer
  cannot be allocated.
- LanceFixedSizeLists allocates only the validity of a fixed-size list
  column whose rows are all lists, as their elements are transferred, not
  copied.

Co-Authored-By: Claude <noreply@anthropic.com>
@malinjawi
malinjawi force-pushed the feat/lance-native-writer branch from be4add1 to 62906ad Compare November 18, 2026 11:17
@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

malinjawi added a commit to malinjawi/incubator-gluten that referenced this pull request Nov 18, 2026
…sts without allocating elements

Addresses the Copilot review on apache#13595:
- exportBatch allocates the ArrowSchema struct inside the cleanup scope of
  the ArrowArray, so a failed allocation no longer leaks the array struct.
- LanceNullSlots frees the validity buffer of a copy when its data buffer
  cannot be allocated.
- LanceFixedSizeLists allocates only the validity of a fixed-size list
  column whose rows are all lists, as their elements are transferred, not
  copied.

Co-Authored-By: Claude <noreply@anthropic.com>
@malinjawi
malinjawi force-pushed the feat/lance-native-writer branch from 62906ad to 6944dc0 Compare November 18, 2026 11:57
@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@malinjawi

Copy link
Copy Markdown
Contributor Author

cc: @LuciferYang PTAL

@LuciferYang

Copy link
Copy Markdown
Contributor

cc: @LuciferYang PTAL

ok

thread.join(StopTimeoutMs)
} catch {
// Spark interrupts a task it kills. Keep the interrupt for Spark to see.
case _: InterruptedException => Thread.currentThread().interrupt()

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.

If the task thread is already interrupted when abort() runs, stopWriter doesn't wait for the writer thread. thread.join(StopTimeoutMs) throws right away, stopWaited keeps close() from waiting, and close() skips stream.release() because the thread is still alive. The flag is still set when Spark kills the task with interruptThread = true (say, a losing speculative attempt) and the kill comes out as a TaskKilledException from an InterruptibleIterator. When queue.offer sees the kill first, its InterruptedException clears the flag and abort() waits as it should.

So the task can finish while QueueReader's root still holds the last imported batch. Task cleanup releases the Velox memory manager with that memory still reserved and logs a leaked Arrow allocator. The batch is freed later, when Lance releases the stream.

Could stopWriter clear the flag with Thread.interrupted(), wait up to StopTimeoutMs, and set it again? The comment above the stream.release() check needs updating too.

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 @LuciferYang It was actually way worse than just a leak as I was able to reproduce the task finished while the writer thread still held a batch, Velox's memory manager check failed, and the JVM aborted. stopWriter now clears the interrupt, waits for the thread (up to the same 5 minutes lance-spark's writer waits), and sets the interrupt again afterwards so Spark still sees it. A second interrupt during the wait doesn't cut it short either. I updated the comment above the stream.release() check too: the only case left where the writer can still be running is when it doesn't stop within those 5 minutes. I also added a test that fails a task with its interrupt flag set; it crashed the JVM before the fix and passes now.

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.

The interrupt fix looks right. One case is still open: if Lance hasn't stopped when the 5-minute wait in stopWriter runs out, the task ends while the reader's root, and anything Lance has buffered, holds batches exported from Velox. That's the state you reproduced earlier, where Velox's memory manager check failed and the JVM aborted, so the comment above the stream.release() check understates it. It needs one Lance call to block for 5 minutes, say an object-store request stuck in retries, so it should be rare.

Joining without a deadline wouldn't fix it alone: the task reaper is off by default and only watches killed tasks, so a write that failed by itself would hang in abort(). If the 5-minute bound stays as the last resort, could the comment and VeloxLance.md say it can abort the executor, and the timeout log go to ERROR and say so too?

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.

Agreed, the 5-minute bound stays as the last resort. The comment above the stream.release() check and VeloxLance.md now say that if Lance is still running when the wait runs out, the task ends with Velox batches still held, which can abort the executor. The timeout log is now an ERROR that says the same.

malinjawi added a commit to malinjawi/incubator-gluten that referenced this pull request Nov 20, 2026
As zhouyuan suggested on apache#13595, and as gluten-iceberg does, the Lance
code is split in two:
- gluten-lance holds what does not depend on Velox: the scan transformer
  and its offload rule, LanceWriteExec (the write validation and the
  batch-write reuse), and the Arrow conversions the writer applies
  (LanceNullSlots, LanceFixedSizeLists), with their unit tests.
- backends-velox/src-lance keeps the Velox parts: the writer that exports
  Velox batches to Lance and its factory, the write nodes, now on a
  VeloxLanceWriteExec trait that provides the writer factory, the write
  offload rules, the component and VeloxLanceConfig (as VeloxDeltaConfig
  stays in backends-velox).

The lance profile builds the module, backends-velox and the bundle depend
on it, and the CI path filters, labeler and test scripts list it. The
Scala formatter now includes the lance profile, so Lance code is
format-checked in CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@malinjawi
malinjawi force-pushed the feat/lance-native-writer branch from 6d9eb13 to 0aed1fb Compare November 20, 2026 15:51
malinjawi added a commit to malinjawi/incubator-gluten that referenced this pull request Nov 20, 2026
When Spark refused the memory for importing an exported Velox batch, the
batch could stay unreleased, and Velox's memory manager then found its
memory still reserved when the task ended. Two paths led there:

- Arrow up to 19 never releases a foreign allocation whose reservation
  fails in onPreAllocation (apache/arrow-java#1240). Batches are now
  imported through a child allocator that reserves in onAllocation,
  where Arrow releases the batch on failure. It releases through the
  same listener, as Arrow moves buffers between the two allocators
  without telling either listener.
- An import that cannot allocate its copy of the C struct fails before
  it takes the batch, but importInto treated the batch as taken. It now
  releases the batch unless the import took it.

Reported by sezruby on apache#13595.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
malinjawi added a commit to malinjawi/incubator-gluten that referenced this pull request Nov 20, 2026
- LanceWriteExec in gluten-lance keeps the checks that hold for any
  backend (the write type, sharding and blob columns) and asks the
  backend for the rest. VeloxLanceWriteExec now holds the checks for
  what Velox's Arrow export produces.
- The pinned Velox exports the undefined values under a struct's null
  rows for strings, binaries, arrays and maps as well as timestamps, so
  those columns inside a struct that may be null now fall back too,
  until Gluten's Velox includes facebookincubator/velox#20126.
- Only float and double fixed-size lists are written as vectors, the
  only ones lance-spark writes; the docs said integers too.
- Adds a round trip for JSON columns.

From sezruby's review on apache#13595.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@malinjawi

Copy link
Copy Markdown
Contributor Author

One thing to coordinate with #13648: it removes LanceScanTransformer and OffloadLanceScan and reads through lance-spark's Arrow batches instead. A LanceArrowBatchScan rule picks the scans to offload based on which Arrow types Velox imports, so it stays in backends-velox/src-lance. After #13648, gluten-lance would have no scan code. #13648 is waiting for a lance-spark release that includes lance-format/lance-spark#908, so this PR will likely land first, and I'll rebase #13648 onto it. Against this head that comes down to two rename/delete conflicts on the moved files, and deleting them resolves both.

LanceWriteExec.unsupportedColumn and timestampInNullableStruct don't depend on Velox at compile time. They do describe what Velox's Arrow export produces, though: plain List for fixed-size lists, plus the timestamp conversion under a null struct. Would it fit the split better for VeloxLanceWriteExec to provide that check, so gluten-lance keeps only what holds for any backend?

Thanks for building it on its own @sezruby! Yes, it fits the split better, so I moved both. LanceWriteExec now has an abstract unsupportedColumn, and VeloxLanceWriteExec provides it from unexportableColumn (was unsupportedColumn, the fixed-size list export) and undefinedUnderNullStruct (was timestampInNullableStruct, now also covering strings, binaries, arrays and maps). gluten-lance keeps only the checks that hold for any backend: the write type, sharding and blob columns.

Sounds good on #13648. Happy for this one to go first, and ping me if the rebase gets in the way.

@malinjawi

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review and for measuring the zeroing on its own @sezruby.

  1. Null-slot zeroing cost. Could you re-run the table with the zeroing in?
    Null-slot zeroing cost Re-ran it with the zeroing in. It doesn't slow the write down: lineitem 60M went from 2.86 s to 2.93 s, within noise. The files are now the same size as lance-spark's writer's.
Input Gluten, native write Gluten, lance-spark's writer Vanilla Spark
lineitem 60M rows 2.93 s 6.25 s 7.48 s
store_sales-like 12M rows 1.23 s 3.90 s 4.15 s
1M x 768 vectors 1.01 s 1.64 s 1.75 s

These are from one laptop (local[12], median of 6 runs). Lance's own threads make local wall-clock gains look bigger than on a cluster, and the CPU saved per write is the better guide. That came out at 1.75x for store_sales-like and 1.29x for vectors, close to the 1.86x and 1.32x from the cluster run in the description. I can re-run the cluster benchmark with the zeroing in once I have cluster access again.

  1. Plans whose input is rows. Is there a number for that case, e.g. a mapInPandas producing 768-d vectors and then writing? If it's slower, the offload could be skipped when the child isn't already columnar.

In my testing It isn't slower. With mapInPandas producing 1M x 768 vectors (MapInPandas -> RowToVeloxColumnar -> VeloxLanceAppendData), most of the time goes to Python: the native write takes 14.1 s vs 14.0 s with lance-spark's writer, with about 25% less JVM CPU. So I kept the offload for row children. Happy to skip it there if you'd still prefer. This one is also from the laptop, and I can confirm it on the cluster too.

  1. JSON columns. Could you add one round trip?

Added a round-trip test, "JSON columns are written natively and read back as lance-spark's writer leaves them". While writing it I found that the Gluten Lance scan throws on the JSON column instead of falling back, so the test reads back with the batch scan off. That's on the read side, so probably worth covering in #13648.

@malinjawi
malinjawi requested a review from sezruby November 20, 2026 20:53
@malinjawi

Copy link
Copy Markdown
Contributor Author
  1. Velox off-heap allocations generating native columnar batches.
  2. In-flight Arrow batches buffered in the queue (QueueCapacity = 4).
  3. Lance's native Rust encoder buffers, which (as noted in the description) are unmanaged by Spark's TaskMemoryManager.

Thanks @malinjawi for addressing the review comments.

One remaining gap - the per-column encoder buffering is the main uncounted component, but the runs only varied vector dimension and data size, not column count. Could you add one run with a wide schema (say 50–100 columns plus the vector column) to confirm the overhead scales with columns as described?

Also, in VeloxLance.md it would help to include a rough formula or example (columns × 8 MiB × concurrent write tasks) and mention that S3 uploads add Lance buffers on top.

With those, I'm happy to approve.

Thanks @rajarajangs. I ran it with a wide schema: 10 to 100 long columns plus a 64-float vector column, 8 concurrent write tasks with 1.2M rows each, so every column's buffer fills. Memory the process grew by during the write, beyond reading the same columns:

Columns (+ vector) Gluten, native write Gluten, lance-spark's writer 8 tasks x (columns + 1) x 8 MiB
10 0.67 GiB 0.55 GiB 0.69 GiB
25 1.79 GiB 1.63 GiB 1.62 GiB
50 2.91 GiB 2.75 GiB 3.19 GiB
100 5.95 GiB 6.27 GiB 6.31 GiB

So it scales with the column count as described, the formula is a fair estimate, and both writers use about the same. Spark counts only about 0.2 GiB of it. The caveat that this was local testing only
VeloxLance.md now has the formula with an example. It also notes that on an object store Lance 12 keeps up to 10 upload parts of 5 MiB in flight per file (LANCE_UPLOAD_CONCURRENCY, source), so about 55 MiB more per write task. 8 tasks writing 20 columns to S3 come to about 1.7 GiB.

malinjawi and others added 10 commits November 21, 2026 13:14
Writes to Lance tables run through Velox when
spark.gluten.sql.columnar.backend.velox.lance.enableNativeWrite is set:
appends, overwrites, and the nested writes of CREATE TABLE AS SELECT and
REPLACE TABLE AS SELECT. Each task exports its Velox batches as an Arrow
C stream and writes them with Fragment.write, using the write
parameters lance-spark resolves for the table
(LanceBatchWrite.getFragmentWriteSpec). The task returns
LanceBatchWrite.taskCommit(fragments), and lance-spark commits or stages
them on the driver as for its own writer. Tasks report the same metrics
as lance-spark's writer, plus Gluten's native write metrics.

Writes Velox cannot serve stay on lance-spark's writer, decided at
planning time: sharded tables, blob columns, and column types Velox
exports with a different layout, such as large strings and binaries,
fixed-size lists and half floats. Each exported batch is also checked
against the layout of the table's Arrow schema, so a type Velox exports
differently fails the task instead of writing wrong data.

This needs lance-spark 0.9.0-beta.2, the first release with taskCommit
and getFragmentWriteSpec, so lance.version moves from 0.8.0. CI now runs
the Lance suites on Spark 4.1 and 4.2 as well as 3.5 and 4.0.
Velox has no fixed-size list type and exports Lance's vector columns as
plain lists, so the Lance write offload fell back for any table with a
vector column. The writer now imports such batches as Velox exports them
and moves each top-level fixed-size list column of signed integers or
floats into the commit schema's fixed-size list vector: without a copy
when every row holds a list, and element by element otherwise. A list
with the wrong number of elements fails the task.

Fixed-size lists nested in other columns, and half-float vectors, still
fall back to lance-spark's writer.
…sts without allocating elements

Addresses the Copilot review on apache#13595:
- exportBatch allocates the ArrowSchema struct inside the cleanup scope of
  the ArrowArray, so a failed allocation no longer leaks the array struct.
- LanceNullSlots frees the validity buffer of a copy when its data buffer
  cannot be allocated.
- LanceFixedSizeLists allocates only the validity of a fixed-size list
  column whose rows are all lists, as their elements are transferred, not
  copied.

Co-Authored-By: Claude <noreply@anthropic.com>
…pted

Addresses LuciferYang's review on apache#13595: when Spark kills a task, its
interrupt can still be pending when the writer is aborted, so the wait for
the writer thread returned at once and the task freed its Velox memory
while the writer still held a batch, which aborted the executor.
stopWriter now clears the interrupt for the wait, keeps waiting up to
StopTimeoutMs if interrupted again, and restores it afterwards.

Also notes in VeloxLance.md that Lance's own encoder memory needs room in
spark.executor.memoryOverhead, and that a task killed after handing Lance
its last batch leaves its files behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
As zhouyuan suggested on apache#13595, and as gluten-iceberg does, the Lance
code is split in two:
- gluten-lance holds what does not depend on Velox: the scan transformer
  and its offload rule, LanceWriteExec (the write validation and the
  batch-write reuse), and the Arrow conversions the writer applies
  (LanceNullSlots, LanceFixedSizeLists), with their unit tests.
- backends-velox/src-lance keeps the Velox parts: the writer that exports
  Velox batches to Lance and its factory, the write nodes, now on a
  VeloxLanceWriteExec trait that provides the writer factory, the write
  offload rules, the component and VeloxLanceConfig (as VeloxDeltaConfig
  stays in backends-velox).

The lance profile builds the module, backends-velox and the bundle depend
on it, and the CI path filters, labeler and test scripts list it. The
Scala formatter now includes the lance profile, so Lance code is
format-checked in CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The queue lets Lance keep encoding while the task exports the next
batches. Queued batches are still Velox batches, counted as task memory
and capped by maxBatchSize, which is why its capacity is a constant
rather than a setting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When Spark refused the memory for importing an exported Velox batch, the
batch could stay unreleased, and Velox's memory manager then found its
memory still reserved when the task ended. Two paths led there:

- Arrow up to 19 never releases a foreign allocation whose reservation
  fails in onPreAllocation (apache/arrow-java#1240). Batches are now
  imported through a child allocator that reserves in onAllocation,
  where Arrow releases the batch on failure. It releases through the
  same listener, as Arrow moves buffers between the two allocators
  without telling either listener.
- An import that cannot allocate its copy of the C struct fails before
  it takes the batch, but importInto treated the batch as taken. It now
  releases the batch unless the import took it.

Reported by sezruby on apache#13595.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- LanceWriteExec in gluten-lance keeps the checks that hold for any
  backend (the write type, sharding and blob columns) and asks the
  backend for the rest. VeloxLanceWriteExec now holds the checks for
  what Velox's Arrow export produces.
- The pinned Velox exports the undefined values under a struct's null
  rows for strings, binaries, arrays and maps as well as timestamps, so
  those columns inside a struct that may be null now fall back too,
  until Gluten's Velox includes facebookincubator/velox#20126.
- Only float and double fixed-size lists are written as vectors, the
  only ones lance-spark writes; the docs said integers too.
- Adds a round trip for JSON columns.

From sezruby's review on apache#13595.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Say that a Lance write still running 5 minutes after the task stopped it
  may abort the executor, in the writer, the docs and an ERROR log.
- Say that CREATE TABLE AS SELECT is offloaded on Spark 3.4 too, since Gluten
  plans it as a nested append, and assert it in the test.
- Fall back for TimestampNTZ values inside a nullable struct as well.
- Read whether the writer thread is alive before its failure, so a failure
  in between keeps Lance's error as the cause.
- Say that Lance pulls the batches on its Tokio threads.
- Give a rough formula for Lance's memory per executor, including the upload
  buffers it keeps on an object store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- VeloxLance.md no longer says float and double are the only fixed-size
  lists lance-spark writes: it also writes Float16 vectors when a
  column's metadata asks for them, and those fall back, since Velox has
  no half-float type.
- isFloatOrDouble matches SINGLE and DOUBLE instead of excluding HALF,
  and the test checks that a Float16 vector falls back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@malinjawi
malinjawi force-pushed the feat/lance-native-writer branch from 0aed1fb to 26ad8ae Compare November 21, 2026 10:14
@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

Gluten's Velox now includes facebookincubator/velox#20126 (bff02cfc4),
which exports the children of a struct's null rows as null, and #20259,
which exports only the elements of non-null array and map rows. So the
export no longer reads the undefined values a CASE WHEN or a join leaves
under those rows.

- Remove the check that kept timestamps, strings, binaries, arrays and
  maps inside a nullable struct on lance-spark's writer, and its row in
  VeloxLance.md.
- The test for those columns now checks that they are offloaded and
  read back as written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@malinjawi

Copy link
Copy Markdown
Contributor Author

@zhouyuan @sezruby @LuciferYang @rajarajangs thanks for all the reviews so far. This PR has grown quite a bit, so I'll split it into smaller PRs and land them one at a time. The first one is #13732, which moves the Lance scan into a new gluten-lance module with no behaviour change. Could you take a look when you get a chance? I'll keep this PR open as the full picture and rebase it as the pieces go in.

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

@malinjawi this seems a big patch, could you please break the PR into smaller ones? I can see a pattern as below:
PR 1: Build and module setup
PR 2: Native append for flat schemas
PR 3: Overwrite, CTAS and RTAS and rest

class VeloxLanceConfig(conf: SQLConf) extends GlutenCoreConfig(conf) {
import VeloxLanceConfig._

def enableNativeWrite: Boolean = getConf(ENABLE_NATIVE_WRITE)

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 you please also add the config for read?

malinjawi added a commit to malinjawi/incubator-gluten that referenced this pull request Nov 24, 2026
As zhouyuan suggested on apache#13595, and as gluten-iceberg does, the Lance
scan transformer and its offload rule move from backends-velox/src-lance
to a new gluten-lance module. backends-velox/src-lance keeps the
component that registers them with Velox and the tests. Nothing else
changes.

The lance profile builds the module, backends-velox and the bundle depend
on it, and the CI path filters, labeler and test scripts list it. The
Scala formatter now includes the lance profile, so Lance code is
format-checked in CI, and the Spark 4.1 and 4.2 jobs run the Lance tests
like 3.5 and 4.0 do.

This is the first part of splitting apache#13595.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@malinjawi malinjawi mentioned this pull request Nov 26, 2026
13 tasks
@malinjawi malinjawi changed the title [GLUTEN-12263][VL] Offload Lance table writes to Velox [GLUTEN-13806][VL] Offload Lance table writes to Velox Nov 26, 2026

This branch has not been deployed

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants