Skip to content
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Release History

## Unreleased

- Reuse successful Thrift feature-flag responses across connections to the same workspace (or host) for every auth type, retaining at most 100 idle responses until their original server TTL (currently up to one hour) without keeping connections or timers. For sequential reconnects, `CONNECTION_OPEN` telemetry latency now includes a TLS handshake (~70 ms), so this metric can rise while total connect+openSession latency falls. (#630)

## 3.1.0

- Upgrade to [kernel 1.5.0](https://github.com/databricks/databricks-sql-kernel/releases/tag/v1.5.0): fix CloudFetch pagination, ordering and cancellation, paged inline Arrow results with CloudFetch disabled, and affected-row counts.
Expand Down
57 changes: 48 additions & 9 deletions lib/FeatureFlagCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ import driverVersion from './version';
export interface FeatureFlagContext {
flags?: Map<string, string>;
fetchPromise?: Promise<void>;
lastFetched?: Date;
lastFetched?: number;
cacheable?: boolean;
refCount: number;
cacheDuration: number;
}
Expand All @@ -35,14 +36,18 @@ export interface FeatureFlagContext {
* Acquire/release a context per consumer; each reader uses its caller's auth.
* Responsibilities:
* - dedupe in-flight fetches (thundering-herd protection);
* - ref-count so context goes away when the last consumer closes;
* - retain bounded successful responses until their original expiry;
* - clamp server-provided TTL into a safe band.
*
* Workspace ID partitions SPOG traffic; normalized host is the fallback.
*/
export default class FeatureFlagCache {
private static sharedContexts = new Map<string, FeatureFlagContext>();

private static idleContexts = new Map<string, FeatureFlagContext>();

private static readonly MAX_IDLE_CONTEXTS = 100;

private contexts = FeatureFlagCache.sharedContexts;

private readonly userAgent: string;
Expand All @@ -63,14 +68,23 @@ export default class FeatureFlagCache {
return workspace ? `workspace:${workspace}` : `host:${buildTelemetryUrl(host, '') ?? host}`;
}

private isExpired(ctx: FeatureFlagContext): boolean {
return ctx.lastFetched === undefined || performance.now() - ctx.lastFetched > ctx.cacheDuration;
}

getOrCreateContext(host: string): FeatureFlagContext {
const key = this.cacheKey(host);
let ctx = this.contexts.get(key);
if (!ctx) {
ctx = {
refCount: 0,
cacheDuration: this.CACHE_DURATION_MS,
};
const idle = FeatureFlagCache.idleContexts.get(key);
FeatureFlagCache.idleContexts.delete(key);
ctx =
idle && !this.isExpired(idle)
? idle
: {
refCount: 0,
cacheDuration: this.CACHE_DURATION_MS,
};
this.contexts.set(key, ctx);
}
ctx.refCount += 1;
Expand All @@ -84,6 +98,17 @@ export default class FeatureFlagCache {
ctx.refCount -= 1;
if (ctx.refCount <= 0) {
this.contexts.delete(key);
if (ctx.cacheable && !ctx.fetchPromise && !this.isExpired(ctx)) {
const idle = FeatureFlagCache.idleContexts;
for (const [idleKey, value] of idle) {
if (this.isExpired(value)) idle.delete(idleKey);
}
idle.delete(key);
idle.set(key, ctx);
while (idle.size > FeatureFlagCache.MAX_IDLE_CONTEXTS) {
idle.delete(idle.keys().next().value!);
}
}
}
}
}
Expand All @@ -96,14 +121,14 @@ export default class FeatureFlagCache {
return undefined;
}

const isExpired = !ctx.lastFetched || Date.now() - ctx.lastFetched.getTime() > ctx.cacheDuration;
const isExpired = this.isExpired(ctx);

if (isExpired) {
if (ctx.fetchPromise || isExpired) {
if (!ctx.fetchPromise) {
ctx.fetchPromise = this.fetchFeatureFlags(host)
.then((flags) => {
ctx.flags = flags;
ctx.lastFetched = new Date();
ctx.lastFetched = performance.now();
})
.catch((error: any) => {
logger.log(LogLevel.debug, `Error fetching feature flag: ${error.message}`);
Expand Down Expand Up @@ -175,6 +200,11 @@ export default class FeatureFlagCache {
private async fetchFeatureFlags(host: string): Promise<Map<string, string>> {
const logger = this.context.getLogger();
const ctx = this.contexts.get(this.cacheKey(host));
const previousCacheDuration = ctx?.cacheDuration ?? this.CACHE_DURATION_MS;
if (ctx) {
ctx.cacheable = false;
ctx.cacheDuration = this.CACHE_DURATION_MS;
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
}

try {
const endpoint = buildTelemetryUrl(
Expand Down Expand Up @@ -209,6 +239,11 @@ export default class FeatureFlagCache {
const data: any = await response.json();

if (data && data.flags && Array.isArray(data.flags)) {
if (ctx) {
ctx.cacheable = data.flags.every(
(flag: any) => typeof flag?.name === 'string' && typeof flag.value === 'string',
);
}
if (ctx && Number.isFinite(data.ttl_seconds) && data.ttl_seconds > 0) {
const clampedTtl = Math.max(this.MIN_CACHE_DURATION_S, Math.min(this.MAX_CACHE_DURATION_S, data.ttl_seconds));
ctx.cacheDuration = clampedTtl * 1000;
Expand All @@ -228,6 +263,10 @@ export default class FeatureFlagCache {
// Preserve the existing policy: use consumer defaults until the next TTL.
// Retrying on every read would add request latency during an outage.
return new Map();
} finally {
if (ctx && !ctx.cacheable) {
ctx.cacheDuration = Math.min(previousCacheDuration, this.CACHE_DURATION_MS);
}
}
}

Expand Down
63 changes: 63 additions & 0 deletions tests/e2e/feature_flag_cache.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { expect } from 'chai';
import sinon from 'sinon';
import { DBSQLClient } from '../../lib';
import config from './utils/config';
import FeatureFlagCache from '../../lib/FeatureFlagCache';

describe('Thrift feature flags across idle reconnects', () => {
let sharedContexts: sinon.SinonStub;
let idleContexts: sinon.SinonStub;

beforeEach(() => {
sharedContexts = sinon.stub(FeatureFlagCache as any, 'sharedContexts').value(new Map());
idleContexts = sinon.stub(FeatureFlagCache as any, 'idleContexts').value(new Map());
});

afterEach(() => {
idleContexts.restore();
sharedContexts.restore();
});

for (const reuseClient of [false, true]) {
it(`reuses flags and preserves results when ${
reuseClient ? 'reconnecting a client' : 'creating another client'
}`, async () => {
const fetch = sinon.spy(FeatureFlagCache.prototype as any, 'fetchFeatureFlags');
let client = new DBSQLClient();
let enabled: boolean | undefined;
try {
const cycle = async (iteration: number) => {
if (!reuseClient && iteration > 0) client = new DBSQLClient();
try {
await client.connect({
host: config.host,
path: config.path,
token: config.token,
userAgentEntry: `feature-flag-reconnect-${reuseClient}`,
});
if (iteration === 0) enabled = client.getTelemetryStats() !== undefined;
expect(client.getTelemetryStats() !== undefined).to.equal(enabled);
const session = await client.openSession();
try {
const operation = await session.executeStatement('SELECT 1 AS value, CAST(NULL AS STRING) AS missing');
try {
expect(await operation.fetchAll({ maxRows: 1 })).to.deep.equal([{ value: 1, missing: null }]);
} finally {
await operation.close();
}
} finally {
await session.close();
}
} finally {
await client.close();
}
};
await cycle(0);
await cycle(1);
expect(fetch.callCount).to.equal(1);
} finally {

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 e2e test asserts fetch.callCount === 1, but the flag fetch only happens in initializeTelemetry. That call is skipped when DATABRICKS_TELEMETRY_DISABLED is set, so the count would be 0 and the test would fail for reasons unrelated to caching. Clear and restore the env var around the test, or skip the test when it is set.

🔀 Found by Claude Opus 5.5 · confirmed by the judge

fetch.restore();
}
});
}
});
2 changes: 2 additions & 0 deletions tests/e2e/telemetry/telemetry-integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,13 @@ describe('Telemetry Integration', () => {
beforeEach(() => {
TelemetryClientProvider.__resetInstanceForTests();
flagContexts.clear();
(FeatureFlagCache as any).idleContexts.clear();
});

afterEach(() => {
TelemetryClientProvider.__resetInstanceForTests();
flagContexts.clear();
(FeatureFlagCache as any).idleContexts.clear();
sinon.restore();
});

Expand Down
5 changes: 4 additions & 1 deletion tests/unit/DBSQLClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1094,7 +1094,10 @@ describe('DBSQLClient feature flag lifecycle', () => {
};
const contexts = (FeatureFlagCache as any).sharedContexts as Map<string, unknown>;

beforeEach(() => contexts.clear());
beforeEach(() => {
contexts.clear();
(FeatureFlagCache as any).idleContexts.clear();
});
afterEach(() => {
sinon.restore();
contexts.clear();
Expand Down
Loading
Loading