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..17f0730a 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. 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 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..c3e3ca99 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -a29235cbea9532efa5572ebff010045583a19cbe +d18b044bdd8d6a3ef7c7dd763a5f38c1532a213f 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..39de4b6c 100644 --- a/lib/kernel/KernelErrorMapping.ts +++ b/lib/kernel/KernelErrorMapping.ts @@ -1,7 +1,17 @@ +import { getSystemErrorMap } 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 +121,25 @@ 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 (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; + } + return mapped; +} + /** * Map a kernel error (as surfaced by the napi-binding) to the appropriate JS * driver error class. @@ -311,7 +340,23 @@ 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; + // 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: [...systemErrors].find(([, [name]]) => name === localCode)?.[0], + path: envelope.localPath, + }); + } const meta = buildKernelMetadata(envelope); // Skip the namespace attachment entirely when no fields validated @@ -327,5 +372,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..e8d20310 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 } @@ -319,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 @@ -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 @@ -1090,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`) @@ -1142,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. @@ -1166,6 +1176,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 +1354,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..18dda57e --- /dev/null +++ b/tests/e2e/kernel/staging-close-e2e.test.ts @@ -0,0 +1,85 @@ +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'; + +// 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) { + 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 within(polling, 'the status poll'); + const started = Date.now(); + 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 { + try { + await within(session.close(), 'the session close'); + } finally { + 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..2f90e1fa 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,23 @@ 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('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 fefa8f2a..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, @@ -10,6 +11,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 +374,50 @@ 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(getSystemErrorName(error.errno as number)).to.equal(expected); + 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', + 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'); + }); +}); 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();