Skip to content

Commit f341c27

Browse files
vuanhphungIsaac
andauthored
fix(telemetry): sanitize error telemetry and report result delivery shape (#596)
Error telemetry copied the raw server error message and JS stack into the emitted event and the exported payload, leaking SQL-derived identifiers. It now carries only the error class name and the server SQLSTATE, matching the kernel's sanitized error_info; the emitter, aggregator and exporter each drop message/stack. statement.complete on the Thrift backend now reports resultFormat and compressed from result metadata the backend already holds (direct results or the result path's fetch), with no extra RPC. Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com>
1 parent 8482d2a commit f341c27

16 files changed

Lines changed: 481 additions & 125 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
- `oauthScopes` is now honored on the Thrift backend: OAuth client-secret M2M sends the configured scopes instead of always `all-apis`, so scoped service-principal secrets can authenticate, and U2M uses them in place of `sql offline_access`. On both backends, entries are split on whitespace and blank values fall back to those defaults. A token read from `persistence` that records different scopes from the ones the client would request is no longer reused or refreshed; the client acquires a new one (for U2M, through a new browser login). Tokens that don't record scopes are still reused. (#540)
2222
- Fix `DECIMAL` parameters losing their fractional digits on the Thrift backend: `"123.45"` was bound as `decimal(3,0)` and came back as `123`. Both backends now send `DECIMAL(p,s)` derived from the value (also for the `DEC` / `NUMERIC` synonyms), stringify `Int64` values beyond 2^53 exactly instead of as `Infinity`, accept exponent forms such as `1e-7` (rewritten as a plain numeral), and throw a `ParameterError` for non-numeric values or values that need more than 38 digits. (#474)
2323
- `customHeaders` are now sent on every Thrift request (session, statement and metadata calls), as the kernel backend already did, instead of only on telemetry and feature-flag requests. On these requests, caller values for driver-managed headers (`Authorization`, `User-Agent`, `Content-Type`, `Content-Length`, `Transfer-Encoding`, `Connection`) are ignored on both backends, and the Thrift backend rejects header names or values that cannot be sent at connect time. (#491)
24+
- Error telemetry now reports only the error class name and the server SQLSTATE. It no longer includes the error message or stack trace, which could contain table and column names from the query. On the Thrift backend, `statement.complete` telemetry now also reports the result delivery format (inline Arrow, inline columnar, or CloudFetch) and whether the server LZ4-compressed the result. (#508)
2425

2526
## 3.0.0
2627

‎docs/TELEMETRY.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,13 @@ same auth as your queries.
1515
version, and boolean feature toggles (CloudFetch, LZ4, Arrow, direct results) plus numeric
1616
configs (socket timeout, retry max, CloudFetch concurrency).
1717
- **Statement** (`statement.start` / `statement.complete`): randomly generated statement and
18-
session UUIDs, operation type (e.g. `SELECT`), latency, result format, poll count, chunk
19-
count, bytes downloaded.
18+
session UUIDs, operation type (e.g. `SELECT`), latency, result delivery format
19+
(`INLINE_ARROW`, `COLUMNAR_INLINE`, or `EXTERNAL_LINKS`), whether the server compressed the
20+
result, poll count, chunk count, bytes downloaded.
2021
- **CloudFetch chunk** (`cloudfetch.chunk`): chunk index, download latency, byte size,
2122
compressed flag.
22-
- **Error**: error class name, sanitized message (no PII), HTTP status, terminal-vs-retryable
23-
flag. Stack traces are not transmitted.
23+
- **Error**: error class name, server SQLSTATE (e.g. `42P01`) when present, terminal-vs-retryable
24+
flag. Error messages and stack traces are not collected because they can quote SQL text.
2425

2526
Correlation IDs (session ID, statement ID) are random UUIDs and are not tied to user identity.
2627
Workspace ID is included for aggregation.

‎lib/DBSQLOperation.ts‎

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import ThriftOperationBackend from './thrift-backend/ThriftOperationBackend';
2121
import { synthesizeThriftStatus, synthesizeThriftResultSetMetadata } from './thrift-backend/wireSynthesis';
2222
import { mapOperationTypeToTelemetryType } from './telemetry/telemetryTypeMappers';
2323
import ExceptionClassifier from './telemetry/ExceptionClassifier';
24-
import { safeEmit } from './telemetry/telemetryUtils';
24+
import { describeErrorForTelemetry, safeEmit } from './telemetry/telemetryUtils';
2525
// Declares `Symbol.asyncDispose` for the emitted typings of `[Symbol.asyncDispose]()` below
2626
import './contracts/asyncDispose';
2727

@@ -451,14 +451,15 @@ export default class DBSQLOperation implements IOperation {
451451
// throws if the operation is already in an error/closed state, which
452452
// would then fire spurious error telemetry from `getMetadata`'s error
453453
// wrapper.
454-
const resultFormat = mapNeutralResultFormatToTelemetryType(this.metadata?.resultFormat);
454+
const metadata = this.backend.getCachedResultMetadata?.() ?? this.metadata;
455455
const latencyMs = Date.now() - this.startTime;
456456

457457
emitter.emitStatementComplete({
458458
statementId: this.id,
459459
sessionId: this.sessionId,
460460
latencyMs,
461-
resultFormat,
461+
resultFormat: mapNeutralResultFormatToTelemetryType(metadata?.resultFormat),
462+
compressed: metadata ? Boolean(metadata.lz4Compressed) : undefined,
462463
pollCount: this.pollCount,
463464
});
464465

@@ -467,24 +468,18 @@ export default class DBSQLOperation implements IOperation {
467468
}
468469

469470
/**
470-
* Emit a telemetry error event for an exception thrown by an operation.
471-
* Terminal errors (per `ExceptionClassifier`) trigger an immediate flush
472-
* in the aggregator; retryable errors are buffered until the statement
473-
* completes. All exceptions from this method itself are swallowed at
474-
* debug level — telemetry must never break the driver.
475-
*
476-
* Pass `deferToCompletion` when the caller completes the statement right
477-
* afterwards: the error is then buffered (not terminal) so the statement's
478-
* aggregation is finalized once, by that completion.
471+
* Report only the error class name and SQLSTATE. Terminal errors flush
472+
* immediately; retryable errors are buffered until statement completion.
473+
* `deferToCompletion` buffers a terminal error when the caller completes
474+
* the statement next, so aggregation is finalized once.
475+
* Telemetry failures are swallowed at debug level.
479476
*/
480477
private emitErrorEvent(error: Error, options?: { deferToCompletion?: boolean }): void {
481478
safeEmit(this.context, (emitter) => {
482479
emitter.emitError({
483480
statementId: this.id,
484481
sessionId: this.sessionId,
485-
errorName: error.name || 'Error',
486-
errorMessage: error.message || 'Unknown error',
487-
errorStack: error.stack,
482+
...describeErrorForTelemetry(error),
488483
isTerminal: options?.deferToCompletion ? false : ExceptionClassifier.isTerminal(error),
489484
});
490485
});

‎lib/contracts/IOperationBackend.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,13 @@ export default interface IOperationBackend {
106106
/** Fetch result-set metadata (schema, format, lz4 flag, arrow schema, staging flag). */
107107
getResultMetadata(): Promise<ResultMetadata>;
108108

109+
/**
110+
* Result-set metadata if it is already on hand (direct results or an earlier
111+
* fetch), else `undefined`. MUST NOT issue an RPC or throw — statement
112+
* telemetry reads it at close time.
113+
*/
114+
getCachedResultMetadata?(): ResultMetadata | undefined;
115+
109116
/** Cancel the operation. */
110117
cancel(): Promise<Status>;
111118

‎lib/telemetry/DatabricksTelemetryExporter.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,9 @@ import {
2929
hasAuthorization,
3030
normalizeHeaders,
3131
redactSensitive,
32+
sanitizeErrorName,
3233
sanitizeProcessName,
34+
sanitizeSqlState,
3335
} from './telemetryUtils';
3436
import buildUserAgentString from '../utils/buildUserAgentString';
3537

@@ -456,14 +458,12 @@ export default class DatabricksTelemetryExporter {
456458
}
457459
}
458460
} else if (metric.metricType === 'error') {
459-
const stackOrMessage = metric.errorStack ?? metric.errorMessage ?? '';
460-
// Primary redaction site is TelemetryEventEmitter.emitError — this
461-
// second pass is defence-in-depth in case a metric reached the
462-
// exporter via a path that bypassed the emitter (programmatic injection
463-
// in tests, future call sites). On the unauth path we ship nothing.
461+
// Only the class name and SQLSTATE leave the process (the SQLSTATE in
462+
// `stack_trace`, matching the kernel); message/stack are never read here
463+
// even if a metric bypassed the emitter. Unauth ships no SQLSTATE.
464464
log.entry.sql_driver_log.error_info = {
465-
error_name: metric.errorName || 'UnknownError',
466-
stack_trace: includeCorrelation ? redactSensitive(stackOrMessage) : '',
465+
error_name: sanitizeErrorName(metric.errorName) ?? 'UnknownError',
466+
stack_trace: includeCorrelation ? sanitizeSqlState(metric.sqlState) ?? '' : '',
467467
};
468468
}
469469

‎lib/telemetry/MetricsAggregator.ts‎

Lines changed: 39 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -207,17 +207,7 @@ export default class MetricsAggregator {
207207
this.pushBoundedError(details, event);
208208
this.completeStatement(event.statementId);
209209
} else {
210-
const metric: TelemetryMetric = {
211-
metricType: 'error',
212-
timestamp: event.timestamp,
213-
sessionId: event.sessionId,
214-
statementId: event.statementId,
215-
workspaceId: event.workspaceId,
216-
errorName: event.errorName,
217-
errorMessage: event.errorMessage,
218-
errorStack: event.errorStack,
219-
};
220-
this.addPendingMetric(metric);
210+
this.addPendingMetric(MetricsAggregator.errorMetric(event, event));
221211
}
222212

223213
// Fire-and-forget on the terminal-error path so customer code doesn't
@@ -233,6 +223,25 @@ export default class MetricsAggregator {
233223
}
234224
}
235225

226+
/**
227+
* The only place error metrics are built: copies the sanitized descriptor
228+
* (name + SQLSTATE) and never a message or stack, whatever the event carries.
229+
*/
230+
private static errorMetric(
231+
errorEvent: TelemetryEvent,
232+
ids: { sessionId?: string; statementId?: string; workspaceId?: string },
233+
): TelemetryMetric {
234+
return {
235+
metricType: 'error',
236+
timestamp: errorEvent.timestamp,
237+
sessionId: ids.sessionId,
238+
statementId: ids.statementId,
239+
workspaceId: ids.workspaceId,
240+
errorName: errorEvent.errorName,
241+
sqlState: errorEvent.sqlState,
242+
};
243+
}
244+
236245
private pushBoundedError(details: StatementTelemetryDetails, event: TelemetryEvent): void {
237246
if (details.errors.length >= this.maxErrorsPerStatement) {
238247
details.errors.shift();
@@ -252,6 +261,7 @@ export default class MetricsAggregator {
252261
case TelemetryEventType.STATEMENT_COMPLETE:
253262
details.executionLatencyMs = event.latencyMs;
254263
details.resultFormat = event.resultFormat;
264+
MetricsAggregator.mergeCompressed(details, event.compressed);
255265
// STATEMENT_COMPLETE may not carry chunk counts (the operation
256266
// doesn't always know them at close time); only override when the
257267
// emit explicitly supplied a value, otherwise the values accumulated
@@ -270,17 +280,7 @@ export default class MetricsAggregator {
270280
case TelemetryEventType.CLOUDFETCH_CHUNK:
271281
details.chunkCount += 1;
272282
details.bytesDownloaded += event.bytes ?? 0;
273-
// `compressionEnabled` is a sticky OR across all chunks in the
274-
// statement — any compressed chunk flips it true and it stays true.
275-
// Previously we copied the last chunk's value, which silently lied
276-
// for mixed-compression batches (compressed chunk 1, uncompressed
277-
// chunk 2 → compressionEnabled=false). True-on-any matches the
278-
// dashboard contract "did this statement benefit from compression".
279-
if (event.compressed === true) {
280-
details.compressionEnabled = true;
281-
} else if (event.compressed === false && details.compressionEnabled === undefined) {
282-
details.compressionEnabled = false;
283-
}
283+
MetricsAggregator.mergeCompressed(details, event.compressed);
284284
// Per-chunk timing aggregation. Only record positive latencies — keeps
285285
// prefetched/cached pages out of the timing stats.
286286
if (event.latencyMs !== undefined && event.latencyMs > 0) {
@@ -299,6 +299,20 @@ export default class MetricsAggregator {
299299
}
300300
}
301301

302+
/**
303+
* `compressionEnabled` is a sticky OR across the statement's chunks and its
304+
* completion event — any compressed report flips it true and it stays true.
305+
* True-on-any matches the dashboard contract "did this statement benefit
306+
* from compression".
307+
*/
308+
private static mergeCompressed(details: StatementTelemetryDetails, compressed: boolean | undefined): void {
309+
if (compressed === true) {
310+
details.compressionEnabled = true;
311+
} else if (compressed === false && details.compressionEnabled === undefined) {
312+
details.compressionEnabled = false;
313+
}
314+
}
315+
302316
private getOrCreateStatementDetails(event: TelemetryEvent): StatementTelemetryDetails {
303317
const statementId = event.statementId!;
304318

@@ -336,16 +350,7 @@ export default class MetricsAggregator {
336350
const id = oldest.value;
337351
const details = this.statementMetrics.get(id)!;
338352
for (const errorEvent of details.errors) {
339-
this.addPendingMetric({
340-
metricType: 'error',
341-
timestamp: errorEvent.timestamp,
342-
sessionId: details.sessionId,
343-
statementId: details.statementId,
344-
workspaceId: details.workspaceId,
345-
errorName: errorEvent.errorName,
346-
errorMessage: errorEvent.errorMessage,
347-
errorStack: errorEvent.errorStack,
348-
});
353+
this.addPendingMetric(MetricsAggregator.errorMetric(errorEvent, details));
349354
}
350355
this.statementMetrics.delete(id);
351356
this.evictedStatements += 1;
@@ -366,16 +371,7 @@ export default class MetricsAggregator {
366371
for (const [id, details] of this.statementMetrics) {
367372
if (details.startTime < cutoff) {
368373
for (const errorEvent of details.errors) {
369-
this.addPendingMetric({
370-
metricType: 'error',
371-
timestamp: errorEvent.timestamp,
372-
sessionId: details.sessionId,
373-
statementId: details.statementId,
374-
workspaceId: details.workspaceId,
375-
errorName: errorEvent.errorName,
376-
errorMessage: errorEvent.errorMessage,
377-
errorStack: errorEvent.errorStack,
378-
});
374+
this.addPendingMetric(MetricsAggregator.errorMetric(errorEvent, details));
379375
}
380376
this.statementMetrics.delete(id);
381377
evicted += 1;
@@ -476,17 +472,7 @@ export default class MetricsAggregator {
476472
this.addPendingMetric(metric);
477473

478474
for (const errorEvent of details.errors) {
479-
const errorMetric: TelemetryMetric = {
480-
metricType: 'error',
481-
timestamp: errorEvent.timestamp,
482-
sessionId: details.sessionId,
483-
statementId: details.statementId,
484-
workspaceId: details.workspaceId,
485-
errorName: errorEvent.errorName,
486-
errorMessage: errorEvent.errorMessage,
487-
errorStack: errorEvent.errorStack,
488-
};
489-
this.addPendingMetric(errorMetric);
475+
this.addPendingMetric(MetricsAggregator.errorMetric(errorEvent, details));
490476
}
491477

492478
this.statementMetrics.delete(statementId);

‎lib/telemetry/TelemetryEventEmitter.ts‎

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import { EventEmitter } from 'events';
1818
import IClientContext from '../contracts/IClientContext';
1919
import { LogLevel } from '../contracts/IDBSQLLogger';
2020
import { TelemetryEvent, TelemetryEventType, DriverConfiguration } from './types';
21-
import { redactSensitive } from './telemetryUtils';
21+
import { sanitizeErrorName, sanitizeSqlState } from './telemetryUtils';
2222

2323
/**
2424
* Typed map of event-type → listener payload shape. Keeps `on`/`off` calls
@@ -135,6 +135,7 @@ export default class TelemetryEventEmitter extends EventEmitter {
135135
sessionId?: string;
136136
latencyMs?: number;
137137
resultFormat?: string;
138+
compressed?: boolean;
138139
chunkCount?: number;
139140
bytesDownloaded?: number;
140141
pollCount?: number;
@@ -146,6 +147,7 @@ export default class TelemetryEventEmitter extends EventEmitter {
146147
sessionId: data.sessionId,
147148
latencyMs: data.latencyMs,
148149
resultFormat: data.resultFormat,
150+
compressed: data.compressed,
149151
chunkCount: data.chunkCount,
150152
bytesDownloaded: data.bytesDownloaded,
151153
pollCount: data.pollCount,
@@ -171,24 +173,20 @@ export default class TelemetryEventEmitter extends EventEmitter {
171173
}
172174

173175
/**
174-
* Emit an error event.
175-
*
176-
* Redaction happens HERE — not at the exporter — so any in-process listener
177-
* (this class extends `EventEmitter` and `getTelemetryEmitter()` is reachable
178-
* from any consumer of `@databricks/sql`) sees the same redacted strings
179-
* the export pipeline does. `redactSensitive` strips Bearer/Basic, Databricks
180-
* token prefixes, JWTs, JSON-encoded secrets, URL userinfo, and common
181-
* username-bearing filesystem paths, then caps length.
182-
*
183-
* `errorMessage` is also redacted, not only `errorStack` — operation error
184-
* messages can carry query fragments, table names, parameter values that the
185-
* SECRET_PATTERNS regex must scrub before they're emitted anywhere.
176+
* Emit an error event carrying only a sanitized descriptor: the error class
177+
* name and the server SQLSTATE. Error messages and stacks quote SQL
178+
* identifiers and literals, so they are never emitted — sanitizing here (not
179+
* at the exporter) keeps in-process listeners on `getTelemetryEmitter()`
180+
* equally clean.
186181
*/
187182
emitError(data: {
188183
statementId?: string;
189184
sessionId?: string;
190185
errorName: string;
191-
errorMessage: string;
186+
sqlState?: string;
187+
/** @deprecated Ignored; error messages are never emitted. */
188+
errorMessage?: string;
189+
/** @deprecated Ignored; error stacks are never emitted. */
192190
errorStack?: string;
193191
isTerminal: boolean;
194192
}): void {
@@ -197,9 +195,8 @@ export default class TelemetryEventEmitter extends EventEmitter {
197195
timestamp: Date.now(),
198196
statementId: data.statementId,
199197
sessionId: data.sessionId,
200-
errorName: data.errorName,
201-
errorMessage: redactSensitive(data.errorMessage),
202-
errorStack: data.errorStack === undefined ? undefined : redactSensitive(data.errorStack),
198+
errorName: sanitizeErrorName(data.errorName) ?? 'Error',
199+
sqlState: sanitizeSqlState(data.sqlState),
203200
isTerminal: data.isTerminal,
204201
}));
205202
}

‎lib/telemetry/telemetryUtils.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,42 @@ export function redactSensitive(value: string | undefined, maxLen = 2048): strin
179179
return redacted;
180180
}
181181

182+
// A class-like identifier, optionally two words (e.g. `StatusError`'s 'Status Error').
183+
const ERROR_NAME_PATTERN = /^[A-Za-z_$][\w$]*(?: [A-Za-z_$][\w$]*)?$/;
184+
185+
const SQL_STATE_PATTERN = /^[0-9A-Z]{5}$/;
186+
187+
/**
188+
* Returns `name` when it looks like an error class name, otherwise `undefined`.
189+
* Error telemetry carries only this and the SQLSTATE — never a message or stack,
190+
* which routinely quote SQL identifiers and literals.
191+
*/
192+
export function sanitizeErrorName(name: unknown): string | undefined {
193+
return typeof name === 'string' && name.length <= 64 && ERROR_NAME_PATTERN.test(name) ? name : undefined;
194+
}
195+
196+
/** Returns `sqlState` when it is a well-formed 5-character SQLSTATE, otherwise `undefined`. */
197+
export function sanitizeSqlState(sqlState: unknown): string | undefined {
198+
return typeof sqlState === 'string' && SQL_STATE_PATTERN.test(sqlState) ? sqlState : undefined;
199+
}
200+
201+
/**
202+
* Sanitized telemetry descriptor for a thrown value: its class name and
203+
* SQLSTATE. `HiveDriverError` subclasses inherit `name === 'Error'`, so the
204+
* constructor name is used for them.
205+
*/
206+
export function describeErrorForTelemetry(error: unknown): { errorName: string; sqlState?: string } {
207+
const candidate = error as { name?: unknown; sqlState?: unknown } | null | undefined;
208+
let name = candidate?.name;
209+
if ((name === undefined || name === '' || name === 'Error') && typeof error === 'object' && error !== null) {
210+
name = error.constructor?.name;
211+
}
212+
return {
213+
errorName: sanitizeErrorName(name) ?? 'Error',
214+
sqlState: sanitizeSqlState(candidate?.sqlState),
215+
};
216+
}
217+
182218
/**
183219
* Normalises any `HeadersInit` shape (`Headers`, `[string,string][]`, or
184220
* `Record<string, string>`) into a plain string dictionary. Non-string

0 commit comments

Comments
 (0)