Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
200 changes: 200 additions & 0 deletions fluss-common/src/main/java/org/apache/fluss/record/ArrowReadPlan.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.fluss.record;

import org.apache.fluss.annotation.Internal;
import org.apache.fluss.compression.ArrowCompressionFactory;
import org.apache.fluss.memory.MemorySegment;
import org.apache.fluss.row.ProjectedRow;
import org.apache.fluss.row.arrow.ArrowReader;
import org.apache.fluss.shaded.arrow.org.apache.arrow.memory.BufferAllocator;
import org.apache.fluss.shaded.arrow.org.apache.arrow.vector.TypeLayout;
import org.apache.fluss.shaded.arrow.org.apache.arrow.vector.VectorSchemaRoot;
import org.apache.fluss.shaded.arrow.org.apache.arrow.vector.ipc.message.ArrowRecordBatch;
import org.apache.fluss.shaded.arrow.org.apache.arrow.vector.types.pojo.Field;
import org.apache.fluss.types.RowType;
import org.apache.fluss.utils.ArrowUtils;

import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;

/**
* Reads Arrow record batches of one source schema. The loaded vectors, the buffers selected before
* decompression and the output row mapping are all derived from the same selected source fields, so
* they cannot disagree.
*
* <p>The plan owns a {@link VectorSchemaRoot} that is reused across batches: each {@link
* #load(MemorySegment, int, int)} replaces the buffers of the previous one, and {@link #clear()}
* releases them once a batch has been consumed.
*/
@Internal
@NotThreadSafe
public final class ArrowReadPlan implements AutoCloseable {
private final BufferAllocator allocator;
private final RowType loadedRowType;
private final VectorSchemaRoot root;
// null when every source field is loaded and no buffer needs to be skipped
@Nullable private final int[] nodeIndexes;
@Nullable private final int[] bufferIndexes;
private final int nodeCount;
private final int bufferCount;
// null when loaded rows can be returned as-is
@Nullable private final int[] outputMapping;

/**
* Creates a plan reading batches of {@code sourceType} into {@code allocator}.
*
* @param sourceType the row type of the serialized batch
* @param outputToSource maps each output field to its source field (-1 if absent), or null if
* the output fields are the source fields
* @param selectedFields the output fields read by the caller; unselected ones are never loaded
*/
ArrowReadPlan(
RowType sourceType,
@Nullable int[] outputToSource,
int[] selectedFields,
BufferAllocator allocator) {
int sourceFieldCount = sourceType.getFieldCount();
int[] mapping = outputToSource;
if (mapping == null) {
mapping = new int[sourceFieldCount];
Arrays.setAll(mapping, i -> i);
}
BitSet sourceFields = new BitSet(sourceFieldCount);
for (int selectedField : selectedFields) {
if (mapping[selectedField] >= 0) {
sourceFields.set(mapping[selectedField]);
}
}
int[] selectedSourceFields = sourceFields.stream().toArray();
boolean pruneBuffers = selectedSourceFields.length < sourceFieldCount;

this.allocator = allocator;
this.loadedRowType = pruneBuffers ? sourceType.project(selectedSourceFields) : sourceType;
this.outputMapping =
outputToSource == null && !pruneBuffers
? null
: toLoadedPositions(mapping, selectedSourceFields, sourceFieldCount);

List<Field> flattenedFields = new ArrayList<>();
BitSet selectedNodes = new BitSet();
List<Field> fields = ArrowUtils.toArrowSchema(sourceType).getFields();
for (int i = 0; i < fields.size(); i++) {
int start = flattenedFields.size();
flattenField(fields.get(i), flattenedFields);
if (sourceFields.get(i)) {
selectedNodes.set(start, flattenedFields.size());
}
}
BitSet selectedBuffers = new BitSet();
int bufferIndex = 0;
for (int i = 0; i < flattenedFields.size(); i++) {
int count = TypeLayout.getTypeBufferCount(flattenedFields.get(i).getType());
if (selectedNodes.get(i)) {
selectedBuffers.set(bufferIndex, bufferIndex + count);
}
bufferIndex += count;
}
this.nodeCount = flattenedFields.size();
this.bufferCount = bufferIndex;
this.nodeIndexes = pruneBuffers ? selectedNodes.stream().toArray() : null;
this.bufferIndexes = pruneBuffers ? selectedBuffers.stream().toArray() : null;
this.root = VectorSchemaRoot.create(ArrowUtils.toArrowSchema(loadedRowType), allocator);
}

/** Returns the row type of the loaded vectors: the selected source fields in source order. */
public RowType getLoadedRowType() {
return loadedRowType;
}

/**
* Deserializes the Arrow batch and loads only the selected fields; buffers of unselected fields
* are neither copied nor decompressed. Buffers of a previously loaded batch are replaced.

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 full IPC body is still deserialized and copied before pruning. Please describe this as skipping vector loading and decompression for unselected columns, rather than saying their buffers are not copied.

*/
public ArrowReader load(MemorySegment segment, int arrowOffset, int arrowLength) {
try (ArrowRecordBatch batch =
nodeIndexes == null
? ArrowUtils.deserializeArrowRecordBatch(
segment, arrowOffset, arrowLength, allocator)
: ArrowUtils.deserializeProjectedArrowRecordBatch(
segment,
arrowOffset,
arrowLength,
allocator,
nodeCount,
bufferCount,
nodeIndexes,
bufferIndexes)) {
new FlussVectorLoader(root, ArrowCompressionFactory.INSTANCE).load(batch);
return ArrowUtils.createArrowReader(root, loadedRowType);
} catch (RuntimeException | Error e) {
// The root is shared across batches, so partially loaded buffers must not linger.
root.clear();
throw e;
}
}

/**
* Creates a row view exposing loaded rows at the output positions expected by the caller, or
* null if loaded rows already match them. Only selected output fields may be read; the others,
* like fields absent from the source schema, are reported as null.
*/
@Nullable
public ProjectedRow createOutputRow() {
return outputMapping == null ? null : ProjectedRow.from(outputMapping);
}

/** Releases the buffers of the last loaded batch while keeping the plan reusable. */
public void clear() {
root.clear();
}

@Override
public void close() {
root.close();
}

private static int[] toLoadedPositions(
int[] outputToSource, int[] selectedSourceFields, int sourceFieldCount) {
int[] sourceToLoaded = new int[sourceFieldCount];
Arrays.fill(sourceToLoaded, -1);
for (int i = 0; i < selectedSourceFields.length; i++) {
sourceToLoaded[selectedSourceFields[i]] = i;
}
int[] outputToLoaded = new int[outputToSource.length];
for (int i = 0; i < outputToSource.length; i++) {
int sourceField = outputToSource[i];
outputToLoaded[i] = sourceField < 0 ? -1 : sourceToLoaded[sourceField];
}
return outputToLoaded;
}

private static void flattenField(Field field, List<Field> flattenedFields) {
flattenedFields.add(field);
for (Field child : field.getChildren()) {
flattenField(child, flattenedFields);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,8 @@
import org.apache.fluss.row.ProjectedRow;
import org.apache.fluss.row.arrow.ArrowReader;
import org.apache.fluss.row.columnar.ColumnarRow;
import org.apache.fluss.shaded.arrow.org.apache.arrow.memory.BufferAllocator;
import org.apache.fluss.shaded.arrow.org.apache.arrow.vector.VectorSchemaRoot;
import org.apache.fluss.types.DataType;
import org.apache.fluss.types.RowType;
import org.apache.fluss.utils.ArrowUtils;
import org.apache.fluss.utils.CloseableIterator;
import org.apache.fluss.utils.IOUtils;
import org.apache.fluss.utils.MurmurHashUtils;
Expand Down Expand Up @@ -244,21 +241,20 @@ public CloseableIterator<LogRecord> records(ReadContext context) {
int schemaId = schemaId();
long timestamp = commitTimestamp();
LogFormat logFormat = context.getLogFormat();
RowType rowType = context.getRowType(schemaId);
ProjectedRow outputProjection = context.getOutputProjectedRow(schemaId);

switch (logFormat) {
case ARROW:
return columnRecordIterator(
rowType,
outputProjection,
context.getVectorSchemaRoot(schemaId),
context.getBufferAllocator(),
timestamp);
return columnRecordIterator(context.getArrowReadPlan(schemaId), timestamp);
case INDEXED:
return rowRecordIterator(rowType, outputProjection, timestamp);
return rowRecordIterator(
context.getRowType(schemaId),
context.getOutputProjectedRow(schemaId),
timestamp);
case COMPACTED:
return compactedRowRecordIterator(rowType, outputProjection, timestamp);
return compactedRowRecordIterator(
context.getRowType(schemaId),
context.getOutputProjectedRow(schemaId),
timestamp);
default:
throw new IllegalArgumentException("Unsupported log format: " + logFormat);
}
Expand Down Expand Up @@ -388,23 +384,17 @@ public void close() {}
};
}

private CloseableIterator<LogRecord> columnRecordIterator(
RowType rowType,
@Nullable ProjectedRow outputProjection,
VectorSchemaRoot root,
BufferAllocator allocator,
long timestamp) {
private CloseableIterator<LogRecord> columnRecordIterator(ArrowReadPlan plan, long timestamp) {
ProjectedRow outputProjection = plan.createOutputRow();
boolean isAppendOnly = isAppendOnly();
int recordsDataOffset = recordsDataOffset();
if (isAppendOnly) {
// append only batch, no change type vector,
// the start of the arrow data is the beginning of the batch records
int arrowOffset = position + recordsDataOffset;
int arrowLength = sizeInBytes() - recordsDataOffset;
ArrowReader reader =
ArrowUtils.createArrowReader(
segment, arrowOffset, arrowLength, root, allocator, rowType);
return new ArrowLogRecordIterator(root, reader, timestamp, outputProjection) {
ArrowReader reader = plan.load(segment, arrowOffset, arrowLength);
return new ArrowLogRecordIterator(plan, reader, timestamp, outputProjection) {
@Override
protected ChangeType getChangeType(int rowId) {
return ChangeType.APPEND_ONLY;
Expand All @@ -418,10 +408,8 @@ protected ChangeType getChangeType(int rowId) {
new ChangeTypeVector(segment, changeTypeOffset, getRecordCount());
int arrowOffset = changeTypeOffset + changeTypeVector.sizeInBytes();
int arrowLength = sizeInBytes() - recordsDataOffset - changeTypeVector.sizeInBytes();
ArrowReader reader =
ArrowUtils.createArrowReader(
segment, arrowOffset, arrowLength, root, allocator, rowType);
return new ArrowLogRecordIterator(root, reader, timestamp, outputProjection) {
ArrowReader reader = plan.load(segment, arrowOffset, arrowLength);
return new ArrowLogRecordIterator(plan, reader, timestamp, outputProjection) {
@Override
protected ChangeType getChangeType(int rowId) {
return changeTypeVector.getChangeType(rowId);
Expand All @@ -436,18 +424,18 @@ private boolean isAppendOnly() {

/** The basic implementation for Arrow log record iterator. */
private abstract class ArrowLogRecordIterator extends LogRecordIterator {
private final VectorSchemaRoot root;
private final ArrowReadPlan plan;
private final ArrowReader reader;
private final long timestamp;
private int rowId = 0;
@Nullable private final ProjectedRow outputProjection;

private ArrowLogRecordIterator(
VectorSchemaRoot root,
ArrowReadPlan plan,
ArrowReader reader,
long timestamp,
@Nullable ProjectedRow outputProjection) {
this.root = root;
this.plan = plan;
this.reader = reader;
this.timestamp = timestamp;
this.outputProjection = outputProjection;
Expand Down Expand Up @@ -484,7 +472,7 @@ protected boolean ensureNoneRemaining() {
public void close() {
// Clear old buffers before the next batch load to avoid temporary
// duplication of buffers (old + new) during loadFieldBuffers.
root.clear();
plan.clear();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@
import org.apache.fluss.annotation.PublicEvolving;
import org.apache.fluss.metadata.LogFormat;
import org.apache.fluss.row.ProjectedRow;
import org.apache.fluss.shaded.arrow.org.apache.arrow.memory.BufferAllocator;
import org.apache.fluss.shaded.arrow.org.apache.arrow.vector.VectorSchemaRoot;
import org.apache.fluss.types.RowType;
import org.apache.fluss.utils.CloseableIterator;

Expand Down Expand Up @@ -199,27 +197,22 @@ interface ReadContext {
RowType getRowType(int schemaId);

/**
* Gets the Arrow {@link VectorSchemaRoot} for the given schema id. The returned schema root
* is projected if the record batch is a projected {@link LogRecordBatch}.
* Gets the plan to read {@link LogFormat#ARROW} record batches of the given schema id. The
* plan decides which fields are loaded (projected if the record batch is a projected {@link
* LogRecordBatch}, or if the reader only selects some fields) and how loaded rows map to
* output rows. Client-side field selection does not change the serialized batch or its
* checksum.
*
* <p>The schema root is used to read the Arrow records in the batch, if this is a {@link
* LogFormat#ARROW} record batch.
*
* <p><b>Lifecycle:</b> DO NOT close the returned {@link VectorSchemaRoot} because it is
* shared across multiple batches. Each new batch load replaces the old buffers inside the
* same root. To avoid temporary buffer duplication (old and new buffers coexisting during
* the load), callers should call {@link VectorSchemaRoot#clear()} after finishing each
* batch to release old buffers immediately before the next batch is loaded. If you need to
* retain the data beyond the current batch, use {@link VectorSchemaRoot#slice(int)} to
* create an independent copy and close it after use.
* <p><b>Lifecycle:</b> DO NOT close the returned plan because it is shared across multiple
* batches. Each new batch load replaces the old buffers inside the same plan. To avoid
* temporary buffer duplication (old and new buffers coexisting during the load), callers
* should call {@link ArrowReadPlan#clear()} after finishing each batch to release old
* buffers immediately before the next batch is loaded.
*
* @param schemaId The schema id of the record batch.
* @return The (maybe projected) schema root of the record batch.
* @return The read plan of the record batch.
*/
VectorSchemaRoot getVectorSchemaRoot(int schemaId);

/** Gets the buffer allocator. */
BufferAllocator getBufferAllocator();
ArrowReadPlan getArrowReadPlan(int schemaId);

/**
* If the read context defines an output projection (for example, log records may add new
Expand All @@ -228,6 +221,9 @@ interface ReadContext {
* The returned object is used by readers to transform or materialize rows according to the
* output projection. Returns {@code null} if no output projection is configured.
*
* <p>For {@link LogFormat#ARROW}, this is the output row of {@link #getArrowReadPlan(int)},
* on which only the selected fields may be read.
*
* @param schemaId the current row schema id
* @return a {@link ProjectedRow} describing the output projection, or {@code null} if none
*/
Expand Down
Loading
Loading