Skip to content

Commit d9bd91f

Browse files
vuanhphungIsaac
andauthored
Read Arrow rows directly from vectors with per-batch converters (#628)
* Read Arrow rows directly from vectors with per-batch scalar converters Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com> * Pin batch changes and legacy Arrow value semantics Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com> * Guard legacy Arrow fallbacks and scalar conversion semantics Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com> * Strengthen Arrow fallback tests and kernel e2e coverage Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com> --------- Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com>
1 parent fc085d4 commit d9bd91f

7 files changed

Lines changed: 608 additions & 40 deletions

File tree

‎.github/workflows/kernel-e2e.yml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ jobs:
160160
# Run when the kernel driver layer, the napi binding contract, kernel
161161
# e2e tests, this workflow, the kernel revision pin, or core deps
162162
# move.
163-
if echo "$CHANGED" | grep -qE "^(lib/kernel/|native/kernel/|tests/e2e/kernel/|tests/unit/kernel/|\.github/workflows/kernel-e2e\.yml|KERNEL_REV|package\.json|package-lock\.json)"; then
163+
if echo "$CHANGED" | grep -qE "^(lib/kernel/|lib/result/|native/kernel/|tests/e2e/kernel/|tests/e2e/utils/rowMaterialization\.ts|tests/unit/kernel/|\.github/workflows/kernel-e2e\.yml|KERNEL_REV|package\.json|package-lock\.json)"; then
164164
echo "run_tests=true" >> "$GITHUB_OUTPUT"
165165
else
166166
echo "run_tests=false" >> "$GITHUB_OUTPUT"
@@ -410,6 +410,6 @@ jobs:
410410
completed_at: new Date().toISOString(),
411411
output: {
412412
title: 'Skipped — no kernel-relevant changes',
413-
summary: 'No files under lib/kernel/, native/kernel/, tests/e2e/kernel/, tests/unit/kernel/, KERNEL_REV, package.json, or package-lock.json changed.'
413+
summary: 'No files under lib/kernel/, lib/result/, native/kernel/, tests/e2e/kernel/, tests/e2e/utils/rowMaterialization.ts, tests/unit/kernel/, KERNEL_REV, package.json, or package-lock.json changed.'
414414
}
415415
});

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
## Unreleased
44

