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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/kernel-e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 3 additions & 4 deletions CONNECTION_PARAMETERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>` | ✅ | ✅ | — | 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`. |
Expand Down Expand Up @@ -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<string, DBSQLParameter \| DBSQLParameterValue>` | ✅ | ✅ | — | Named SQL parameters. Cannot be combined with non-empty `ordinalParameters`. Thrift requires a protocol that supports parameterized queries. |
| `ordinalParameters` | `Array<DBSQLParameter \| DBSQLParameterValue>` | ✅ | ✅ | — | Positional SQL parameters. Cannot be combined with non-empty `namedParameters`. |
| `queryTags` | `Record<string, string \| null \| undefined>` | ✅ | ✅ | — | Serialized into the per-statement `query_tags` conf overlay on both. |
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion KERNEL_REV
Original file line number Diff line number Diff line change
@@ -1 +1 @@
a29235cbea9532efa5572ebff010045583a19cbe
d18b044bdd8d6a3ef7c7dd763a5f38c1532a213f
3 changes: 2 additions & 1 deletion lib/contracts/IDBSQLSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
49 changes: 47 additions & 2 deletions lib/kernel/KernelErrorMapping.ts
Original file line number Diff line number Diff line change
@@ -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<string, string> = {
NotFound: 'ENOENT',
PermissionDenied: 'EACCES',
AlreadyExists: 'EEXIST',
NotADirectory: 'ENOTDIR',
IsADirectory: 'EISDIR',
};

/**
* Sentinel prefix the napi binding's `napi_err_from_kernel` puts on
Expand Down Expand Up @@ -111,6 +121,25 @@ function defineErrorMetadata<K extends string, V>(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);
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
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.
Expand Down Expand Up @@ -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), {
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
code: localCode,
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
errno: [...systemErrors].find(([, [name]]) => name === localCode)?.[0],
path: envelope.localPath,
});
}

const meta = buildKernelMetadata(envelope);
// Skip the namespace attachment entirely when no fields validated
Expand All @@ -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);
}
22 changes: 21 additions & 1 deletion lib/kernel/KernelOperationBackend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export type KernelOperationStatement = KernelStatementHandle & Partial<KernelSta
* (`KernelResultsProvider` → `ArrowResultConverter` → `ResultSlicer`) consumes
* either interchangeably.
*/
type KernelFetchHandle = Pick<KernelStatement, 'fetchNextBatch' | 'schema'>;
type KernelFetchHandle = Pick<KernelStatement, 'fetchNextBatch' | 'schema' | 'isVolumeOperation'>;

/**
* The rich operation-status surface the kernel exposes on a terminal sync
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -207,6 +209,8 @@ export default class KernelOperationBackend implements IOperationBackend {

private readonly rowMode?: RowMode;

private readonly volume: boolean;

private resultSlicer?: ResultSlicer<any>;

private resultsProvider?: KernelResultsProvider;
Expand Down Expand Up @@ -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 =
Expand All @@ -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()`
Expand Down Expand Up @@ -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 [];
Expand All @@ -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<boolean> {
return this.volume && (await this.getFetchHandle()).isVolumeOperation;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low — The package.json pins still point at native 1.5.0, which ignores volume. On those builds isVolumeOperation is undefined, so no file moves and the instruction row is returned silently. The CHANGELOG notes the required bump but nothing checks it at runtime. Bump the pins together with this change, or warn or throw when the handle lacks isVolumeOperation.

🔀 Found by Claude Opus 5.5 · confirmed by the judge

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same release gate as #613 (comment): the fix is bumping the @databricks/databricks-sql-kernel-* pins to a release that includes databricks/databricks-sql-kernel#520 and #521, not a runtime check, since this driver ships those pins. This stays open until that release.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still open at 9705b74: package.json:95-102 still pins every kernel platform at 1.5.0; keeping this open until the pins are bumped.

}

public async hasMore(): Promise<boolean> {
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();
Expand Down
43 changes: 25 additions & 18 deletions lib/kernel/KernelSessionBackend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<IOperationBackend> {
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) {
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -280,6 +276,7 @@ export default class KernelSessionBackend implements ISessionBackend {
asyncStatement: asyncStatement!,
context: this.context,
rowMode: options.rowMode,
volume,
});
}

Expand Down Expand Up @@ -328,6 +325,16 @@ export default class KernelSessionBackend implements ISessionBackend {
}
}

if (options.stagingAllowedLocalPath !== undefined) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium — The platform packages remain pinned at 1.5.0 while only KERNEL_REV changed. A binding without ExecuteOptions.volume would silently run no transfer, and the old warning was removed. Keep a warning or fail until the binding is detected to support Volume options, or bump the package pins in this PR.

🔀 Found by Claude Opus 5.5 · confirmed by the judge

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same release gate as #613 (comment). databricks/databricks-sql-kernel#520 and #521 are merged (KERNEL_REV now pins d18b044b), but the @databricks/databricks-sql-kernel-* pins and the lockfile can only move once a kernel release ships, so this stays open until then.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still open at 4d0f6fd: platform package pins are still 1.5.0, and there is no warning or capability check until a kernel release ships.

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;
}

Expand Down
Loading
Loading