Copilot commented on code in PR #13800:
URL: https://github.com/apache/gluten/pull/13800#discussion_r4704558274
##########
docs/backends/velox/velox-columnar-table-cache.md:
##########
@@ -0,0 +1,234 @@
+---
+layout: page
+title: Velox Columnar Table Cache
+nav_order: 11
+---
+
+# Velox Columnar Table Cache
+
+This document describes how the Velox backend implements Spark's in-memory
table cache
+(`df.cache()`, `df.persist()`, `CACHE TABLE`) and the
`InMemoryTableScanExecTransformer` that reads it, the
+formats the cached batches are stored in, and how the implementation compares
with the Arrow-based
+cache serializer in Apache Spark.
+
+## 1. Overview
+
+Gluten plugs a columnar serializer into Spark's pluggable
`CachedBatchSerializer` API, and the
+planner treats the cache scan as a Velox columnar operator. The scan runs as
+`InMemoryTableScanExecTransformer`, a subclass of Spark's
`InMemoryTableScanExec` that adds read
+metrics (see [Scan metrics](#scan-metrics)). Because it is a subclass, Spark
code that matches the
+concrete `InMemoryTableScanExec`, such as AQE table cache stages and the SQL
UI plan graph, keeps
+working.
+
+### Enabling
+
+`spark.gluten.sql.columnar.tableCache` is a static configuration and defaults
to `true`. When it is
+on, `VeloxListenerApi` sets on the driver:
+
+```
+spark.sql.cache.serializer =
org.apache.spark.sql.execution.ColumnarCachedBatchSerializer
+```
+
+This overrides any value the user sets for `spark.sql.cache.serializer`. To
use another cache
+serializer, set `spark.gluten.sql.columnar.tableCache=false`.
+
+Every `df.cache()` then takes Spark's normal path, `CacheManager` →
`InMemoryRelation` →
+`CachedRDDBuilder`, with `ColumnarCachedBatchSerializer` doing the conversion.
+
+### Planner integration
+
+| Code | Role |
+|---|---|
+| `VeloxBackend.batchTypeOf` | Tags an `InMemoryTableScanExec` whose
`supportsColumnar` is true and whose serializer is
`ColumnarCachedBatchSerializer` as `VeloxBatchType`, so Velox operators read
its output without a transition |
+| `PlanUtil.isGlutenTableCache` | Identifies such scans, including when AQE
wraps them in a `TableCacheQueryStage` |
+| `MiscColumnarRules.RemoveGlutenTableCacheColumnarToRow` | Removes a
`ColumnarToRow` placed above the cache scan, because the scan converts to rows
itself (see [Read path](#4-read-path)) |
+| `VeloxTableCacheScanRule` | Replaces an `InMemoryTableScanExec` over a
Gluten cache with `InMemoryTableScanExecTransformer`. Registered as a query
stage preparation rule, which runs before AQE wraps the scan in a table cache
stage, and as a final columnar rule for plans run without AQE |
+| `ExpandFallbackPolicy` | Counts a Gluten table cache under a fallen-back
operator as a transition cost, which biases the policy against falling back a
stage that reads the cache |
+
+### Write path
+
+`ColumnarCachedBatchSerializer.convertColumnarBatchToCachedBatch`:
+
+1. `supportsColumnarInput` / `supportsColumnarOutput` validate the schema with
+ `ValidatorApi.doSchemaValidate`. If the schema is not supported, the whole
relation is delegated
+ to Spark's row-based `DefaultCachedBatchSerializer`.
+2. If the cached plan produces rows, `convertInternalRowToCachedBatch` first
converts them with
+ `RowToVeloxColumnarExec.toColumnarBatchIterator`.
+3. Each batch goes through `VeloxColumnarBatches.ensureVeloxBatch` and is
serialized over JNI by
+ `ColumnarBatchSerializerJniWrapper`, in one of the formats described in
+ [section 3](#3-cached-batch-formats).
+4. The result is a `CachedColumnarBatch(numRows, sizeInBytes, bytes, stats,
schema)`, which extends
+ `SimpleMetricsCachedBatch`. `sizeInBytes` is the serialized length, so
Spark's memory accounting
+ matches the real footprint.
+
+Cached batches are not resized: each input Velox batch becomes one cached
batch.
+
+## 2. Where serialization is implemented
+
+The serializer is a Gluten C++ class. It delegates the encoding of vectors to
Velox's
+`PrestoVectorSerde`; no Velox patch is involved.
+
+| Layer | Location |
+|---|---|
+| Spark `CachedBatchSerializer` |
`backends-velox/src/main/scala/org/apache/spark/sql/execution/ColumnarCachedBatchSerializer.scala`
|
+| JNI entry points | `ColumnarBatchSerializerJniWrapper` →
`cpp/core/jni/JniWrapper.cc` (`serialize`, `serializeWithStats`, `serializeV3`,
`serializeWithStatsV3`, `init`, `deserialize`, `deserializeWithProjection`) |
+| Backend-neutral interface |
`cpp/core/operators/serializer/ColumnarBatchSerializer.h`. Backends that do not
implement the V2/V3 hooks return null, and the JVM falls back to an older
format |
+| Factory | `VeloxRuntime::createColumnarBatchSerializer` in
`cpp/velox/compute/VeloxRuntime.cc` |
+| Implementation |
`cpp/velox/operators/serializer/VeloxColumnarBatchSerializer.{h,cc}` |
+| Vector encoding | Velox
`facebook::velox::serializer::presto::PrestoVectorSerde` |
+
+Gluten owns the frame layouts, the statistics (`computeStats`,
`buildStatsBlob`), column
+projection on read (`deserializeV3`), and `CachedColumnLoader`, a Velox
`VectorLoader` that makes
+each projected column a `LazyVector`.
+
+The serializer options are `useLosslessTimestamp=true`, `nullsFirst=false`,
and the compression
+kind from
`spark.gluten.sql.columnar.backend.velox.columnarBatchSerializerCompression`
(default
+`none`). The same class also serializes batches for broadcast exchange.
+
+## 3. Cached batch formats
+
+There are three formats. The writer uses V3. If a V3 write fails, the batch is
written as V2 when
+partition statistics are enabled, and as V1 otherwise; with the default
configuration (statistics
+disabled) a V3 failure goes straight to V1. V2 is never written unless
statistics are enabled.
+
+| | V1 (legacy) | V2 | V3 (default) |
+|---|---|---|---|
+| Velox API | `createIterativeSerializer` → `append` / `flush`: one Presto
page for the whole batch | Same as V1 | `serializeSingleColumn` per column;
each column is a self-contained blob |
+| Frame | None; `bytes` is the Presto page | `[magic FE CA 53
02][statsLen][statsBlob][bytesLen][bytesBlob]` | `[magic FE CA 53
03][statsLen][statsBlob][numRows][numCols]` followed by `[colLen][colBytes]`
per column |
+| Stored in `CachedColumnarBatch.bytes` | The Presto page | Only `bytesBlob`;
the JVM strips the frame and stores the stats in the `stats` field | The whole
frame |
+| Input vector | As produced, encodings kept | As produced, encodings kept |
`getFlattenedRowVector()`: dictionary and constant encodings are flattened
first |
+| Compression | Configured `compressionKind` | Configured `compressionKind` |
None. Velox requires `CompressionKind_NONE` for single-column serde |
+| Partition stats | None (`stats = null`) | Always | Optional; `statsLen = 0`
when stats are disabled |
+| Read | `deserialize` decodes all columns, then `ColumnarBatches.select`
projects | Same as V1 | `deserializeWithProjection` builds only the requested
columns as `LazyVector`s, decoded on first access |
+
+V1 and V2 store the same data bytes: V2's `framedSerializeWithStats` produces
its data blob through
+the same `append` / `serializeTo` path as V1 and only adds the statistics. V3
is a different
+encoding. Its per-column layout is what lets a read decode only the projected
columns; a single
+Presto page cannot be partially decoded, so V1 and V2 always decode every
cached column.
+
+The trade-off of V3 is size: data is stored uncompressed and flattened, so a
V3 cache can be larger
+than a V1/V2 cache of the same data.
+
+### Fallback between formats
+
+Two JVM-wide flags, `statsExtV3Available` and `statsExtAvailable`, start as
`true`. An
+`UnsatisfiedLinkError`, for example a newer Gluten jar with an older
`libgluten.so`, clears the flag
+for the rest of the JVM's life and the writer uses the next format. A corrupt
frame from a single
+batch only falls back for that batch; its warning is logged at most 100 times
per JVM.
+
+## 4. Read path
+
+`convertCachedBatchToColumnarBatch` creates one native deserializer per
partition (`jni.init` with
+the Arrow-exported cache schema). For each cached batch:
+
+* V3 bytes go to `deserializeWithProjection(handle, bytes, requestedColumns)`.
`requestedColumns` is
+ `null` when all columns are selected, empty for `count(*)`, and the
projected ordinals otherwise.
+ The whole frame is passed to native code.
+* V1/V2 bytes go to `deserialize`, followed by `ColumnarBatches.select` when a
subset of columns is
+ requested.
+
+`convertCachedBatchToInternalRow` decodes to Velox batches the same way and
then converts with
+`VeloxColumnarToRowExec.toRowIterator`.
+
+When a query that reads a Gluten cache falls back to vanilla Spark,
`RemoveGlutenTableCacheColumnarToRow`
+removes the explicit `ColumnarToRow`, and the vanilla operators call the
scan's row path. The
+columnar-to-row conversion of the whole cache then happens inside the
+`InMemoryTableScanExecTransformer` node. No separate node shows it in the
plan; the node reports it
+as `time of columnar to row`. The same time is also included in the parent
operator's own timing,
+for example `time in aggregation build` of a `HashAggregate` in the same
whole-stage codegen.
+
+### Scan metrics
+
+`InMemoryTableScanExecTransformer` reports:
+
+| Metric | Description |
+|---|---|
+| `number of output rows` | Rows returned by the scan |
+| `number of cached batches` | Cached batches before partition-statistics
pruning |
+| `number of cached batches read after pruning` | Cached batches left after
pruning and read |
+| `cached bytes read` | Serialized size of the cached batches read |
+| `time to read cached batches` | Time spent decoding cached batches into
Velox batches |
Review Comment:
For the default V3 format, this timer covers cache iteration and lazy batch
construction, not the column decoding performed later by the consumer. Calling
it decoding time can mislead readers diagnosing slow cache scans. Describe
batch retrieval separately from deferred V3 decoding.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]