From 4f9205592c50b75118286e0c055e1a0cc1391f40 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 03:32:01 +0000 Subject: [PATCH 1/5] feat(kernel): run Volume PUT, GET and REMOVE on the kernel backend With stagingAllowedLocalPath set, the kernel backend passes the allowed paths as the Volume options, so the kernel transfers the file of a PUT, GET or REMOVE inside execution. A Volume result then returns no rows, a failed transfer raises StagingError and a local file error is shaped like a Node fs error, as on Thrift. Removes the warning that ignored stagingAllowedLocalPath on the kernel backend. Pins KERNEL_REV to databricks-sql-kernel#521 and regenerates the native typings. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- .github/workflows/kernel-e2e.yml | 2 +- CHANGELOG.md | 1 + CONNECTION_PARAMETERS.md | 7 +- KERNEL_REV | 2 +- lib/contracts/IDBSQLSession.ts | 3 +- lib/kernel/KernelErrorMapping.ts | 48 +++++- lib/kernel/KernelOperationBackend.ts | 22 ++- lib/kernel/KernelSessionBackend.ts | 43 +++--- native/kernel/index.d.ts | 30 +++- tests/e2e/README.md | 2 +- tests/e2e/kernel/staging-close-e2e.test.ts | 67 +++++++++ tests/e2e/kernel/staging-e2e.test.ts | 17 +++ tests/e2e/staging_ingestion.test.ts | 137 +----------------- tests/e2e/utils/stagingTests.ts | 127 ++++++++++++++++ .../kernel/KernelOperationBackend.test.ts | 11 ++ tests/unit/kernel/error-mapping.test.ts | 46 ++++++ tests/unit/kernel/execution.test.ts | 16 +- 17 files changed, 416 insertions(+), 165 deletions(-) create mode 100644 tests/e2e/kernel/staging-close-e2e.test.ts create mode 100644 tests/e2e/kernel/staging-e2e.test.ts create mode 100644 tests/e2e/utils/stagingTests.ts diff --git a/.github/workflows/kernel-e2e.yml b/.github/workflows/kernel-e2e.yml index 28f22293..a46af95f 100644 --- a/.github/workflows/kernel-e2e.yml +++ b/.github/workflows/kernel-e2e.yml @@ -146,7 +146,7 @@ jobs: echo "Changed files:" echo "$CHANGED" # Run when kernel code, tests, build setup, revision, or dependencies change. - if echo "$CHANGED" | grep -qE "^(lib/kernel/|lib/result/|native/kernel/|tests/e2e/kernel/|tests/e2e/utils/rowMaterialization\.ts|tests/unit/kernel/|\.github/actions/build-kernel/|\.github/workflows/kernel-e2e\.yml|KERNEL_REV|package\.json|package-lock\.json)"; then + if echo "$CHANGED" | grep -qE "^(lib/kernel/|lib/result/|native/kernel/|tests/e2e/kernel/|tests/e2e/utils/rowMaterialization\.ts|tests/e2e/utils/stagingTests\.ts|tests/unit/kernel/|\.github/actions/build-kernel/|\.github/workflows/kernel-e2e\.yml|KERNEL_REV|package\.json|package-lock\.json)"; then echo "run_tests=true" >> "$GITHUB_OUTPUT" else echo "run_tests=false" >> "$GITHUB_OUTPUT" diff --git a/CHANGELOG.md b/CHANGELOG.md index 3eaac70f..c47ea465 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ - **Behavior change:** Thrift `getSchema()` and `getResultMetadata().schema` return `{ columns: [] }` for statements without output columns when Arrow metadata has no fields. Check `columns.length` before indexing. `getMetadata()` and responses without Arrow metadata (including `arrowEnabled: false` and older protocols) retain the `Result STRING` placeholder. (#651) - Fix `fetchAll()` and `fetchChunk()` hanging on column-based results with an empty or missing schema. (#651) - Kernel backend: support SOCKS proxies through the `proxy` option. +- Kernel backend: support Volume `PUT`, `GET` and `REMOVE` when `stagingAllowedLocalPath` is set. The kernel runs the transfer inside execution, and local paths, with symlinks resolved, must be within the allowed paths (#613). ## 3.1.0 diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index feeed0a1..fbb1ea20 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -78,7 +78,7 @@ Per-statement `useCloudFetch` overrides remain unsupported on the kernel backend | Option | Type | Thrift | Kernel | Default Value | Note | | --------------------------- | ------------------------ | :----: | :----: | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `socketTimeout` | `number` (ms) | ✅ | ⚠️ | `900000` / `120000` | Kernel forwards only positive values. `0` means no timeout on Thrift but is omitted on Kernel, which then keeps its 120-second default. | +| `socketTimeout` | `number` (ms) | ✅ | ⚠️ | `900000` / `120000` | Kernel forwards only positive values. `0` means no timeout on Thrift but is omitted on Kernel, which then keeps its 120-second default. For a Volume transfer, the kernel uses it as an idle limit. | | `proxy` | `ProxyOptions` | ✅ | ⚠️ | — | `{protocol, host, port, auth}`. Kernel maps `socks` to `socks5h` (DNS at the proxy, as on Thrift) and doesn't send a SOCKS4 user ID yet. Without `proxy`, it honors `HTTPS_PROXY`, `ALL_PROXY` and `NO_PROXY` (SOCKS too); Thrift ignores them. | | `noProxy` (internal) | `string` | ❌ | ⚠️ | — | Runtime-only Kernel bypass list, forwarded as `bypassHosts` only when an explicit `proxy` is also supplied. | | `customHeaders` | `Record` | ✅ | ✅ | — | Sent on workspace, telemetry and feature-flag requests, not OAuth. Workspace calls ignore caller `Authorization`, `User-Agent`, `Content-Type`, `Content-Length`, `Transfer-Encoding`, `Connection`; Kernel also ignores `x-databricks-org-id`. | @@ -213,7 +213,7 @@ telemetry implementation, so only the options explicitly forwarded by | `maxRows` | `number \| bigint \| Int64 \| null` | ✅ | ❌ | `100000` / — | Thrift uses it for the initial Direct Results row count; `null` disables Direct Results. Kernel does not retain or forward the supplied value. | | `useCloudFetch` | `boolean` | ✅ | ❌ | `true` / — | Kernel logs and ignores this per-statement hint; Kernel result fetching owns its CloudFetch behavior. | | `useLZ4Compression` | `boolean` | ✅ | ❌ | `true` / — | Thrift uses it when supported and when the result is not CloudFetch. Kernel owns and auto-detects result compression. | -| `stagingAllowedLocalPath` | `string \| string[]` | ✅ | ❌ | — | Local allowlist for Thrift volume/staging operations. Kernel volume operations are unsupported. | +| `stagingAllowedLocalPath` | `string \| string[]` | ✅ | ✅ | — | Local allowlist for Volume operations. The kernel runs the transfer inside execution and also checks resolved symlink targets. | | `namedParameters` | `Record` | ✅ | ✅ | — | Named SQL parameters. Cannot be combined with non-empty `ordinalParameters`. Thrift requires a protocol that supports parameterized queries. | | `ordinalParameters` | `Array` | ✅ | ✅ | — | Positional SQL parameters. Cannot be combined with non-empty `namedParameters`. | | `queryTags` | `Record` | ✅ | ✅ | — | Serialized into the per-statement `query_tags` conf overlay on both. | @@ -244,8 +244,7 @@ session parameter surface. Thrift-only capabilities include custom/token-provider authentication, custom OAuth persistence, SOCKS4 user IDs, authenticated/driver-buffer telemetry knobs, -query timeout, Direct Results `maxRows`, per-statement CloudFetch/LZ4 hints, and -volume operations. +query timeout, Direct Results `maxRows`, and per-statement CloudFetch/LZ4 hints. Kernel-only capabilities include connection-pool sizing, proxy bypass hosts, independent TLS hostname verification, optional U2M disk caching, and diff --git a/KERNEL_REV b/KERNEL_REV index 418c81d3..8259df97 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -a29235cbea9532efa5572ebff010045583a19cbe +4471d5cd5ec0819037293344c1a0bf1d54f2a9d1 diff --git a/lib/contracts/IDBSQLSession.ts b/lib/contracts/IDBSQLSession.ts index 12d7d6c2..f91c2a05 100644 --- a/lib/contracts/IDBSQLSession.ts +++ b/lib/contracts/IDBSQLSession.ts @@ -32,7 +32,8 @@ export type ExecuteStatementOptions = { * `false`/unset (default) runs the blocking direct-results path (faster, * cancellable mid-compute); `true` submits and polls (returns a pending * handle before completion). Default is sync, matching the python - * connector's `cursor.execute()`. + * connector's `cursor.execute()`. With `stagingAllowedLocalPath` set, + * `executeStatement` resolves only after the statement finishes, regardless of this option. */ runAsync?: boolean; maxRows?: number | bigint | Int64 | null; diff --git a/lib/kernel/KernelErrorMapping.ts b/lib/kernel/KernelErrorMapping.ts index d83d7e59..7d67c52e 100644 --- a/lib/kernel/KernelErrorMapping.ts +++ b/lib/kernel/KernelErrorMapping.ts @@ -1,7 +1,18 @@ +import { constants } from 'node:os'; +import { getSystemErrorName } from 'node:util'; import HiveDriverError from '../errors/HiveDriverError'; import AuthenticationError from '../errors/AuthenticationError'; import OperationStateError, { OperationStateErrorCode } from '../errors/OperationStateError'; import ParameterError from '../errors/ParameterError'; +import StagingError from '../errors/StagingError'; + +const kindCodes: Record = { + NotFound: 'ENOENT', + PermissionDenied: 'EACCES', + AlreadyExists: 'EEXIST', + NotADirectory: 'ENOTDIR', + IsADirectory: 'EISDIR', +}; /** * Sentinel prefix the napi binding's `napi_err_from_kernel` puts on @@ -111,6 +122,24 @@ function defineErrorMetadata(error: Error, key: K, value: V }); } +const STAGING_ERROR_CODES = new Set([ + 'VOLUME_STORAGE_HTTP_ERROR', + 'VOLUME_PATH_NOT_ALLOWED', + 'VOLUME_INVALID_INSTRUCTION', +]); + +// A failed Volume transfer raises StagingError, as on Thrift. +function toStagingTransferError(mapped: ErrorWithSqlState): ErrorWithSqlState { + const metadata = mapped.kernelMetadata; + if (metadata?.errorCode && STAGING_ERROR_CODES.has(metadata.errorCode)) { + const staging = new StagingError(mapped.message); + if (metadata) defineErrorMetadata(staging, 'kernelMetadata', metadata); + if ('cause' in mapped) defineErrorMetadata(staging, 'cause', mapped.cause); + return staging; + } + return mapped; +} + /** * Map a kernel error (as surfaced by the napi-binding) to the appropriate JS * driver error class. @@ -311,7 +340,22 @@ export function decodeNapiKernelError(err: unknown): Error { const msg = envelope.message as string; const sqlState = typeof envelope.sqlState === 'string' ? envelope.sqlState : undefined; - const jsErr = mapKernelErrorToJsError({ code, message: msg, sqlstate: sqlState }); + let jsErr = mapKernelErrorToJsError({ code, message: msg, sqlstate: sqlState }); + if (typeof envelope.localPath === 'string' && typeof envelope.localErrorKind === 'string') { + const raw = + typeof envelope.localOsError === 'number' && Number.isSafeInteger(envelope.localOsError) + ? envelope.localOsError + : undefined; + const systemCode = process.platform !== 'win32' && raw ? getSystemErrorName(-Math.abs(raw)) : undefined; + const localCode = + systemCode && systemCode in constants.errno ? systemCode : kindCodes[envelope.localErrorKind] ?? 'EIO'; + // Shaped like a Node fs error, which carries no sqlState. + jsErr = Object.assign(new Error(msg), { + code: localCode, + errno: -(constants.errno as Record)[localCode], + path: envelope.localPath, + }); + } const meta = buildKernelMetadata(envelope); // Skip the namespace attachment entirely when no fields validated @@ -327,5 +371,5 @@ export function decodeNapiKernelError(err: unknown): Error { // message is the whole envelope, including the unbounded diagnostics, which // `util.inspect` would print for every kernel error. defineErrorMetadata(jsErr, 'cause', new Error(boundCauseMessage(`${code}: ${msg}`))); - return jsErr; + return toStagingTransferError(jsErr); } diff --git a/lib/kernel/KernelOperationBackend.ts b/lib/kernel/KernelOperationBackend.ts index 81647ece..7fa0df61 100644 --- a/lib/kernel/KernelOperationBackend.ts +++ b/lib/kernel/KernelOperationBackend.ts @@ -84,7 +84,7 @@ export type KernelOperationStatement = KernelStatementHandle & Partial; +type KernelFetchHandle = Pick; /** * The rich operation-status surface the kernel exposes on a terminal sync @@ -170,6 +170,8 @@ export interface KernelOperationBackendOptions { id?: string; /** Row shape returned by `fetchChunk`; defaults to `'object'`. */ rowMode?: RowMode; + /** Whether the statement ran with Volume options. */ + volume?: boolean; } export default class KernelOperationBackend implements IOperationBackend { @@ -207,6 +209,8 @@ export default class KernelOperationBackend implements IOperationBackend { private readonly rowMode?: RowMode; + private readonly volume: boolean; + private resultSlicer?: ResultSlicer; private resultsProvider?: KernelResultsProvider; @@ -236,6 +240,7 @@ export default class KernelOperationBackend implements IOperationBackend { context, id, rowMode, + volume, }: KernelOperationBackendOptions) { // Exactly one of the three handle kinds must be supplied. const providedCount = @@ -250,6 +255,7 @@ export default class KernelOperationBackend implements IOperationBackend { this.asyncStatement = asyncStatement; this.cancellableExecution = cancellableExecution; this.blockingStatement = statement; + this.volume = volume ?? false; // Lifecycle surface. The async/metadata handles expose both cancel/close. // The sync-execute path uses a composite: `cancel()` always routes to the // cancellable execution (lock-free, interrupts a running `result()` @@ -328,6 +334,9 @@ export default class KernelOperationBackend implements IOperationBackend { return []; } try { + if (await this.transferredVolume()) { + return []; + } const slicer = await this.getResultSlicer(); if (isClosed?.()) { return []; @@ -338,9 +347,20 @@ export default class KernelOperationBackend implements IOperationBackend { } } + /** + * The kernel ran the transfer of a Volume result inside execute. As on + * Thrift, which reads the instruction row to run it, such a result has no rows. + */ + private async transferredVolume(): Promise { + return this.volume && (await this.getFetchHandle()).isVolumeOperation; + } + public async hasMore(): Promise { failIfNotActive(this.lifecycle); try { + if (await this.transferredVolume()) { + return false; + } // `hasMore()` prefetches the next batch, so it fails like `fetchChunk()`. const slicer = await this.getResultSlicer(); return await slicer.hasMore(); diff --git a/lib/kernel/KernelSessionBackend.ts b/lib/kernel/KernelSessionBackend.ts index dd55dd4c..869fe80d 100644 --- a/lib/kernel/KernelSessionBackend.ts +++ b/lib/kernel/KernelSessionBackend.ts @@ -146,22 +146,22 @@ export default class KernelSessionBackend implements ISessionBackend { * - `rowLimit` → `rowLimit` (kernel-only server-side row cap); * - `queryTags` → serialised into the conf overlay's reserved * `query_tags` key (the same wire shape Thrift's `serializeQueryTags` - * produces), merged with any explicit `statementConf`. + * produces), merged with any explicit `statementConf`; + * - `stagingAllowedLocalPath` → the Volume options, so the kernel runs the + * file transfer of a Volume PUT, GET or REMOVE inside execute. * - * Still rejected (genuinely unsupported on kernel, rather than silently - * dropped): `useCloudFetch` (governed by the kernel `ResultConfig`, not a - * per-statement knob), `useLZ4Compression` (kernel owns result compression), - * and `stagingAllowedLocalPath` (volume operations). `maxRows` is applied by + * `useCloudFetch` and `useLZ4Compression` are logged and ignored because the + * kernel owns result fetching and compression. `maxRows` is applied by * the facade at fetch time, so it is intentionally not handled here. */ public async executeStatement(statement: string, options: ExecuteStatementOptions): Promise { this.failIfClosed(); + const volume = options.stagingAllowedLocalPath !== undefined; // Per-statement options the kernel backend doesn't honour are treated as // NO-OPs (logged at warn), not errors — so call sites written for the Thrift // backend are drop-in on the kernel path. These are perf/format hints the - // kernel governs internally (useCloudFetch / useLZ4Compression) or a feature - // it doesn't expose yet (staging); ignoring them cannot change query results. + // kernel governs internally (useCloudFetch / useLZ4Compression). // NB: parameter binding (compound/BINARY) is deliberately NOT no-op'd — a // dropped param would silently change results, so it still throws. if (options.useCloudFetch !== undefined) { @@ -180,15 +180,6 @@ export default class KernelSessionBackend implements ISessionBackend { 'kernel executeStatement: ignoring per-statement `useLZ4Compression` — result compression is governed by the kernel (no-op on kernel).', ); } - if (options.stagingAllowedLocalPath !== undefined) { - this.context - .getLogger() - .log( - LogLevel.warn, - 'kernel executeStatement: ignoring `stagingAllowedLocalPath` — volume/staging operations are not yet supported on the kernel backend (no-op).', - ); - } - // `runAsync` selects the kernel execution path. NOTE: this is a kernel- // specific use of the option — the Thrift backend hardcodes `runAsync: true` // on the wire and never reads `options.runAsync`, so the field is a no-op @@ -257,9 +248,14 @@ export default class KernelSessionBackend implements ISessionBackend { // Feature-detect the arm via a type guard: only the Running `AsyncStatement` // exposes `awaitResult`; the terminal `Statement` (Completed arm) does not. if (isKernelAsyncStatement(direct)) { - return new KernelOperationBackend({ asyncStatement: direct, context: this.context, rowMode: options.rowMode }); + return new KernelOperationBackend({ + asyncStatement: direct, + context: this.context, + rowMode: options.rowMode, + volume, + }); } - return new KernelOperationBackend({ statement: direct, context: this.context, rowMode: options.rowMode }); + return new KernelOperationBackend({ statement: direct, context: this.context, rowMode: options.rowMode, volume }); } // Async path: submit (`wait_timeout=0s`) returns a pending handle the @@ -280,6 +276,7 @@ export default class KernelSessionBackend implements ISessionBackend { asyncStatement: asyncStatement!, context: this.context, rowMode: options.rowMode, + volume, }); } @@ -328,6 +325,16 @@ export default class KernelSessionBackend implements ISessionBackend { } } + if (options.stagingAllowedLocalPath !== undefined) { + execOptions.volume = { + allowedPaths: Array.isArray(options.stagingAllowedLocalPath) + ? options.stagingAllowedLocalPath + : [options.stagingAllowedLocalPath], + // Node Thrift REMOVE treats a missing object as success. + removeNotFoundIsSuccess: true, + }; + } + return Object.keys(execOptions).length > 0 ? execOptions : undefined; } diff --git a/native/kernel/index.d.ts b/native/kernel/index.d.ts index f4957491..ee5df1fc 100644 --- a/native/kernel/index.d.ts +++ b/native/kernel/index.d.ts @@ -24,6 +24,8 @@ export declare class AsyncResultHandle { * `statementId`. */ get statementId(): string + /** True when the server marked this result as a Volume PUT, GET or REMOVE. */ + get isVolumeOperation(): boolean /** * Pull the next batch of results. Returns `null` when the * stream is exhausted. The returned `ArrowBatch.ipcBytes` is a @@ -151,7 +153,9 @@ export declare class AsyncStatement { * * Also invalidates the handles `awaitResult()` returned: their * `fetchNextBatch()` then rejects with `InvalidStatementHandle`, - * unless a fetch was in progress when `close()` ran. + * unless a fetch was in progress when `close()` ran. If another call on + * the statement is still running, such as an `awaitResult()` and its + * Volume transfer, the statement is cancelled first. */ close(): Promise } @@ -444,6 +448,8 @@ export declare class Statement { * kernel / server logs which key on the same id. */ get statementId(): string + /** True when the server marked this result as a Volume PUT, GET or REMOVE. */ + get isVolumeOperation(): boolean /** * Number of rows modified by the statement (UPDATE / INSERT / * DELETE / MERGE). `null` for SELECT and on warehouses that don't @@ -1068,7 +1074,8 @@ export interface ConnectionOptions { * long a single HTTP round-trip may block waiting on the server * before the request errors out. Maps onto the kernel * [`HttpConfig::request_timeout`] (the internal reqwest - * `Client::timeout`). + * `Client::timeout`), which is also the idle limit for Volume file + * transfers. `0` keeps the kernel default. * * Omitted ⇒ kernel default (120 000 ms / 120 s). Napi-rs * serialises `u32` as JS `number`; the largest representable value @@ -1166,6 +1173,14 @@ export interface ExecuteOptions { * typed parameters or combine named and positional markers. */ rawParams?: Array + /** + * Volume transfer settings. With them, executing a Volume PUT, GET or + * REMOVE also runs its file transfer, and a failed transfer fails the + * execution. Omitted ⇒ a Volume statement returns its instruction row + * and moves no file. Maps to `StatementSpec.volume`. No upload bytes + * can be passed, so `PUT '__input_stream__'` fails. + */ + volume?: VolumeExecuteOptions } /** @@ -1336,3 +1351,14 @@ export interface TypedValueInput { * loaded?" probe for the JS-side loader's structured diagnostics. */ export declare function version(): string + +/** Volume transfer settings for one execution. */ +export interface VolumeExecuteOptions { + /** + * Local directories a PUT may read from and a GET may write to. The + * local path, with symlinks resolved, must be inside one of them. + */ + allowedPaths: Array + /** Report success when REMOVE targets an object that does not exist. */ + removeNotFoundIsSuccess?: boolean +} diff --git a/tests/e2e/README.md b/tests/e2e/README.md index c75bc5e0..a2426e70 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -21,7 +21,7 @@ The `e2e-test` job in `.github/workflows/main.yml` runs against the minimum patc Per-test isolation is achieved by: - **Tables**: all DDL in tests is templated against `${E2E_TABLE_SUFFIX}`, which in CI is `${{ github.sha }}_node${{ matrix.node-suffix }}`. The matrix suffix uses underscores because dots and hyphens aren't valid within these SQL unquoted identifiers. -- **Volume files**: `tests/e2e/staging_ingestion.test.ts` generates per-file `uuid.v4()` names. Multiple matrix entries can read/write the volume concurrently without collisions. +- **Volume files**: `tests/e2e/utils/stagingTests.ts` generates per-file `uuid.v4()` names. Multiple matrix entries can read/write the volume concurrently without collisions. No test creates or drops the shared catalog/schema/volume. If you add a test that does, you'll need to suffix-unique the resource name too — verify before merging. diff --git a/tests/e2e/kernel/staging-close-e2e.test.ts b/tests/e2e/kernel/staging-close-e2e.test.ts new file mode 100644 index 00000000..968e5c55 --- /dev/null +++ b/tests/e2e/kernel/staging-close-e2e.test.ts @@ -0,0 +1,67 @@ +import { expect } from 'chai'; +import { createServer } from 'node:http'; +import { AddressInfo } from 'node:net'; +import { tryGetKernelNative } from '../../../lib/kernel/KernelNativeLoader'; +import DBSQLClient from '../../../lib/DBSQLClient'; +import DBSQLSession from '../../../lib/DBSQLSession'; +import KernelSessionBackend from '../../../lib/kernel/KernelSessionBackend'; + +describe('native staging close', () => { + const native = tryGetKernelNative(); + if (native === undefined) { + it.skip('kernel native binding not available on this platform'); + return; + } + + it('closes a session during a pending staged statement with default options', async function () { + this.timeout(10000); + let polled!: () => void; + const polling = new Promise((resolve) => { + polled = resolve; + }); + const server = createServer((request, response) => { + response.setHeader('content-type', 'application/json'); + if (request.method === 'POST' && request.url?.endsWith('/sessions')) { + response.end(JSON.stringify({ session_id: 'session', warehouse_id: 'wh' })); + } else if (request.url?.startsWith('/api/2.0/sql/statements')) { + response.end(JSON.stringify({ statement_id: 'pending', status: { state: 'RUNNING' } })); + if (request.method === 'GET') polled(); + } else { + response.end('{}'); + } + }); + await new Promise((resolve) => { + server.listen(0, '127.0.0.1', resolve); + }); + const context = new DBSQLClient({ logger: { log() {} } }); + const connection = await native.openSession({ + hostName: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, + httpPath: '/sql/1.0/warehouses/wh', + token: 'test-token', + telemetryEnabled: false, + }); + const session = new DBSQLSession({ + backend: new KernelSessionBackend({ connection, context, id: connection.sessionId }), + context, + }); + try { + const executing = session.executeStatement('REMOVE remote', { stagingAllowedLocalPath: [] }).then( + () => { + throw new Error('pending statement completed'); + }, + (error) => error, + ); + await polling; + const started = Date.now(); + await session.close(); + expect(Date.now() - started).to.be.lessThan(1000); + expect(await executing).to.be.instanceOf(Error); + } finally { + await session.close(); + server.closeAllConnections(); + await new Promise((resolve) => { + server.close(() => resolve()); + }); + } + }); +}); diff --git a/tests/e2e/kernel/staging-e2e.test.ts b/tests/e2e/kernel/staging-e2e.test.ts new file mode 100644 index 00000000..6770e33f --- /dev/null +++ b/tests/e2e/kernel/staging-e2e.test.ts @@ -0,0 +1,17 @@ +import stagingTests from '../utils/stagingTests'; + +const kernelDescribe = + process.env.DATABRICKS_PECOTESTING_SERVER_HOSTNAME && + process.env.DATABRICKS_PECOTESTING_HTTP_PATH && + process.env.DATABRICKS_PECOTESTING_TOKEN_PERSONAL + ? describe + : describe.skip; + +kernelDescribe('Kernel Staging Test', () => { + stagingTests(() => ({ + host: process.env.DATABRICKS_PECOTESTING_SERVER_HOSTNAME as string, + path: process.env.DATABRICKS_PECOTESTING_HTTP_PATH as string, + token: process.env.DATABRICKS_PECOTESTING_TOKEN_PERSONAL as string, + useKernel: true, + })); +}); diff --git a/tests/e2e/staging_ingestion.test.ts b/tests/e2e/staging_ingestion.test.ts index 7721dc75..bc739ef5 100644 --- a/tests/e2e/staging_ingestion.test.ts +++ b/tests/e2e/staging_ingestion.test.ts @@ -1,135 +1,10 @@ -import { expect } from 'chai'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; -import * as uuid from 'uuid'; -import { DBSQLClient } from '../../lib'; -import StagingError from '../../lib/errors/StagingError'; - +import stagingTests from './utils/stagingTests'; import config from './utils/config'; describe('Staging Test', () => { - const localPath = fs.mkdtempSync(path.join(os.tmpdir(), 'databricks-sql-tests-')); - - after(() => { - fs.rmSync(localPath, { - recursive: true, - force: true, - }); - }); - - it('put staging data and receive it', async () => { - const { catalog, schema, volume } = config; - - const client = new DBSQLClient(); - await client.connect({ - host: config.host, - path: config.path, - token: config.token, - }); - - const session = await client.openSession({ - initialCatalog: catalog, - initialSchema: schema, - }); - - const expectedData = 'Hello World!'; - const stagingFileName = `/Volumes/${catalog}/${schema}/${volume}/${uuid.v4()}.csv`; - const localFile = path.join(localPath, `${uuid.v4()}.csv`); - - fs.writeFileSync(localFile, expectedData); - await session.executeStatement(`PUT '${localFile}' INTO '${stagingFileName}' OVERWRITE`, { - stagingAllowedLocalPath: [localPath], - }); - fs.rmSync(localFile); - - await session.executeStatement(`GET '${stagingFileName}' TO '${localFile}'`, { - stagingAllowedLocalPath: [localPath], - }); - const result = fs.readFileSync(localFile); - fs.rmSync(localFile); - expect(result.toString() === expectedData).to.be.true; - }); - - it('put staging data and remove it', async () => { - const { catalog, schema, volume } = config; - - const client = new DBSQLClient(); - await client.connect({ - host: config.host, - path: config.path, - token: config.token, - }); - - const session = await client.openSession({ - initialCatalog: catalog, - initialSchema: schema, - }); - - const expectedData = 'Hello World!'; - const stagingFileName = `/Volumes/${catalog}/${schema}/${volume}/${uuid.v4()}.csv`; - const localFile = path.join(localPath, `${uuid.v4()}.csv`); - - fs.writeFileSync(localFile, expectedData); - await session.executeStatement(`PUT '${localFile}' INTO '${stagingFileName}' OVERWRITE`, { - stagingAllowedLocalPath: [localPath], - }); - fs.rmSync(localFile); - - await session.executeStatement(`REMOVE '${stagingFileName}'`, { stagingAllowedLocalPath: [localPath] }); - - try { - await session.executeStatement(`GET '${stagingFileName}' TO '${localFile}'`, { - stagingAllowedLocalPath: [localPath], - }); - expect.fail('It should throw HTTP 404 error'); - } catch (error) { - if (error instanceof StagingError) { - // File should not exist after deleting - expect(error.message).to.contain('404'); - } else { - throw error; - } - } finally { - fs.rmSync(localFile, { force: true }); - } - }); - - it('delete non-existent data', async () => { - const { catalog, schema, volume } = config; - - const client = new DBSQLClient(); - await client.connect({ - host: config.host, - path: config.path, - token: config.token, - }); - - const session = await client.openSession({ - initialCatalog: catalog, - initialSchema: schema, - }); - - const stagingFileName = `/Volumes/${catalog}/${schema}/${volume}/${uuid.v4()}.csv`; - const localFile = path.join(localPath, `${uuid.v4()}.csv`); - - // File should not exist before removing - try { - await session.executeStatement(`GET '${stagingFileName}' TO '${localFile}'`, { - stagingAllowedLocalPath: [localPath], - }); - expect.fail('It should throw HTTP 404 error'); - } catch (error) { - if (error instanceof StagingError) { - expect(error.message).to.contain('404'); - } else { - throw error; - } - } finally { - fs.rmSync(localFile, { force: true }); - } - - // Try to remove the file - it should succeed and not throw any errors - await session.executeStatement(`REMOVE '${stagingFileName}'`, { stagingAllowedLocalPath: [localPath] }); - }); + stagingTests(() => ({ + host: config.host, + path: config.path, + token: config.token, + })); }); diff --git a/tests/e2e/utils/stagingTests.ts b/tests/e2e/utils/stagingTests.ts new file mode 100644 index 00000000..8b7e08f0 --- /dev/null +++ b/tests/e2e/utils/stagingTests.ts @@ -0,0 +1,127 @@ +import { expect } from 'chai'; +import fs from 'fs'; +import path from 'path'; +import os from 'os'; +import * as uuid from 'uuid'; +import { DBSQLClient } from '../../../lib'; +import { ConnectionOptions } from '../../../lib/contracts/IDBSQLClient'; +import StagingError from '../../../lib/errors/StagingError'; + +import config from './config'; + +export default function stagingTests(connectOptions: () => ConnectionOptions) { + let localPath: string; + before(() => { + localPath = fs.mkdtempSync(path.join(os.tmpdir(), 'databricks-sql-tests-')); + }); + + after(() => { + fs.rmSync(localPath, { + recursive: true, + force: true, + }); + }); + + it('put staging data and receive it', async () => { + const { catalog, schema, volume } = config; + + const client = new DBSQLClient(); + await client.connect(connectOptions()); + + const session = await client.openSession({ + initialCatalog: catalog, + initialSchema: schema, + }); + + const expectedData = 'Hello World!'; + const stagingFileName = `/Volumes/${catalog}/${schema}/${volume}/${uuid.v4()}.csv`; + const localFile = path.join(localPath, `${uuid.v4()}.csv`); + + fs.writeFileSync(localFile, expectedData); + await session.executeStatement(`PUT '${localFile}' INTO '${stagingFileName}' OVERWRITE`, { + stagingAllowedLocalPath: [localPath], + }); + fs.rmSync(localFile); + + await session.executeStatement(`GET '${stagingFileName}' TO '${localFile}'`, { + stagingAllowedLocalPath: [localPath], + }); + const result = fs.readFileSync(localFile); + fs.rmSync(localFile); + expect(result.toString()).to.equal(expectedData); + }); + + it('put staging data and remove it', async () => { + const { catalog, schema, volume } = config; + + const client = new DBSQLClient(); + await client.connect(connectOptions()); + + const session = await client.openSession({ + initialCatalog: catalog, + initialSchema: schema, + }); + + const expectedData = 'Hello World!'; + const stagingFileName = `/Volumes/${catalog}/${schema}/${volume}/${uuid.v4()}.csv`; + const localFile = path.join(localPath, `${uuid.v4()}.csv`); + + fs.writeFileSync(localFile, expectedData); + await session.executeStatement(`PUT '${localFile}' INTO '${stagingFileName}' OVERWRITE`, { + stagingAllowedLocalPath: [localPath], + }); + fs.rmSync(localFile); + + await session.executeStatement(`REMOVE '${stagingFileName}'`, { stagingAllowedLocalPath: [localPath] }); + + try { + await session.executeStatement(`GET '${stagingFileName}' TO '${localFile}'`, { + stagingAllowedLocalPath: [localPath], + }); + expect.fail('It should throw HTTP 404 error'); + } catch (error) { + if (error instanceof StagingError) { + // File should not exist after deleting + expect(error.message).to.contain('404'); + } else { + throw error; + } + } finally { + fs.rmSync(localFile, { force: true }); + } + }); + + it('delete non-existent data', async () => { + const { catalog, schema, volume } = config; + + const client = new DBSQLClient(); + await client.connect(connectOptions()); + + const session = await client.openSession({ + initialCatalog: catalog, + initialSchema: schema, + }); + + const stagingFileName = `/Volumes/${catalog}/${schema}/${volume}/${uuid.v4()}.csv`; + const localFile = path.join(localPath, `${uuid.v4()}.csv`); + + // File should not exist before removing + try { + await session.executeStatement(`GET '${stagingFileName}' TO '${localFile}'`, { + stagingAllowedLocalPath: [localPath], + }); + expect.fail('It should throw HTTP 404 error'); + } catch (error) { + if (error instanceof StagingError) { + expect(error.message).to.contain('404'); + } else { + throw error; + } + } finally { + fs.rmSync(localFile, { force: true }); + } + + // Try to remove the file - it should succeed and not throw any errors + await session.executeStatement(`REMOVE '${stagingFileName}'`, { stagingAllowedLocalPath: [localPath] }); + }); +} diff --git a/tests/unit/kernel/KernelOperationBackend.test.ts b/tests/unit/kernel/KernelOperationBackend.test.ts index 972de4fc..30a2562c 100644 --- a/tests/unit/kernel/KernelOperationBackend.test.ts +++ b/tests/unit/kernel/KernelOperationBackend.test.ts @@ -55,6 +55,8 @@ class StatementStub { public closed = false; + public isVolumeOperation = false; + constructor(schemaIpc: Buffer, batches: Buffer[]) { this.schemaIpc = schemaIpc; this.batches = [...batches]; @@ -259,6 +261,15 @@ describe('KernelOperationBackend — M0 datatype round-trip via napi → ArrowRe }); } + it('returns no rows for a Volume result run with the Volume options', async () => { + const schema = new Schema([new Field('operation', new Utf8(), true)]); + const stub = new StatementStub(ipcSchemaOnly(schema), [ipcFromColumns(schema, { operation: ['GET'] })]); + stub.isVolumeOperation = true; + const backend = new KernelOperationBackend({ statement: stub, context: new ClientContextStub(), volume: true }); + expect(await backend.hasMore()).to.equal(false); + expect(await backend.fetchChunk({ limit: 10 })).to.deep.equal([]); + }); + it('preserves decimal qualifiers for a schema-only result with zero scale', async () => { const schema = new Schema([new Field('amount', new Decimal(0, 38, 128), true)]); const backend = new KernelOperationBackend({ diff --git a/tests/unit/kernel/error-mapping.test.ts b/tests/unit/kernel/error-mapping.test.ts index fefa8f2a..0b2c2cb3 100644 --- a/tests/unit/kernel/error-mapping.test.ts +++ b/tests/unit/kernel/error-mapping.test.ts @@ -10,6 +10,7 @@ import HiveDriverError from '../../../lib/errors/HiveDriverError'; import AuthenticationError from '../../../lib/errors/AuthenticationError'; import OperationStateError, { OperationStateErrorCode } from '../../../lib/errors/OperationStateError'; import ParameterError from '../../../lib/errors/ParameterError'; +import StagingError from '../../../lib/errors/StagingError'; describe('KernelErrorMapping.mapKernelErrorToJsError', () => { // The 13 kernel ErrorCode variants — kept in sync with src/kernel_error.rs:66-134. @@ -372,3 +373,48 @@ describe('KernelErrorMapping.decodeNapiKernelError — cause chain', () => { expect(err.cause).to.equal(undefined); }); }); + +describe('KernelErrorMapping.decodeNapiKernelError — local file errors', () => { + for (const [raw, kind, expected] of [ + [2, 'NotFound', 'ENOENT'], + [undefined, 'PermissionDenied', 'EACCES'], + [undefined, 'Unrecognized', 'EIO'], + [1000000, 'NotFound', 'ENOENT'], + ] as const) { + it(`preserves local file error code and path for ${kind}/${raw}`, () => { + const error = decodeNapiKernelError( + new Error( + `__databricks_error__:${JSON.stringify({ + code: 'NotFound', + message: 'Local file does not exist', + localOsError: raw, + localErrorKind: kind, + localPath: '/allowed/missing', + sqlState: 'HY000', + queryId: 'query-id', + })}`, + ), + ) as NodeJS.ErrnoException; + expect(error.code).to.equal(expected); + expect(error.path).to.equal('/allowed/missing'); + expect(error.errno).to.be.lessThan(0); + expect(error).to.have.property('kernelMetadata').with.property('queryId', 'query-id'); + }); + } +}); + +describe('KernelErrorMapping.decodeNapiKernelError — Volume transfer errors', () => { + it('raises StagingError for a failed Volume transfer, as on Thrift', () => { + const error = decodeNapiKernelError( + new Error( + `__databricks_error__:${JSON.stringify({ + code: 'NotFound', + message: 'Volume storage request failed: HTTP 404', + errorCode: 'VOLUME_STORAGE_HTTP_ERROR', + })}`, + ), + ); + expect(error).to.be.instanceOf(StagingError); + expect(error.message).to.equal('Volume storage request failed: HTTP 404'); + }); +}); diff --git a/tests/unit/kernel/execution.test.ts b/tests/unit/kernel/execution.test.ts index 9aae43f5..b62443d7 100644 --- a/tests/unit/kernel/execution.test.ts +++ b/tests/unit/kernel/execution.test.ts @@ -41,6 +41,8 @@ import { DBSQLParameter, DBSQLParameterType } from '../../../lib/DBSQLParameter' // ----------------------------------------------------------------------------- class FakeNativeStatement implements KernelStatement { + public readonly isVolumeOperation = false; + public closed = false; public cancelled = false; @@ -1091,6 +1093,16 @@ describe('KernelSessionBackend', () => { expect((connection.lastOptions as { queryTimeoutSecs?: number } | undefined)?.queryTimeoutSecs).to.equal(undefined); }); + it('executeStatement turns stagingAllowedLocalPath into the Volume options', async () => { + const connection = new FakeNativeConnection(); + const session = makeSession(connection); + await session.executeStatement('GET', { stagingAllowedLocalPath: '/tmp' }); + expect((connection.lastOptions as { volume?: unknown }).volume).to.deep.equal({ + allowedPaths: ['/tmp'], + removeNotFoundIsSuccess: true, + }); + }); + it('executeStatement forwards rowLimit', async () => { const connection = new FakeNativeConnection(); const session = makeSession(connection); @@ -1152,13 +1164,11 @@ describe('KernelSessionBackend', () => { // Unsupported-on-kernel per-statement HINTS are NO-OPs (not errors) so Thrift- // targeted call sites are drop-in on the kernel path. They are kernel-governed - // perf/format hints (useCloudFetch / useLZ4Compression) or an unexposed feature - // (staging); ignoring them can't change results. (Parameter binding is NOT here + // perf/format hints (useCloudFetch / useLZ4Compression). (Parameter binding is NOT here // — a dropped param would change results, so it still throws; asserted above.) for (const { name, options } of [ { name: 'useCloudFetch', options: { useCloudFetch: true } }, { name: 'useLZ4Compression', options: { useLZ4Compression: true } }, - { name: 'stagingAllowedLocalPath', options: { stagingAllowedLocalPath: '/tmp' } }, ] as const) { it(`executeStatement ignores unsupported ${name} (no-op, does not throw)`, async () => { const connection = new FakeNativeConnection(); From 14c1e67e123579485cd50d9a2f967a831f61d252 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 22:20:33 +0000 Subject: [PATCH 2/5] chore(kernel): pin the merged Volume bindings Pin the kernel to d18b044b, the databricks-sql-kernel main commit that merged #521 (Volume bindings, on #520). The bindings tree matches the commit this PR pinned before, plus #511 (configurable Arrow LZ4 compression) from kernel main. native/kernel/index.d.ts is regenerated with npm run build:native, which adds the lz4Compression execute option. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- KERNEL_REV | 2 +- native/kernel/index.d.ts | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/KERNEL_REV b/KERNEL_REV index 8259df97..c3e3ca99 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -4471d5cd5ec0819037293344c1a0bf1d54f2a9d1 +d18b044bdd8d6a3ef7c7dd763a5f38c1532a213f diff --git a/native/kernel/index.d.ts b/native/kernel/index.d.ts index ee5df1fc..e8d20310 100644 --- a/native/kernel/index.d.ts +++ b/native/kernel/index.d.ts @@ -323,7 +323,7 @@ export declare class Connection { * uses (`runAsync: true`): the SEA backend submits, returns a * pending operation handle, and polls to terminal during * fetch. Option semantics (statementConf / queryTags / - * rowLimit / positional + named params) match `executeStatement`. + * rowLimit / lz4Compression / positional + named params) match `executeStatement`. * Submit always sends `wait_timeout=0s` so the call returns * immediately; the caller drives completion via `status()` / * `awaitResult()`. Only the blocking-vs-pending return contract @@ -1097,6 +1097,7 @@ export interface ConnectionOptions { * `key:value` wire shape NodeJS Thrift's `serializeQueryTags` * produces (`lib/utils/queryTags.ts`). Backslashes in keys are * doubled; backslash/colon/comma in values are backslash-escaped. + * - `lz4Compression` — override the session default for Arrow result compression * * `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel * `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`) @@ -1149,6 +1150,8 @@ export interface ExecuteOptions { * `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. */ rowLimit?: number + /** Request LZ4 compression for Arrow results. Omit to use the session default. */ + lz4Compression?: boolean /** * Positional parameters, in 1-based wire order. Index `i` in this * Vec corresponds to the `i+1`-th `?` placeholder in the SQL. From ed47e1932ec63b39a8c9299af33d695188305abb Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 22:37:44 +0000 Subject: [PATCH 3/5] fix(kernel): give local Volume file errors the errno Node fs errors carry A local file error now takes its errno from libuv's error map, so on Windows it matches Node fs errors (-4058 for ENOENT) rather than the POSIX number. A Volume transfer StagingError keeps the kernel sqlState. Tests cover a non-Volume result run with the Volume options, and the staging-close e2e test bounds its waits so cleanup always runs. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- lib/kernel/KernelErrorMapping.ts | 13 +++++++------ tests/e2e/kernel/staging-close-e2e.test.ts | 19 +++++++++++++++++-- .../kernel/KernelOperationBackend.test.ts | 8 ++++++++ tests/unit/kernel/error-mapping.test.ts | 5 ++++- 4 files changed, 36 insertions(+), 9 deletions(-) diff --git a/lib/kernel/KernelErrorMapping.ts b/lib/kernel/KernelErrorMapping.ts index 7d67c52e..39de4b6c 100644 --- a/lib/kernel/KernelErrorMapping.ts +++ b/lib/kernel/KernelErrorMapping.ts @@ -1,5 +1,4 @@ -import { constants } from 'node:os'; -import { getSystemErrorName } from 'node:util'; +import { getSystemErrorMap } from 'node:util'; import HiveDriverError from '../errors/HiveDriverError'; import AuthenticationError from '../errors/AuthenticationError'; import OperationStateError, { OperationStateErrorCode } from '../errors/OperationStateError'; @@ -133,6 +132,7 @@ function toStagingTransferError(mapped: ErrorWithSqlState): ErrorWithSqlState { const metadata = mapped.kernelMetadata; if (metadata?.errorCode && STAGING_ERROR_CODES.has(metadata.errorCode)) { const staging = new StagingError(mapped.message); + if (mapped.sqlState !== undefined) defineErrorMetadata(staging, 'sqlState', mapped.sqlState); if (metadata) defineErrorMetadata(staging, 'kernelMetadata', metadata); if ('cause' in mapped) defineErrorMetadata(staging, 'cause', mapped.cause); return staging; @@ -346,13 +346,14 @@ export function decodeNapiKernelError(err: unknown): Error { typeof envelope.localOsError === 'number' && Number.isSafeInteger(envelope.localOsError) ? envelope.localOsError : undefined; - const systemCode = process.platform !== 'win32' && raw ? getSystemErrorName(-Math.abs(raw)) : undefined; - const localCode = - systemCode && systemCode in constants.errno ? systemCode : kindCodes[envelope.localErrorKind] ?? 'EIO'; + // Node fs errors carry libuv error numbers, which differ from the OS codes on Windows. + const systemErrors = getSystemErrorMap(); + const systemCode = process.platform !== 'win32' && raw ? systemErrors.get(-Math.abs(raw))?.[0] : undefined; + const localCode = systemCode ?? kindCodes[envelope.localErrorKind] ?? 'EIO'; // Shaped like a Node fs error, which carries no sqlState. jsErr = Object.assign(new Error(msg), { code: localCode, - errno: -(constants.errno as Record)[localCode], + errno: [...systemErrors].find(([, [name]]) => name === localCode)?.[0], path: envelope.localPath, }); } diff --git a/tests/e2e/kernel/staging-close-e2e.test.ts b/tests/e2e/kernel/staging-close-e2e.test.ts index 968e5c55..1dbcc886 100644 --- a/tests/e2e/kernel/staging-close-e2e.test.ts +++ b/tests/e2e/kernel/staging-close-e2e.test.ts @@ -6,6 +6,21 @@ import DBSQLClient from '../../../lib/DBSQLClient'; import DBSQLSession from '../../../lib/DBSQLSession'; import KernelSessionBackend from '../../../lib/kernel/KernelSessionBackend'; +// Bounded so a missed step fails the test and the cleanup still runs. +async function within(promise: Promise, step: string): Promise { + let timer: NodeJS.Timeout | undefined; + try { + return await Promise.race([ + promise, + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`${step} took over 3s`)), 3000); + }), + ]); + } finally { + clearTimeout(timer); + } +} + describe('native staging close', () => { const native = tryGetKernelNative(); if (native === undefined) { @@ -51,11 +66,11 @@ describe('native staging close', () => { }, (error) => error, ); - await polling; + await within(polling, 'the status poll'); const started = Date.now(); await session.close(); expect(Date.now() - started).to.be.lessThan(1000); - expect(await executing).to.be.instanceOf(Error); + expect(await within(executing, 'the statement failure')).to.be.instanceOf(Error); } finally { await session.close(); server.closeAllConnections(); diff --git a/tests/unit/kernel/KernelOperationBackend.test.ts b/tests/unit/kernel/KernelOperationBackend.test.ts index 30a2562c..2f90e1fa 100644 --- a/tests/unit/kernel/KernelOperationBackend.test.ts +++ b/tests/unit/kernel/KernelOperationBackend.test.ts @@ -270,6 +270,14 @@ describe('KernelOperationBackend — M0 datatype round-trip via napi → ArrowRe expect(await backend.fetchChunk({ limit: 10 })).to.deep.equal([]); }); + it('returns the rows of a non-Volume result run with the Volume options', async () => { + const schema = new Schema([new Field('id', new Utf8(), true)]); + const stub = new StatementStub(ipcSchemaOnly(schema), [ipcFromColumns(schema, { id: ['1'] })]); + stub.isVolumeOperation = false; + const backend = new KernelOperationBackend({ statement: stub, context: new ClientContextStub(), volume: true }); + expect(await backend.fetchChunk({ limit: 10 })).to.deep.equal([{ id: '1' }]); + }); + it('preserves decimal qualifiers for a schema-only result with zero scale', async () => { const schema = new Schema([new Field('amount', new Decimal(0, 38, 128), true)]); const backend = new KernelOperationBackend({ diff --git a/tests/unit/kernel/error-mapping.test.ts b/tests/unit/kernel/error-mapping.test.ts index 0b2c2cb3..2e195208 100644 --- a/tests/unit/kernel/error-mapping.test.ts +++ b/tests/unit/kernel/error-mapping.test.ts @@ -1,4 +1,5 @@ import { expect } from 'chai'; +import { getSystemErrorName } from 'node:util'; import { mapKernelErrorToJsError, decodeNapiKernelError, @@ -397,7 +398,7 @@ describe('KernelErrorMapping.decodeNapiKernelError — local file errors', () => ) as NodeJS.ErrnoException; expect(error.code).to.equal(expected); expect(error.path).to.equal('/allowed/missing'); - expect(error.errno).to.be.lessThan(0); + expect(getSystemErrorName(error.errno as number)).to.equal(expected); expect(error).to.have.property('kernelMetadata').with.property('queryId', 'query-id'); }); } @@ -411,10 +412,12 @@ describe('KernelErrorMapping.decodeNapiKernelError — Volume transfer errors', code: 'NotFound', message: 'Volume storage request failed: HTTP 404', errorCode: 'VOLUME_STORAGE_HTTP_ERROR', + sqlState: 'HY000', })}`, ), ); expect(error).to.be.instanceOf(StagingError); expect(error.message).to.equal('Volume storage request failed: HTTP 404'); + expect(error).to.have.property('sqlState', 'HY000'); }); }); From 4d0f6fd426b544a1585b1ca474da5558bdedccc3 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 22:38:58 +0000 Subject: [PATCH 4/5] docs(changelog): name the kernel release the Volume entry needs Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c47ea465..17f0730a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ - **Behavior change:** Thrift `getSchema()` and `getResultMetadata().schema` return `{ columns: [] }` for statements without output columns when Arrow metadata has no fields. Check `columns.length` before indexing. `getMetadata()` and responses without Arrow metadata (including `arrowEnabled: false` and older protocols) retain the `Result STRING` placeholder. (#651) - Fix `fetchAll()` and `fetchChunk()` hanging on column-based results with an empty or missing schema. (#651) - Kernel backend: support SOCKS proxies through the `proxy` option. -- Kernel backend: support Volume `PUT`, `GET` and `REMOVE` when `stagingAllowedLocalPath` is set. The kernel runs the transfer inside execution, and local paths, with symlinks resolved, must be within the allowed paths (#613). +- Kernel backend: support Volume `PUT`, `GET` and `REMOVE` when `stagingAllowedLocalPath` is set. The kernel runs the transfer inside execution, and local paths, with symlinks resolved, must be within the allowed paths. The published `@databricks/databricks-sql-kernel-*` native packages must be bumped to a release that includes databricks/databricks-sql-kernel#520 and #521 (#613). ## 3.1.0 From 9705b74f980629266b2b17bb1435f0fdd9a77c32 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 22:46:41 +0000 Subject: [PATCH 5/5] test(kernel): bound the session closes in the staging-close e2e test A close that hangs now fails the test, and the server still shuts down. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- tests/e2e/kernel/staging-close-e2e.test.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/tests/e2e/kernel/staging-close-e2e.test.ts b/tests/e2e/kernel/staging-close-e2e.test.ts index 1dbcc886..18dda57e 100644 --- a/tests/e2e/kernel/staging-close-e2e.test.ts +++ b/tests/e2e/kernel/staging-close-e2e.test.ts @@ -68,15 +68,18 @@ describe('native staging close', () => { ); await within(polling, 'the status poll'); const started = Date.now(); - await session.close(); + await within(session.close(), 'the session close'); expect(Date.now() - started).to.be.lessThan(1000); expect(await within(executing, 'the statement failure')).to.be.instanceOf(Error); } finally { - await session.close(); - server.closeAllConnections(); - await new Promise((resolve) => { - server.close(() => resolve()); - }); + try { + await within(session.close(), 'the session close'); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => { + server.close(() => resolve()); + }); + } } }); });