5+
- Reduce Arrow row materialization overhead on both backends by reading vectors directly and resolving scalar conversions once per batch. Object and array row values are unchanged.
56
- The Thrift token federation exchange (`enableTokenFederation`) now goes through the connection's agent, so `proxy`, `checkServerCertificate`, `customCaCert` and `clientCert`/`clientKey` apply to it. Previously it connected directly with Node's default agent, so behind a required proxy the exchange failed and the driver fell back to the original token. (#611)
67
- Kernel backend: a failed status poll while waiting for a statement (a `runAsync: true` statement, or a default execution that outlives the server's inline wait) and a failed result fetch in `hasMoreRows()` now throw the mapped driver error, such as `HiveDriverError: HTTP 500: Internal Server Error` once retries on HTTP 5xx run out, instead of a raw `Error` whose message is the internal `__databricks_error__:{...}` envelope. As in `fetchChunk()`, a failed fetch in `hasMoreRows()` also closes the statement. (#608)
78
- Honor `cloudFetchConcurrentDownloads` when opening kernel sessions, with a default window of 16 and explicit chunk-setting overrides. Values other than positive safe integers raise `HiveDriverError` at session open.

‎lib/result/ArrowResultConverter.ts‎

Lines changed: 72 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ const { isArrowBigNumSymbol, bigNumToBigInt } = arrowUtils;
2626

2727
type ArrowSchema = Schema<TypeMap>;
2828
type ArrowSchemaField = Field<DataType<Type, TypeMap>>;
29+
type ValueConverter = (value: any) => any;
30+
31+
const identity: ValueConverter = (value) => value;
2932

3033
/**
3134
* Metadata key carrying the original Arrow `Duration` time unit on fields
@@ -284,11 +287,8 @@ export default class ArrowResultConverter implements IResultsProvider<Array<any>
284287
let result: Array<any>;
285288
if (this.disableRowMaterialization) {
286289
result = new Array(batchRows).fill(null);
287-
} else if (this.rowMode === 'array') {
288-
result = this.getRowArrays(batch, batchRows);
289290
} else {
290-
const table = new Table(batch);
291-
result = this.getRows(table.schema, table.toArray().slice(0, this.remainingRows));
291+
result = this.getRows(batch, batchRows);
292292
}
293293

294294
// Reduce remaining rows count by a count of rows we just processed.
@@ -349,7 +349,7 @@ export default class ArrowResultConverter implements IResultsProvider<Array<any>
349349
}
350350
}
351351

352-
private getRows(schema: ArrowSchema, rows: Array<StructRow | MapRow>): Array<any> {
352+
private getObjectRows(schema: ArrowSchema, rows: Array<StructRow | MapRow>): Array<any> {
353353
return rows.map((row) => {
354354
// First, convert native Arrow values to corresponding plain JS objects
355355
const record = this.convertArrowTypes(row, undefined, schema.fields, undefined);
@@ -358,29 +358,79 @@ export default class ArrowResultConverter implements IResultsProvider<Array<any>
358358
});
359359
}
360360

361-
// Reads cells by column index, so same-named columns are all kept. Fields come from the
362-
// batch data type: `RecordBatch.schema` merges same-named fields into one type.
363-
private getRowArrays(batch: RecordBatch<TypeMap>, rowCount: number): Array<Array<any>> {
364-
const fields: Array<ArrowSchemaField> = batch.data.type.children;
361+
private getRows(batch: RecordBatch<TypeMap>, rowCount: number): Array<any> {
362+
const arrayRows = this.rowMode === 'array';
363+
const fields: Array<ArrowSchemaField> = arrayRows ? batch.data.type.children : batch.schema.fields;
364+
const names = this.schema.map((column) => column.columnName);
365+
if (
366+
!arrayRows &&
367+
(new Set(names).size !== names.length ||
368+
names.includes('__proto__') ||
369+
fields.length !== names.length ||
370+
fields.some((field, index) => field.name !== names[index]))
371+
) {
372+
const table = new Table(batch);
373+
return this.getObjectRows(table.schema, table.toArray().slice(0, rowCount));
374+
}
365375
const vectors = this.schema.map((column, index) => batch.getChildAt(index));
366-
const rows: Array<Array<any>> = [];
367-
for (let i = 0; i < rowCount; i += 1) {
368-
const row: Array<any> = [];
369-
for (let j = 0; j < this.schema.length; j += 1) {
370-
const field = fields[j];
371-
const value = this.convertArrowTypes(
372-
vectors[j]?.get(i) ?? null,
373-
field?.type,
374-
field?.type.children || [],
375-
field,
376-
);
377-
row.push(this.convertThriftColumnValue(this.schema[j], value));
376+
const keys = arrayRows ? names.map((name, index) => index) : names;
377+
const converters = this.schema.map((column, index) => {
378+
const convert = this.getArrowValueConverter(fields[index]);
379+
const descriptor = column.typeDesc.types[0]?.primitiveEntry;
380+
const thriftType =
381+
this.preserveBigNumericPrecision &&
382+
(descriptor?.type === TTypeId.DECIMAL_TYPE || descriptor?.type === TTypeId.BIGINT_TYPE)
383+
? undefined
384+
: descriptor;
385+
return (value: any) => (value === null ? null : convertThriftValue(thriftType, convert(value)));
386+
});
387+
const rows: Array<any> = new Array(rowCount);
388+
for (let rowIndex = 0; rowIndex < rowCount; rowIndex += 1) {
389+
const row: any = arrayRows ? [] : {};
390+
for (let columnIndex = 0; columnIndex < names.length; columnIndex += 1) {
391+
const value = converters[columnIndex](vectors[columnIndex]?.get(rowIndex) ?? null);
392+
row[keys[columnIndex]] = value;
378393
}
379-
rows.push(row);
394+
rows[rowIndex] = row;
380395
}
381396
return rows;
382397
}
383398

399+
private getArrowValueConverter(field?: ArrowSchemaField): ValueConverter {
400+
const valueType = field?.type;
401+
if (DataType.isTimestamp(valueType)) {
402+
return (value) => new Date(value);
403+
}
404+
if (DataType.isInterval(valueType)) {
405+
return (value) => formatArrowInterval(value, valueType);
406+
}
407+
if (DataType.isDecimal(valueType)) {
408+
return this.preserveBigNumericPrecision
409+
? (value) => bigNumDecimalToString(bigNumToBigInt(value), valueType.scale)
410+
: (value) => Number(bigNumToBigInt(value)) / 10 ** valueType.scale;
411+
}
412+
if (DataType.isBinary(valueType) || DataType.isFixedSizeBinary(valueType)) {
413+
return (value) => Buffer.from(value);
414+
}
415+
if (DataType.isInt(valueType) && valueType.bitWidth === 64) {
416+
const durationUnit = field?.metadata.get(DURATION_UNIT_METADATA_KEY);
417+
if (durationUnit) {
418+
return (value) => formatDurationToIntervalDayTime(value, durationUnit);
419+
}
420+
return this.preserveBigNumericPrecision ? identity : Number;
421+
}
422+
if (
423+
DataType.isBool(valueType) ||
424+
DataType.isInt(valueType) ||
425+
DataType.isFloat(valueType) ||
426+
DataType.isUtf8(valueType) ||
427+
DataType.isDate(valueType)
428+
) {
429+
return identity;
430+
}
431+
return (value) => this.convertArrowTypes(value, valueType, valueType?.children || [], field);
432+
}
433+
384434
private convertArrowTypes(
385435
value: any,
386436
valueType: DataType | undefined,
@@ -525,20 +575,4 @@ export default class ArrowResultConverter implements IResultsProvider<Array<any>
525575

526576
return result;
527577
}
528-
529-
// Per-cell equivalent of `convertThriftTypes`, used by array rows. Kept separate so
530-
// the default object path stays as is.
531-
private convertThriftColumnValue(column: TColumnDesc, value: any): any {
532-
if (value === null) {
533-
return null;
534-
}
535-
const typeDescriptor = column.typeDesc.types[0]?.primitiveEntry;
536-
if (
537-
this.preserveBigNumericPrecision &&
538-
(typeDescriptor?.type === TTypeId.DECIMAL_TYPE || typeDescriptor?.type === TTypeId.BIGINT_TYPE)
539-
) {
540-
return value;
541-
}
542-
return convertThriftValue(typeDescriptor, value);
543-
}
544578
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import rowMaterializationTests from '../utils/rowMaterialization';
2+
3+
rowMaterializationTests(true);
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import rowMaterializationTests from './utils/rowMaterialization';
2+
3+
rowMaterializationTests(false);
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import { expect } from 'chai';
2+
import { DBSQLClient } from '../../../lib';
3+
import { ConnectionOptions } from '../../../lib/contracts/IDBSQLClient';
4+
import { InternalConnectionOptions } from '../../../lib/contracts/InternalConnectionOptions';
5+
import config from './config';
6+
7+
const largeInteger = BigInt('9007199254740993');
8+
9+
export default function rowMaterializationTests(useKernel: boolean) {
10+
describe(`Arrow row materialization (${useKernel ? 'kernel' : 'Thrift'})`, () => {
11+
for (const rowMode of ['object', 'array'] as const) {
12+
for (const useArrowNativeTypes of [false, true]) {
13+
for (const preserveBigNumericPrecision of [false, true]) {
14+
it(`preserves values (${rowMode}, native=${useArrowNativeTypes}, precision=${preserveBigNumericPrecision})`, async () => {
15+
const client = new DBSQLClient();
16+
const base = client.getConfig();
17+
client.getConfig = () => ({ ...base, useArrowNativeTypes });
18+
try {
19+
await client.connect({
20+
host: config.host,
21+
path: config.path,
22+
token: config.token,
23+
useKernel,
24+
preserveBigNumericPrecision,
25+
} as ConnectionOptions & InternalConnectionOptions);
26+
const session = await client.openSession();
27+
try {
28+
const operation = await session.executeStatement(
29+
`
30+
SELECT CAST(id AS INT) AS id,
31+
IF(id = 1, NULL, true) AS b,
32+
IF(id = 1, NULL, CAST(-7 AS TINYINT)) AS tiny,
33+
IF(id = 1, NULL, CAST(300 AS SMALLINT)) AS small,
34+
IF(id = 1, NULL, CAST(9007199254740993 AS BIGINT)) AS big,
35+
IF(id = 1, NULL, CAST(1.25 AS DECIMAL(30,4))) AS dec,
36+
IF(id = 1, NULL, CAST(1.25 AS FLOAT)) AS flt,
37+
IF(id = 1, NULL, CAST(-2.5 AS DOUBLE)) AS dbl,
38+
IF(id = 1, NULL, 'hello🌍') AS txt,
39+
IF(id = 1, NULL, unhex('0080ff')) AS bin,
40+
IF(id = 1, NULL, DATE '2026-01-02') AS dt,
41+
IF(id = 1, NULL, TIMESTAMP '2026-01-02 03:04:05') AS ts,
42+
IF(id = 1, NULL, array(1, NULL, 3)) AS arr,
43+
IF(id = 1, NULL, map('a', 1, 'b', NULL)) AS mp,
44+
IF(id = 1, NULL, named_struct('items', array(1, NULL), 'text', 'x')) AS st,
45+
IF(id = 1, NULL, INTERVAL '1-2' YEAR TO MONTH) AS ym,
46+
IF(id = 1, NULL, INTERVAL '1 02:03:04.123456' DAY TO SECOND) AS day_time
47+
FROM range(3) ORDER BY id
48+
`,
49+
{ rowMode },
50+
);
51+
try {
52+
const precise = preserveBigNumericPrecision;
53+
const values = {
54+
id: 0,
55+
b: true,
56+
tiny: -7,
57+
small: 300,
58+
big: precise ? largeInteger : 9007199254740992,
59+
dec: precise ? '1.2500' : 1.25,
60+
flt: 1.25,
61+
dbl: -2.5,
62+
txt: 'hello🌍',
63+
bin: Buffer.from([0, 128, 255]),
64+
dt: new Date('2026-01-02T00:00:00Z'),
65+
ts: useKernel || useArrowNativeTypes ? new Date('2026-01-02T03:04:05Z') : '2026-01-02 03:04:05',
66+
arr: [1, null, 3],
67+
mp: { a: 1, b: null },
68+
st: { items: [1, null], text: 'x' },
69+
ym: '1-2',
70+
day_time: '1 02:03:04.123456000',
71+
};
72+
const expected = [
73+
values,
74+
Object.fromEntries(Object.keys(values).map((key) => [key, key === 'id' ? 1 : null])),
75+
{ ...values, id: 2 },
76+
];
77+
expect(await operation.fetchAll()).to.deep.equal(
78+
rowMode === 'array' ? expected.map(Object.values) : expected,
79+
);
80+
} finally {
81+
await operation.close();
82+
}
83+
} finally {
84+
await session.close();
85+
}
86+
} finally {
87+
await client.close();
88+
}
89+
});
90+
}
91+
}
92+
}
93+
});
94+
}

0 commit comments

Comments
 (0)