Skip to content
Draft
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
2 changes: 1 addition & 1 deletion packages/amp/src/arrow-flight/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ const make = Effect.gen(function* () {

// Setup the query headers
const headers = new Headers()
if (Predicate.isNotUndefined(options?.stream)) {
if (options?.stream === true) {
headers.set("amp-stream", "true")
}
if (Predicate.isNotUndefined(options?.resumeWatermark)) {
Expand Down
10 changes: 10 additions & 0 deletions packages/amp/src/internal/arrow-flight-ipc/Decoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ export const decodeRecordBatch = (

let nodeIndex = 0
let bufferIndex = 0
let variadicBufferCountIndex = 0

function decodeField(field: ArrowField): DecodedColumn {
const node = recordBatch.nodes[nodeIndex++]
Expand All @@ -234,6 +235,15 @@ export const decodeRecordBatch = (
for (let i = 0; i < bufferTypes.length; i++) {
buffers.push(extractedBuffers[bufferIndex++])
}
// View types are followed by a variable number of data buffers, whose
// count is given by the record batch's variadic buffer counts
const typeId = field.type.typeId
if (!field.dictionaryEncoding && (typeId === "utf8-view" || typeId === "binary-view")) {
const variadicBufferCount = Number(recordBatch.variadicBufferCounts[variadicBufferCountIndex++])
for (let i = 0; i < variadicBufferCount; i++) {
buffers.push(extractedBuffers[bufferIndex++])
}
}

// Decode children recursively
const children: ReadonlyArray<DecodedColumn> = field.children.map((child) => decodeField(child))
Expand Down
114 changes: 113 additions & 1 deletion packages/amp/src/internal/arrow-flight-ipc/Readers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ const BYTES_PER_INT32 = 4
const BYTES_PER_INT64 = 8
/** Number of bytes per interval (month-day-nano) value: 4 + 4 + 8 = 16 */
const BYTES_PER_INTERVAL_MONTH_DAY_NANO = 16
/** Number of bytes per view (utf8-view, binary-view): 4 + 12 = 16 */
const BYTES_PER_VIEW = 16
/** Maximum length of a view value that is stored inline in its view */
const MAX_INLINE_VIEW_LENGTH = 12
/** Number of bits per byte (for validity bitmap calculations) */
const BITS_PER_BYTE = 8

Expand Down Expand Up @@ -846,6 +850,108 @@ export const readFixedSizeBinaryValues = (
return values
}

// =============================================================================
// Views
// =============================================================================

/**
* Returns the bytes of the value at `index` in an Arrow view column.
*
* Each view is 16 bytes, starting with the value's length (32-bit integer):
* - Values of up to 12 bytes are stored inline in the remaining 12 bytes.
* - Longer values store a 4-byte prefix, then the index of the data buffer
* that holds the value and the value's offset in it (32-bit integers).
*/
const getViewBytes = (
viewsBuffer: Uint8Array,
viewsView: DataView,
dataBuffers: ReadonlyArray<Uint8Array>,
index: number
): Uint8Array => {
const viewStart = index * BYTES_PER_VIEW
const length = viewsView.getInt32(viewStart, true)
if (length <= MAX_INLINE_VIEW_LENGTH) {
return viewsBuffer.subarray(viewStart + 4, viewStart + 4 + length)
}
const bufferIndex = viewsView.getInt32(viewStart + 8, true)
const offset = viewsView.getInt32(viewStart + 12, true)
return dataBuffers[bufferIndex].subarray(offset, offset + length)
}

/**
* Reads UTF-8 encoded string values from an Arrow Utf8View column's buffers.
*
* Utf8View stores each string as a 16-byte view instead of an offset:
* 1. **Validity buffer**: Bitmap indicating which values are non-null
* 2. **Views buffer**: One 16-byte view per value, holding strings of up to 12
* bytes inline and pointing into a data buffer for longer ones
* 3. **Data buffers**: Zero or more buffers holding the strings that aren't inlined
*
* @param validityBuffer - The validity bitmap indicating which values are non-null.
* An empty buffer indicates all values are valid.
* @param viewsBuffer - The views buffer. Should contain `length * 16` bytes.
* @param dataBuffers - The data buffers that views of longer strings point into.
* @param length - The number of string values to read.
*
* @returns An array of string values (or null for invalid entries).
*
* @see {@link https://arrow.apache.org/docs/format/Columnar.html#variable-size-binary-view-layout | Arrow Variable-Size Binary View Layout}
*/
export const readUtf8ViewValues = (
validityBuffer: Uint8Array,
viewsBuffer: Uint8Array,
dataBuffers: ReadonlyArray<Uint8Array>,
length: number
): ReadonlyArray<string | null> => {
const validityChecker = createValidityChecker(validityBuffer)
const viewsView = new DataView(viewsBuffer.buffer, viewsBuffer.byteOffset, viewsBuffer.byteLength)
const values = new Array<string | null>(length)
for (let i = 0; i < length; i++) {
if (validityChecker(i)) {
values[i] = textDecoder.decode(getViewBytes(viewsBuffer, viewsView, dataBuffers, i))
} else {
values[i] = null
}
}
return values
}

/**
* Reads binary (byte array) values from an Arrow BinaryView column's buffers.
*
* BinaryView has the same layout as Utf8View, but the data is treated as raw
* bytes. The returned arrays are **copies** of the data (via `slice()`).
*
* @param validityBuffer - The validity bitmap indicating which values are non-null.
* An empty buffer indicates all values are valid.
* @param viewsBuffer - The views buffer. Should contain `length * 16` bytes.
* @param dataBuffers - The data buffers that views of longer values point into.
* @param length - The number of binary values to read.
*
* @returns An array of `Uint8Array` values (or null for invalid entries). Each
* `Uint8Array` is an independent copy of the binary data.
*
* @see {@link https://arrow.apache.org/docs/format/Columnar.html#variable-size-binary-view-layout | Arrow Variable-Size Binary View Layout}
*/
export const readBinaryViewValues = (
validityBuffer: Uint8Array,
viewsBuffer: Uint8Array,
dataBuffers: ReadonlyArray<Uint8Array>,
length: number
): ReadonlyArray<Uint8Array | null> => {
const validityChecker = createValidityChecker(validityBuffer)
const viewsView = new DataView(viewsBuffer.buffer, viewsBuffer.byteOffset, viewsBuffer.byteLength)
const values = new Array<Uint8Array | null>(length)
for (let i = 0; i < length; i++) {
if (validityChecker(i)) {
values[i] = getViewBytes(viewsBuffer, viewsView, dataBuffers, i).slice()
} else {
values[i] = null
}
}
return values
}

// =============================================================================
// Temporal
// =============================================================================
Expand Down Expand Up @@ -1503,7 +1609,7 @@ const readDictionaryEncodedValues = (
*
* **Primitive types**: Null, Bool, Int8/16/32/64, UInt8/16/32/64, Float16/32/64, Decimal128/256
*
* **String/Binary types**: Utf8, LargeUtf8, Binary, LargeBinary, FixedSizeBinary
* **String/Binary types**: Utf8, LargeUtf8, Utf8View, Binary, LargeBinary, BinaryView, FixedSizeBinary
*
* **Temporal types**: Date (day/millisecond), Time (second/milli/micro/nano),
* Timestamp (second/milli/micro/nano), Duration, Interval (year-month/day-time/month-day-nano)
Expand Down Expand Up @@ -1612,12 +1718,18 @@ export const readColumnValues = (column: DecodedColumn, registry?: DictionaryReg
case "large-utf8": {
return readLargeUtf8Values(buffers[0], buffers[1], buffers[2], length)
}
case "utf8-view": {
return readUtf8ViewValues(buffers[0], buffers[1], buffers.slice(2), length)
}
case "binary": {
return readBinaryValues(buffers[0], buffers[1], buffers[2], length)
}
case "large-binary": {
return readLargeBinaryValues(buffers[0], buffers[1], buffers[2], length)
}
case "binary-view": {
return readBinaryViewValues(buffers[0], buffers[1], buffers.slice(2), length)
}
case "fixed-size-binary": {
return readFixedSizeBinaryValues(buffers[0], buffers[1], length, type.byteWidth)
}
Expand Down
37 changes: 34 additions & 3 deletions packages/amp/src/internal/arrow-flight-ipc/RecordBatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ export const BufferType = {
/** Data buffer containing actual values */
DATA: 3,
/** Type IDs for union types */
TYPE_ID: 4
TYPE_ID: 4,
/** 16-byte views for view types (utf8-view, binary-view) */
VIEW: 5
} as const
export type BufferType = (typeof BufferType)[keyof typeof BufferType]

Expand All @@ -53,6 +55,7 @@ export type BufferType = (typeof BufferType)[keyof typeof BufferType]
* - `nodes`: One `FieldNode` per field (including nested), describing validity/length
* - `buffers`: Buffer locations within the body for all field data
* - `compression`: Optional compression info
* - `variadicBufferCounts`: The number of data buffers of each view-type field
*/
export class RecordBatch {
/**
Expand All @@ -76,16 +79,24 @@ export class RecordBatch {
*/
readonly compression: BodyCompression | undefined

/**
* The number of data buffers that follow the views buffer of each view-type
* field (utf8-view, binary-view), in the same depth-first order as `nodes`.
*/
readonly variadicBufferCounts: ReadonlyArray<bigint>

constructor(
length: bigint,
nodes: ReadonlyArray<FieldNode>,
buffers: ReadonlyArray<BufferDescriptor>,
compression?: BodyCompression | undefined
compression?: BodyCompression | undefined,
variadicBufferCounts: ReadonlyArray<bigint> = []
) {
this.length = length
this.nodes = nodes
this.buffers = buffers
this.compression = compression
this.variadicBufferCounts = variadicBufferCounts
}
}

Expand Down Expand Up @@ -272,6 +283,13 @@ export const getBufferTypesForType = (type: ArrowDataType): ReadonlyArray<Buffer
return [BufferType.VALIDITY, BufferType.LARGE_OFFSET, BufferType.DATA]
}

// View types: validity + views (followed by a variable number of data
// buffers, given by the record batch's `variadicBufferCounts`)
case "binary-view":
case "utf8-view": {
return [BufferType.VALIDITY, BufferType.VIEW]
}

// List: validity + offsets (children handled separately)
case "list": {
return [BufferType.VALIDITY, BufferType.OFFSET]
Expand Down Expand Up @@ -373,6 +391,7 @@ export class DecodedColumn {
* The layout of the buffers depends on the type:
* - Primitive: [validity, data]
* - Variable-length (utf8, binary): [validity, offsets, data]
* - View (utf8-view, binary-view): [validity, views, ...data]
* - List: [validity, offsets] + child buffers
* - Struct: [validity] + child buffers
* - etc.
Expand Down Expand Up @@ -471,6 +490,7 @@ export const parseRecordBatch = Effect.fn(function* (flightData: FlightData) {
* 1: nodes ([FieldNode]) - one per field in DFS order
* 2: buffers ([Buffer]) - buffer locations
* 3: compression (BodyCompression) - optional
* 4: variadicBufferCounts ([Int64]) - optional, one per view-type field
*/
export const parseRecordBatchTable = Effect.fn(function* (reader: FlatBufferReader, offset: number) {
// Parse length
Expand Down Expand Up @@ -523,7 +543,18 @@ export const parseRecordBatchTable = Effect.fn(function* (reader: FlatBufferRead
compression = parseBodyCompression(reader, compressionOffset)
}

return new RecordBatch(length, nodes, buffers, compression)
// Parse optional variadic buffer counts
const variadicBufferCounts: Array<bigint> = []
const variadicBufferCountsPosition = reader.getFieldPosition(offset, 4)
if (Predicate.isNotNull(variadicBufferCountsPosition)) {
const variadicBufferCountsVectorOffset = reader.readOffset(variadicBufferCountsPosition)
const count = reader.readVectorLength(variadicBufferCountsVectorOffset)
for (let i = 0; i < count; i++) {
variadicBufferCounts.push(reader.readInt64(variadicBufferCountsVectorOffset + 4 + i * 8))
}
}

return new RecordBatch(length, nodes, buffers, compression, variadicBufferCounts)
})

/**
Expand Down
30 changes: 29 additions & 1 deletion packages/amp/src/internal/arrow-flight-ipc/Schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ export const ArrowDataTypeEnum = {
DURATION: 18,
LARGE_BINARY: 19,
LARGE_UTF8: 20,
LARGE_LIST: 21
LARGE_LIST: 21,
BINARY_VIEW: 23,
UTF8_VIEW: 24
} as const
export type ArrowDataTypeEnum = (typeof ArrowDataTypeEnum)[keyof typeof ArrowDataTypeEnum]

Expand Down Expand Up @@ -174,9 +176,11 @@ export type ArrowDataType =
| DecimalType
| BinaryType
| LargeBinaryType
| BinaryViewType
| FixedSizeBinaryType
| Utf8Type
| LargeUtf8Type
| Utf8ViewType
| DateType
| TimeType
| TimestampType
Expand Down Expand Up @@ -247,6 +251,16 @@ export interface LargeBinaryType {
}
export const LargeBinaryType: LargeBinaryType = { typeId: "large-binary" }

/**
* Same as Binary, but each value is stored as a 16-byte view instead of an
* offset. Values of 12 bytes or less are inlined in the view, longer values
* are referenced by data buffer index and offset.
*/
export interface BinaryViewType {
readonly typeId: "binary-view"
}
export const BinaryViewType: BinaryViewType = { typeId: "binary-view" }

export class FixedSizeBinaryType {
readonly typeId = "fixed-size-binary"
readonly byteWidth: number
Expand All @@ -265,6 +279,14 @@ export interface LargeUtf8Type {
}
export const LargeUtf8Type: LargeUtf8Type = { typeId: "large-utf8" }

/**
* Same as Utf8, but with the view layout of BinaryView.
*/
export interface Utf8ViewType {
readonly typeId: "utf8-view"
}
export const Utf8ViewType: Utf8ViewType = { typeId: "utf8-view" }

export class DateType {
readonly typeId = "date"
readonly unit: keyof typeof DateUnit
Expand Down Expand Up @@ -605,6 +627,9 @@ const parseType = Effect.fn(function* (reader: FlatBufferReader, typeEnum: Arrow
case ArrowDataTypeEnum.LARGE_BINARY: {
return LargeBinaryType
}
case ArrowDataTypeEnum.BINARY_VIEW: {
return BinaryViewType
}
case ArrowDataTypeEnum.FIXED_SIZE_BINARY: {
return parseFixedSizeBinaryType(reader, offset)
}
Expand All @@ -614,6 +639,9 @@ const parseType = Effect.fn(function* (reader: FlatBufferReader, typeEnum: Arrow
case ArrowDataTypeEnum.LARGE_UTF8: {
return LargeUtf8Type
}
case ArrowDataTypeEnum.UTF8_VIEW: {
return Utf8ViewType
}
case ArrowDataTypeEnum.DATE: {
return parseDateType(reader, offset)
}
Expand Down
Loading
Loading