From 27af82b0e1d9476e2cb0ba20adbf61d75517147f Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Wed, 25 Nov 2026 14:14:50 +0000 Subject: [PATCH 01/15] feat: measure post-startup Entra token renewal (WI-9) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 6 + .../connection-lifecycle/telemetry.md | 188 ++++++++++++++++++ src/commands/signInAgain/signInAgain.test.ts | 28 ++- src/commands/signInAgain/signInAgain.ts | 7 +- src/documentdb/ClustersClient.test.ts | 81 +++++++- src/documentdb/ClustersClient.ts | 16 ++ .../auth/MicrosoftEntraIDAuthHandler.ts | 84 +++++--- src/documentdb/auth/WorkerTokenRelay.ts | 31 ++- src/documentdb/auth/authCallerPolicy.ts | 4 + src/documentdb/auth/tokenExpiry.ts | 6 + src/documentdb/auth/tokenRenewalTelemetry.ts | 32 +++ .../playground/PlaygroundEvaluator.ts | 4 +- .../playground/WorkerSessionManager.test.ts | 86 ++++++++ .../playground/WorkerSessionManager.ts | 3 + .../playground/playgroundWorker.test.ts | 12 +- src/documentdb/playground/playgroundWorker.ts | 20 +- src/documentdb/playground/workerTypes.ts | 2 + src/documentdb/shell/ShellSessionManager.ts | 12 +- 18 files changed, 573 insertions(+), 49 deletions(-) create mode 100644 docs/ai-and-plans/features/connection-lifecycle/telemetry.md create mode 100644 src/documentdb/auth/tokenRenewalTelemetry.ts diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 449bdd0fd..21acee7d1 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1872,6 +1872,12 @@ one loop. **Progress:** +- The WI-9 commit records only checked post-startup Entra database lookups. Host lookup eligibility + follows the published client; worker eligibility is captured when the ready or executing worker + requests the token. Neither uses the first callback as a startup proxy. +- Case 1 passed: `npm run build` and 349 focused tests in 8 files. Ingestion is **pending**; the + [telemetry queries](../telemetry.md) and dashboard scope/volume checks are for the operator. + --- ## WI-10: Documentation (PR 7) diff --git a/docs/ai-and-plans/features/connection-lifecycle/telemetry.md b/docs/ai-and-plans/features/connection-lifecycle/telemetry.md new file mode 100644 index 000000000..fc43cb78a --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/telemetry.md @@ -0,0 +1,188 @@ +--- +feature: connection-lifecycle +kind: notes +status: active +created: 2026-11-25 +--- + +# Connection lifecycle telemetry + +**Pending ingestion verification.** Run these queries in the extension's Application Insights Logs workspace. +Paste the common setup before any one query body. Set the deployment timestamp and actual extension versions +for the two cohorts. Use equal, complete UTC windows, with a gap if the rollout was gradual. + +```kusto +let ReleaseAt = startofday(ago(7d)); // Replace with rollout boundary for this comparison. +let Window = 7d; +let RolloutGap = 0d; +let BaselineVersion = "1.1.1"; +let ReleaseVersion = "1.2.0"; +let BeforeEnd = ReleaseAt - RolloutGap; +let AfterStart = ReleaseAt + RolloutGap; +let Warmup = 1d; +let Events = + customEvents + | where timestamp >= BeforeEnd - Window - Warmup and timestamp < AfterStart + Window + | extend version = coalesce(tostring(customDimensions["common.extversion"]), + tostring(customDimensions.extensionVersion), tostring(column_ifexists("application_Version", "")), "(missing)") + | extend cohort = case( + version == BaselineVersion and timestamp >= BeforeEnd - Window - Warmup and timestamp < BeforeEnd, "before", + version == ReleaseVersion and timestamp >= AfterStart - Warmup and timestamp < AfterStart + Window, "after", "") + | where isnotempty(cohort) + | extend inWindow = iff(cohort == "before", timestamp >= BeforeEnd - Window, timestamp >= AfterStart) + | extend eventScope = tolower(extract(@"([^/]+)$", 1, name)), + sdkResult = tolower(tostring(customDimensions.result)); +let Operations = + Events + | where inWindow + | extend family = case( + eventScope == "connect", "connect", + eventScope startswith "documentdb.rpc.", "rpc", + (eventScope == "getchildren" or eventScope endswith ".getchildren") + and isnotempty(tostring(customDimensions.parentNodeContext)) + and tostring(customDimensions.parentNodeContext) !~ "root" + and tostring(customDimensions.usedCachedErrorNode) !~ "true", "getchildren", + "") + | where isnotempty(family) + | extend connectionResult = tolower(tostring(customDimensions.connectionResult)) + | extend operationResult = case( + sdkResult == "canceled" or connectionResult in ("canceled", "cancelled"), "canceled", + sdkResult == "failed" or connectionResult == "failed", "failed", + sdkResult == "succeeded" or connectionResult == "success", "succeeded", + "(missing)") + | extend ageMs = todouble(customMeasurements.connectionAgeMs), + generation = tolong(customMeasurements.clientGeneration), + failureKind = tostring(customDimensions.connectionFailureKind), + failureType = coalesce(tostring(customDimensions.causeType), tostring(customDimensions.error)), + failureMessage = tostring(customDimensions.errorMessage) + | extend signature = case( + operationResult != "failed", "", + failureType in~ ("18", "391", "AuthenticationFailed", "Unauthorized", + "EntraSignInRequiredError", "EntraIdentityMismatchError"), "auth", + failureType in~ ("MongoNotConnectedError", "MongoTopologyClosedError"), "closedClient", + failureType in~ ("MongoNetworkError", "MongoNetworkTimeoutError", "ECONNRESET", "EPIPE") + or failureMessage matches regex @"(?i)\bconnection \d+ to .+ closed\b", "socket", + "otherOrUnclassified"); +``` + +## Daily database token lookups and lifetime + +`connection.tokenRenewal` counts completed post-startup Entra database token lookups on the extension, +Shell, and Playground. `returned` means a token passed the callback's checks; it does **not** mean the +token changed, MSAL made a network request, or the database accepted the token. Lifetime is the +JWT's positive `exp − iat` in seconds, not its remaining validity. An opaque or invalid lifetime is +missing, not zero. Compare returned rows with and without a lifetime; failures don't have one. + +```kusto +Events +| where inWindow and eventScope == "connection.tokenrenewal" +| extend surface = coalesce(tostring(customDimensions.surface), "(missing)"), + outcome = coalesce(tostring(customDimensions.renewalOutcome), "(missing)"), + lifetime = todouble(customMeasurements.tokenLifetimeSeconds) +| extend lifetime = iff(lifetime > 0, lifetime, real(null)) +| summarize lookups = count(), + lifetimeSamples = countif(isnotnull(lifetime)), + missingLifetime = countif(isnull(lifetime)), + percentiles(lifetime, 50, 90) + by cohort, version, day = bin(timestamp, 1d), surface, outcome +| order by day asc, surface asc, outcome asc +``` + +This is background activity: exclude `connection.tokenrenewal` from active-use event scopes. +Expect roughly one lookup per active Entra client-hour, not one per operation. Use daily counts by +surface to check the observed volume against the telemetry budget. No lookups means no evidence. + +## Post-release outcomes by client age and generation + +Successes on generation 2 or above show the replacement served an operation; they are not a count +of unique recoveries or proof that renewal triggered recovery. Show missing age and generation +explicitly: not every operation has a published client to report. `transient` is broader than +socket failures, so this drilldown keeps the lifecycle kind and the comparable signature separate. + +```kusto +Operations +| where cohort == "after" +| extend ageBand = case( + isnull(ageMs) or ageMs < 0, "(missing)", + ageMs < 3600000, "<1h", ageMs < 7200000, "1–2h", ageMs < 14400000, "2–4h", "4h+"), + generationBand = case(isnull(generation) or generation < 1, "(missing)", generation == 1, "1", "2+"), + lifecycleKind = coalesce(failureKind, "(missing)") +| summarize operations = count(), + successfulOnReplacement = countif(operationResult == "succeeded" and generation >= 2) + by version, family, ageBand, generationBand, operationResult, lifecycleKind, signature +| order by family asc, ageBand asc, generationBand asc +``` + +## Comparable late failures before and after release + +The baseline lacks client age and generation. Use the **same exposure on both versions**: recorded +non-canceled operations at least one hour after the most recent preceding successful database +startup in a VS Code session whose successful startups all used Entra ID. Only existing session +metadata is used for this historical attribution; no session key or raw failure data is returned. +The warmup is the same on both sides. This is a session-age proxy, not a per-client age or a causal +estimate. It can miss sparse telemetry, mixed-auth sessions, and versions that don't report the +same failure signatures. Do not mix new lifecycle-only classifications into the comparison. + +```kusto +let Startups = materialize( + Events + | where eventScope == "connect.startup" and tostring(customDimensions.startupOutcome) =~ "succeeded" + | extend sessionKey = coalesce(tostring(customDimensions.VSCodeSessionId), + tostring(customDimensions["common.vscodesessionid"])), + authMethod = tostring(customDimensions.authMethod) + | where isnotempty(sessionKey) + | project cohort, version, sessionKey, startupAt = timestamp, authMethod +); +let EntraSessions = + Startups + | summarize otherAuth = countif(authMethod !~ "MicrosoftEntraID") by cohort, version, sessionKey + | where otherAuth == 0 + | project cohort, version, sessionKey; +Operations +| where operationResult in ("succeeded", "failed") +| extend sessionKey = coalesce(tostring(customDimensions.VSCodeSessionId), + tostring(customDimensions["common.vscodesessionid"])) +| where isnotempty(sessionKey) +| project cohort, version, sessionKey, timestamp, family, operationResult, signature +| serialize operationRow = row_number() +| join kind=inner (Startups | join kind=leftsemi (EntraSessions) on cohort, version, sessionKey) + on cohort, version, sessionKey +| where startupAt <= timestamp +| summarize arg_max(startupAt, *) by operationRow +| where timestamp - startupAt >= 1h +| summarize exposureOperations = count(), + failedOperations = countif(operationResult == "failed"), + lateAuth = countif(signature == "auth"), + lateSocket = countif(signature == "socket"), + lateClosedClient = countif(signature == "closedClient"), + otherOrUnclassified = countif(signature == "otherOrUnclassified") + by cohort, version, family +| extend authPer1000 = 1000.0 * lateAuth / exposureOperations, + socketPer1000 = 1000.0 * lateSocket / exposureOperations, + closedClientPer1000 = 1000.0 * lateClosedClient / exposureOperations +| order by family asc, cohort asc +``` + +Compare like families and inspect counts along with rates. A missing cohort/family or no later +operations is insufficient exposure, not a zero failure rate. + +## ARM challenge versus final operation result + +Use the existing Azure SDK challenge dimensions and the final framework `result` on the **same** +event. A token was acquired when `challengeSuccess=true`; count `true` with `succeeded` separately +from `true` with `failed`, `canceled`, or a missing result. For a scope that wraps multiple requests +or both ARM and database work, this is the enclosing operation's result, not a per-request ARM +status. Use an ARM-only single-request scope when verifying that ARM accepted the retried request. +Zero observed challenges is inconclusive. + +```kusto +Events +| where inWindow and tostring(customDimensions.challenge) =~ "true" +| extend challengeOutcome = tolower(tostring(customDimensions.challengeSuccess)) +| extend challengeOutcome = case(challengeOutcome == "true", "tokenAcquired", + challengeOutcome == "false", "noToken", "(missing)"), + finalResult = coalesce(sdkResult, "(missing)") +| summarize challengedOperations = count() + by cohort, version, day = bin(timestamp, 1d), eventScope, challengeOutcome, finalResult +| order by day asc, eventScope asc +``` diff --git a/src/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts index 2e28bd824..8d58c74c6 100644 --- a/src/commands/signInAgain/signInAgain.test.ts +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -6,6 +6,7 @@ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; +import { type AuthCallerPolicy } from '../../documentdb/auth/authCallerPolicy'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { EntraIdentityMismatchError, @@ -25,7 +26,7 @@ const pin = { tenantId: 'tenant', } as const; const clusterId = 'cluster'; -const mocks = vi.hoisted(() => ({ configureAuth: vi.fn() })); +const mocks = vi.hoisted(() => ({ configureAuth: vi.fn(), capturePolicy: vi.fn<(policy: AuthCallerPolicy) => void>() })); vi.mock('../../documentdb/ClustersClient', () => ({ addEstablishedConnectionContext: vi.fn(), @@ -40,6 +41,10 @@ vi.mock('../../documentdb/ClustersClient', () => ({ vi.mock('../../documentdb/auth/entraSession', () => ({ getEntraSession: vi.fn() })); vi.mock('../../documentdb/auth/MicrosoftEntraIDAuthHandler', () => ({ MicrosoftEntraIDAuthHandler: class { + constructor(_credentials: unknown, policy: AuthCallerPolicy) { + mocks.capturePolicy(policy); + } + public async configureAuth( _timings: undefined, _trace: undefined, @@ -106,6 +111,27 @@ describe('signInAgain', () => { ); }); + it('observes renewal only for the client established by this sign-in', async (): Promise => { + vi.mocked(getEntraSession).mockResolvedValueOnce({ + account: { id: pin.accountId, label: pin.accountLabel }, + } as vscode.AuthenticationSession); + const isCurrentForTokenRenewal = vi.fn(() => true); + vi.mocked(ClustersClient.startAfterSignIn).mockImplementationOnce(async () => { + const [policy] = mocks.capturePolicy.mock.lastCall!; + expect(policy.canObserveTokenLookup?.()).toBe(false); + return { isCurrentForTokenRenewal } as unknown as ClustersClient; + }); + + await signInAgain(actionContext(), { clusterId }); + + const [policy] = mocks.capturePolicy.mock.lastCall!; + expect(policy.onTokenLookup).toBeTypeOf('function'); + expect(policy.canObserveTokenLookup?.()).toBe(true); + expect(isCurrentForTokenRenewal).toHaveBeenCalledExactlyOnceWith(1); + isCurrentForTokenRenewal.mockReturnValue(false); + expect(policy.canObserveTokenLookup?.()).toBe(false); + }); + it.each([undefined, new Error('User did not consent to login.')])( 'dismisses without reconnecting or retrying session acquisition', async (error): Promise => { diff --git a/src/commands/signInAgain/signInAgain.ts b/src/commands/signInAgain/signInAgain.ts index 5b4a0db62..8e8d9f279 100644 --- a/src/commands/signInAgain/signInAgain.ts +++ b/src/commands/signInAgain/signInAgain.ts @@ -12,8 +12,9 @@ import { EntraSignInRequiredError, } from '../../documentdb/auth/entraErrors/entraCallbackErrors'; import { getEntraSession } from '../../documentdb/auth/entraSession'; -import { sameEntraIdentity } from '../../documentdb/auth/WorkerTokenRelay'; import { MicrosoftEntraIDAuthHandler } from '../../documentdb/auth/MicrosoftEntraIDAuthHandler'; +import { emitTokenRenewal } from '../../documentdb/auth/tokenRenewalTelemetry'; +import { sameEntraIdentity } from '../../documentdb/auth/WorkerTokenRelay'; import { addEstablishedConnectionContext, ClustersClient } from '../../documentdb/ClustersClient'; import { classifyConnectionFailure } from '../../documentdb/connectionFailures'; import { CredentialCache } from '../../documentdb/CredentialCache'; @@ -129,10 +130,13 @@ async function signInAgainInternal( }; let starting = false; + let established: { client: ClustersClient; epoch: number } | undefined; try { const handler = new MicrosoftEntraIDAuthHandler(credentials, { interactive: false, pinnedEntraIdentity: identity, + canObserveTokenLookup: () => established?.client.isCurrentForTokenRenewal(established.epoch) ?? false, + onTokenLookup: (observation) => emitTokenRenewal('extension', observation), }); const auth = await handler.configureAuth(undefined, undefined, async (request) => { if (!isCurrent()) { @@ -176,6 +180,7 @@ async function signInAgainInternal( reportClosed(); return undefined; } + established = { client, epoch: startupEpoch }; if ( ClustersClient.getExistingClient(clusterId) === client && !ClustersClient.getLatchReason(clusterId) && diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 1e6218c59..853c142d4 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -20,11 +20,13 @@ import { traceAuthFlow, type AuthTraceContext } from '../utils/authTrace'; import { type VerifiedEntraIdentity } from './auth/AuthHandler'; import { AuthMethodId } from './auth/AuthMethod'; import * as authHandlerFactory from './auth/createAuthHandler'; +import * as tokenResource from './auth/documentdbTokenResource'; import { EntraIdentityMismatchError, EntraSignInRequiredError, TokenCallbackError, } from './auth/entraErrors/entraCallbackErrors'; +import * as entraSession from './auth/entraSession'; import { ManagedIdentityAuthHandler } from './auth/ManagedIdentityAuthHandler'; import { MicrosoftEntraIDAuthHandler } from './auth/MicrosoftEntraIDAuthHandler'; import { NativeAuthHandler } from './auth/NativeAuthHandler'; @@ -170,6 +172,7 @@ describe('regular connection startup diagnostics', () => { const mockToArray = vi.fn<() => Promise[]>>(); const mockDeleteMany = vi.fn<() => Promise>(); let poolEvents: EventEmitter; + const configureEntraAuth = MicrosoftEntraIDAuthHandler.prototype.configureAuth; function pauseNextConnect(): { started: Promise; resolve: () => void; reject: (error: Error) => void } { const started = deferred(); @@ -565,7 +568,7 @@ describe('regular connection startup diagnostics', () => { expect(authHandlerFactory.createAuthHandler).toHaveBeenLastCalledWith( AuthMethodId.MicrosoftEntraID, expect.objectContaining({ clusterId }), - { interactive: true }, + expect.objectContaining({ interactive: true }), ); expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toEqual(verifiedIdentity); }); @@ -598,7 +601,7 @@ describe('regular connection startup diagnostics', () => { expect(authHandlerFactory.createAuthHandler).toHaveBeenLastCalledWith( AuthMethodId.MicrosoftEntraID, expect.objectContaining({ clusterId }), - { interactive: false, pinnedEntraIdentity: currentIdentity }, + expect.objectContaining({ interactive: false, pinnedEntraIdentity: currentIdentity }), ); expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(published); } @@ -1436,16 +1439,84 @@ describe('regular connection startup diagnostics', () => { const factory = vi.mocked(authHandlerFactory.createAuthHandler); expect(factory).toHaveBeenCalledTimes(1); - expect(factory).toHaveBeenCalledWith(authMethod, expect.objectContaining({ clusterId }), { + const policy = { interactive, - }); + ...(interactive + ? { canObserveTokenLookup: expect.any(Function), onTokenLookup: expect.any(Function) } + : {}), + }; + expect(factory).toHaveBeenCalledWith(authMethod, expect.objectContaining({ clusterId }), policy); const handler = factory.mock.results[0]?.value as unknown; expect(handler).toBeInstanceOf(handlerClass); - expect(handler).toHaveProperty('policy', { interactive }); + expect(handler).toHaveProperty('policy', policy); expect(handlerClass.prototype.configureAuth).toHaveBeenCalledTimes(1); }, ); + it('counts completed Entra lookups only after startup, independent of database acceptance', async () => { + CredentialCache.setAuthCredentials( + clusterId, + AuthMethodId.MicrosoftEntraID, + 'mongodb://example.mongocluster.cosmos.azure.com/', + ); + vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockImplementation(configureEntraAuth); + vi.spyOn(tokenResource, 'resolveInteractiveTokenResource').mockResolvedValue({ + cloudCategory: 'public', reason: 'host', scope: 'test-scope', resource: 'test-resource', details: {}, + }); + vi.spyOn(entraSession, 'readEntraSignInEnvironment').mockReturnValue({ + providerId: 'microsoft', cloudName: 'AzureCloud', authority: 'https://login.microsoftonline.com/', + }); + const now = 1_800_000_000; + vi.setSystemTime(now * 1000); + const timedToken = `header.${Buffer.from(JSON.stringify({ iat: now - 600, exp: now + 3000 })).toString('base64url')}.signature`; + const account = { id: 'test-account', label: 'Test account' }; + const session = { id: 'test-session', account, accessToken: timedToken, scopes: [] }; + const getSession = vi.spyOn(entraSession, 'getEntraSession').mockResolvedValue(session); + const signal = new AbortController(); + const lookup = async (timeoutContext = signal.signal): Promise => { + const options = vi.mocked(MongoClient).mock.lastCall?.[1]; + const callback = options?.authMechanismProperties?.OIDC_CALLBACK; + if (!callback) { + throw new Error('Expected an OIDC callback'); + } + return await callback({ version: 1, timeoutContext }); + }; + const renewalEvents = (): RecordedTelemetry[] => + mockTelemetryEvents.filter(({ eventName }) => eventName === 'connection.tokenRenewal'); + const serverRejection = new MongoServerError({ code: 18, message: 'test server rejection' }); + + mockConnect.mockImplementationOnce(async () => { + await lookup(); + await lookup(); + throw serverRejection; + }); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toBe(serverRejection); + expect(renewalEvents()).toEqual([]); + + // Startup itself succeeds without calling the callback. Its first later callback counts. + const client = await ClustersClient.connectInteractive(clusterId); + expect(renewalEvents()).toEqual([]); + mockListDatabases.mockImplementationOnce(async () => { + expect(await lookup()).toEqual({ accessToken: timedToken, expiresInSeconds: 2999 }); + throw serverRejection; + }); + await expect(client.listDatabases()).rejects.toBe(serverRejection); + + vi.advanceTimersByTime(600_000); + getSession.mockResolvedValueOnce({ ...session, accessToken: 'opaque-test-token' }); + await expect(lookup()).resolves.toEqual({ accessToken: 'opaque-test-token' }); + getSession.mockResolvedValueOnce(undefined); + await expect(lookup()).rejects.toBeInstanceOf(EntraSignInRequiredError); + + signal.abort(); + await lookup(); + expect(renewalEvents().map(({ telemetry, error }) => [telemetry.properties, telemetry.measurements, error])).toEqual([ + [{ surface: 'extension', renewalOutcome: 'returned', result: 'Succeeded' }, { tokenLifetimeSeconds: 3600, duration: 0 }, undefined], + [{ surface: 'extension', renewalOutcome: 'returned', result: 'Succeeded' }, { duration: 0 }, undefined], + [{ surface: 'extension', renewalOutcome: 'noSession', result: 'Succeeded' }, { duration: 0 }, undefined], + ]); + }); + it('passes its startup ID to auth configuration', async (): Promise => { let traceContext: AuthTraceContext | undefined; vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockImplementationOnce( diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 7faae61a5..51820ad68 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -51,6 +51,7 @@ import { createAuthHandler } from './auth/createAuthHandler'; import { EntraSignInRequiredError } from './auth/entraErrors/entraCallbackErrors'; import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; import { readJwtTimes } from './auth/tokenExpiry'; +import { emitTokenRenewal } from './auth/tokenRenewalTelemetry'; import { QueryInsightsApis, type ExplainVerbosity } from './client/QueryInsightsApis'; import { isRetiredConnectionBinding, retireConnectionBindings } from './connectionBindingRetirement'; import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; @@ -633,6 +634,12 @@ export class ClustersClient { const authHandler = createAuthHandler(authMethod, credentials, { interactive: allowInteractive && !pinnedEntraIdentity, ...(pinnedEntraIdentity ? { pinnedEntraIdentity } : {}), + ...(authMethod === AuthMethodId.MicrosoftEntraID + ? { + canObserveTokenLookup: () => this.isCurrentForTokenRenewal(epoch), + onTokenLookup: (observation) => emitTokenRenewal('extension', observation), + } + : {}), }); // Configure auth and get connection options @@ -1135,6 +1142,15 @@ export class ClustersClient { return !this._closed && this._replacement === undefined; } + public isCurrentForTokenRenewal(epoch: number): boolean { + return ( + !this._closed && + ClustersClient.getExistingClient(this.clusterId) === this && + ClustersClient.getEpoch(this.clusterId) === epoch && + !ClustersClient.getLatchReason(this.clusterId) + ); + } + public static hasReusableClient(clusterId: string): boolean { return ClustersClient._clients.get(clusterId)?.canReuse() ?? false; } diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts index 671f5a530..67bc5f271 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { isUserCancelledError } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import { randomUUID } from 'crypto'; import { type OIDCCallbackParams, type OIDCResponse } from 'mongodb'; @@ -31,16 +32,8 @@ import { clearEntraTokenFailure, recordEntraTokenFailure } from './entraErrors/e import { getEntraSession, readEntraSignInEnvironment, type EntraSignInEnvironment } from './entraSession'; import { EntraDestinationRejectedError } from './oidcAllowedHosts'; import { buildOidcClientConfiguration, createOidcDestinationPolicy } from './oidcClientOptions'; -import { readJwtTimes } from './tokenExpiry'; - -interface EntraTokenLookupObservation { - readonly outcome: 'returned' | 'noSession' | 'identityMismatch' | 'failed'; - readonly lifetimeSeconds?: number; -} - -interface EntraCallerPolicy extends AuthCallerPolicy { - readonly onTokenLookup?: (observation: EntraTokenLookupObservation) => void; -} +import { jwtLifetimeSeconds, readJwtTimes } from './tokenExpiry'; +import { type EntraTokenLookupObservation } from './tokenRenewalTelemetry'; function assertEntraSignInEnvironment(expected: EntraSignInEnvironment | undefined): EntraSignInEnvironment { let current: EntraSignInEnvironment; @@ -69,13 +62,21 @@ function assertEntraSignInEnvironment(expected: EntraSignInEnvironment | undefin export class MicrosoftEntraIDAuthHandler implements AuthHandler { constructor( private readonly clusterCredentials: CachedClusterCredentials, - public readonly policy: EntraCallerPolicy = { interactive: true }, + public readonly policy: AuthCallerPolicy = { interactive: true }, ) {} private notify(notify: (observer: AuthPhaseObserver) => void): void { notifyAuthPhaseObserver(this.policy.observer, notify); } + private canObserveTokenLookup(): boolean { + try { + return this.policy.onTokenLookup !== undefined && (this.policy.canObserveTokenLookup?.() ?? true); + } catch { + return false; + } + } + public async configureAuth( timings?: ConnectionStartupTimings, traceContext?: AuthTraceContext, @@ -232,7 +233,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { callbackAuthMethod: AuthMethodId.MicrosoftEntraID, oidcCallback: async (_params: OIDCCallbackParams): Promise => { const currentInvocation = ++invocation; - let observation: EntraTokenLookupObservation = { outcome: 'failed' }; + let returned = false; try { assertEntraSignInEnvironment(signInEnvironment); let renewed: vscode.AuthenticationSession | undefined; @@ -246,27 +247,20 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { throw new EntraSignInRequiredError('noSession'); } if (renewed.account.id !== accountId) { - observation = { outcome: 'identityMismatch' }; throw new EntraIdentityMismatchError(); } const { accessToken } = renewed; - const { iatSec, expSec } = readJwtTimes(accessToken); - const lifetimeSeconds = iatSec !== undefined && expSec !== undefined ? expSec - iatSec : undefined; - observation = { - outcome: 'returned', - ...(lifetimeSeconds !== undefined && Number.isFinite(lifetimeSeconds) - ? { lifetimeSeconds } - : {}), - }; + const { expSec } = readJwtTimes(accessToken); + returned = true; return expSec === undefined ? { accessToken } : { accessToken, expiresInSeconds: Math.max(0, Math.floor(expSec - Date.now() / 1000)) }; } catch (error) { - if (error instanceof EntraSignInRequiredError) { - observation = { outcome: 'noSession' }; - throw error; - } - if (error instanceof EntraIdentityMismatchError || error instanceof EntraDestinationRejectedError) { + if ( + error instanceof EntraSignInRequiredError || + error instanceof EntraIdentityMismatchError || + error instanceof EntraDestinationRejectedError + ) { throw error; } recordEntraTokenFailure(clusterId, { @@ -280,26 +274,38 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { 'interactiveEntra.oidcCallback', { invocation: currentInvocation, - outcome: observation.outcome === 'returned' ? 'returned' : 'threw', + outcome: returned ? 'returned' : 'threw', }, authCorrelationId, traceContext, ); - try { - this.policy.onTokenLookup?.(observation); - } catch { - // Observers never change the auth flow. - } } }, }); const properties = configuration.options.authMechanismProperties; const callback = properties?.OIDC_CALLBACK; - if (this.policy.observer?.onCallbackTokenObserved && properties && callback) { + if ((this.policy.onTokenLookup || this.policy.observer?.onCallbackTokenObserved) && properties && callback) { properties.OIDC_CALLBACK = async (params): Promise => { + const observe = this.canObserveTokenLookup(); + const notifyLookup = (observation: EntraTokenLookupObservation): void => { + if (observe && !params.timeoutContext?.aborted && this.canObserveTokenLookup()) { + try { + this.policy.onTokenLookup?.(observation); + } catch { + // Observers never change the auth flow. + } + } + }; try { // Report acquisition only after the configured callback re-checks destination trust. const response = await callback(params); + if (observe) { + const lifetimeSeconds = jwtLifetimeSeconds(readJwtTimes(response.accessToken)); + notifyLookup({ + outcome: 'returned', + ...(lifetimeSeconds !== undefined ? { lifetimeSeconds } : {}), + }); + } this.notify((observer) => observer.onCallbackTokenObserved?.({ outcome: 'acquired', @@ -309,6 +315,18 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { ); return response; } catch (error) { + if ( + !isUserCancelledError(error) && + !(error instanceof TokenCallbackError && isUserCancelledError(error.cause)) + ) { + let outcome: EntraTokenLookupObservation['outcome'] = 'failed'; + if (error instanceof EntraSignInRequiredError) { + outcome = 'noSession'; + } else if (error instanceof EntraIdentityMismatchError) { + outcome = 'identityMismatch'; + } + notifyLookup({ outcome }); + } if ( error instanceof EntraSignInRequiredError || error instanceof EntraIdentityMismatchError || diff --git a/src/documentdb/auth/WorkerTokenRelay.ts b/src/documentdb/auth/WorkerTokenRelay.ts index 7d8b91452..07d6a57cc 100644 --- a/src/documentdb/auth/WorkerTokenRelay.ts +++ b/src/documentdb/auth/WorkerTokenRelay.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { UserCancelledError } from '@microsoft/vscode-azext-utils'; +import { isUserCancelledError, UserCancelledError } from '@microsoft/vscode-azext-utils'; import { traceAuthFlow, traceEntraDestination, type AuthTraceContext } from '../../utils/authTrace'; import { ClustersClient } from '../ClustersClient'; import { @@ -30,6 +30,8 @@ import { import { clearEntraTokenFailure, recordEntraTokenFailure } from './entraErrors/entraTokenFailures'; import { getEntraSession, readEntraSignInEnvironment } from './entraSession'; import { EntraDestinationRejectedError } from './oidcAllowedHosts'; +import { jwtLifetimeSeconds, readJwtTimes } from './tokenExpiry'; +import { emitTokenRenewal } from './tokenRenewalTelemetry'; export function sameEntraIdentity(a: VerifiedEntraIdentity, b: VerifiedEntraIdentity): boolean { return a.providerId === b.providerId && a.accountId === b.accountId && a.tenantId === b.tenantId; @@ -63,11 +65,12 @@ export class WorkerTokenRelay { ) {} async relay( - { requestId }: Extract, + { requestId, driverAbortFlag }: Extract, postResponse: (response: MainToWorkerMessage) => void, isCurrentWorker: () => boolean, timings?: ConnectionStartupTimings, trace?: AuthTraceContext, + postStartup = false, epoch = this.epoch, ): Promise { const isCurrentEpoch = (): boolean => @@ -85,8 +88,15 @@ export class WorkerTokenRelay { }; const activeTrace = (): AuthTraceContext | undefined => isCurrentWorker() && isCurrentEpoch() ? trace : undefined; - const { connectionString, authMechanism, tenantId, managedIdentityClientId } = this.init; + const { connectionString, authMechanism, tenantId, managedIdentityClientId, persistent } = this.init; const managed = authMechanism === AuthMethodId.ManagedIdentity; + const abortFlag = + driverAbortFlag instanceof SharedArrayBuffer && driverAbortFlag.byteLength === Int32Array.BYTES_PER_ELEMENT + ? new Int32Array(driverAbortFlag) + : undefined; + const shouldObserve = (): boolean => + postStartup && authMechanism === AuthMethodId.MicrosoftEntraID && (!abortFlag || Atomics.load(abortFlag, 0) === 0); + const surface = persistent ? 'shell' : 'playground'; const assertDestination = (): void => { const decision = evaluateEntraDestinationFromSettings(connectionString); traceEntraDestination(decision, requestId, activeTrace()); @@ -202,6 +212,12 @@ export class WorkerTokenRelay { clearEntraTokenFailure(this.clusterId); traceAuthFlow('workerTokenRelay.completed', { mode, outcome: 'returned' }, requestId, activeTrace()); postResponse({ type: 'tokenResponse', requestId, accessToken }); + if (shouldObserve()) { + emitTokenRenewal(surface, { + outcome: 'returned', + lifetimeSeconds: jwtLifetimeSeconds(readJwtTimes(accessToken)), + }); + } } catch (error) { if (!canReply()) { return; @@ -232,6 +248,15 @@ export class WorkerTokenRelay { reason, ...(reason === 'destinationRejected' ? { errorName: 'EntraDestinationRejectedError' as const } : {}), }); + if (shouldObserve() && !isUserCancelledError(error)) { + let outcome: 'noSession' | 'identityMismatch' | 'failed' = 'failed'; + if (reason === 'signInRequired') { + outcome = 'noSession'; + } else if (reason === 'identityMismatch') { + outcome = 'identityMismatch'; + } + emitTokenRenewal(surface, { outcome }); + } } }; diff --git a/src/documentdb/auth/authCallerPolicy.ts b/src/documentdb/auth/authCallerPolicy.ts index b357a2db2..a000992ed 100644 --- a/src/documentdb/auth/authCallerPolicy.ts +++ b/src/documentdb/auth/authCallerPolicy.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { type VerifiedEntraIdentity } from './AuthHandler'; +import { type EntraTokenLookupObservation } from './tokenRenewalTelemetry'; /** * Host-only callbacks that report the authentication phases in the order they really happen. @@ -44,6 +45,9 @@ export interface AuthCallerPolicy { readonly interactive: boolean; readonly pinnedEntraIdentity?: VerifiedEntraIdentity; readonly observer?: AuthPhaseObserver; + /** Entra only. Check at callback entry and completion to exclude startup and obsolete clients. */ + readonly canObserveTokenLookup?: () => boolean; + readonly onTokenLookup?: (observation: EntraTokenLookupObservation) => void; } /** diff --git a/src/documentdb/auth/tokenExpiry.ts b/src/documentdb/auth/tokenExpiry.ts index 0d6f4dd7f..c279ff99f 100644 --- a/src/documentdb/auth/tokenExpiry.ts +++ b/src/documentdb/auth/tokenExpiry.ts @@ -27,6 +27,12 @@ export function readJwtTimes(token: string): { iatSec?: number; expSec?: number } } +/** The JWT's full lifetime, not its remaining validity or an opaque-token fallback. */ +export function jwtLifetimeSeconds({ iatSec, expSec }: ReturnType): number | undefined { + const lifetime = iatSec !== undefined && expSec !== undefined ? expSec - iatSec : undefined; + return lifetime !== undefined && Number.isFinite(lifetime) && lifetime > 0 ? lifetime : undefined; +} + /** * Seconds until an absolute expiry timestamp (milliseconds since the epoch), floored at zero. * diff --git a/src/documentdb/auth/tokenRenewalTelemetry.ts b/src/documentdb/auth/tokenRenewalTelemetry.ts new file mode 100644 index 000000000..56fe50753 --- /dev/null +++ b/src/documentdb/auth/tokenRenewalTelemetry.ts @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { callWithTelemetryAndErrorHandling } from '@microsoft/vscode-azext-utils'; + +export interface EntraTokenLookupObservation { + readonly outcome: 'returned' | 'noSession' | 'identityMismatch' | 'failed'; + readonly lifetimeSeconds?: number; +} + +export function emitTokenRenewal( + surface: 'extension' | 'shell' | 'playground', + { outcome, lifetimeSeconds }: EntraTokenLookupObservation, +): void { + void callWithTelemetryAndErrorHandling('connection.tokenRenewal', (context) => { + context.errorHandling.suppressDisplay = true; + context.telemetry.properties.surface = surface; + context.telemetry.properties.renewalOutcome = outcome; + if ( + outcome === 'returned' && + lifetimeSeconds !== undefined && + Number.isFinite(lifetimeSeconds) && + lifetimeSeconds > 0 + ) { + context.telemetry.measurements.tokenLifetimeSeconds = lifetimeSeconds; + } + }).catch(() => { + // Telemetry delivery must not affect authentication. + }); +} diff --git a/src/documentdb/playground/PlaygroundEvaluator.ts b/src/documentdb/playground/PlaygroundEvaluator.ts index 86dfab8bf..42c7fe272 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.ts @@ -168,9 +168,9 @@ export class PlaygroundEvaluator implements vscode.Disposable { break; } }, - onTokenRequest: async (request, post, isCurrent, timings, trace) => { + onTokenRequest: async (request, post, isCurrent, timings, trace, postStartup) => { const relay = this._relay; - await relay?.relay(request, post, () => this._relay === relay && isCurrent(), timings, trace); + await relay?.relay(request, post, () => this._relay === relay && isCurrent(), timings, trace, postStartup); }, onWorkerExit: (exitCode: number) => { ext.outputChannel.debug(`${logPrefix} Worker exited with code ${String(exitCode)}`); diff --git a/src/documentdb/playground/WorkerSessionManager.test.ts b/src/documentdb/playground/WorkerSessionManager.test.ts index d4a1fe4b7..dcd3de7fb 100644 --- a/src/documentdb/playground/WorkerSessionManager.test.ts +++ b/src/documentdb/playground/WorkerSessionManager.test.ts @@ -16,6 +16,7 @@ import { ext } from '../../extensionVariables'; import { traceAuthFlow, type AuthTraceContext } from '../../utils/authTrace'; import { AuthMethodId } from '../auth/AuthMethod'; import * as tokenResource from '../auth/documentdbTokenResource'; +import * as entraSession from '../auth/entraSession'; import { getRecentEntraTokenFailure, recordEntraTokenFailure, @@ -809,6 +810,91 @@ describe('WorkerSessionManager', () => { return { manager, initPromise, requestId: initMessage.requestId, worker }; } + it.each([true, false])('counts only checked post-startup Entra relay outcomes (persistent=%s)', async (persistent) => { + const clusterId = 'test-cluster'; + const environment = { + providerId: 'microsoft', cloudName: 'AzureCloud', authority: 'https://login.microsoftonline.com/', + }; + const readEnvironment = vi.spyOn(entraSession, 'readEntraSignInEnvironment').mockReturnValue(environment); + const resolveResource = vi.spyOn(tokenResource, 'resolveInteractiveTokenResource').mockResolvedValue({ + cloudCategory: 'public', reason: 'host', scope: 'test-scope', resource: 'test-resource', details: {}, + }); + const account = { id: 'test-account', label: 'Test account' }; + const now = 1_800_000_000; + vi.setSystemTime(now * 1000); + const accessToken = `header.${Buffer.from(JSON.stringify({ iat: now - 60, exp: now + 3540 })).toString('base64url')}.signature`; + const session = { id: 'test-session', account, accessToken, scopes: [] }; + const getSession = vi.spyOn(entraSession, 'getEntraSession').mockResolvedValue(session); + const relay = new WorkerTokenRelay( + clusterId, + { + type: 'init', requestId: '', connectionString: 'mongodb://example.mongocluster.cosmos.azure.com/', + clientOptions: {}, databaseName: 'test', authMechanism: AuthMethodId.MicrosoftEntraID, persistent, + }, + ClustersClient.getEpoch(clusterId), + 'relay-id', + undefined, + ); + const onTokenRequest = vi.fn>( + relay.relay.bind(relay), + ); + callbacks.onTokenRequest = onTokenRequest; + const manager = new WorkerSessionManager(callbacks); + try { + const active = await startWorker(persistent, {}, manager); + const request = async (requestId: string): Promise => { + active.worker._emit('message', { type: 'tokenRequest', requestId }); + await onTokenRequest.mock.results.at(-1)?.value; + }; + const renewalEvents = (): RecordedTelemetry[] => + mockTelemetryEvents.filter(({ eventName }) => eventName === 'connection.tokenRenewal'); + await request('startup-lookup'); + await request('another-startup-lookup'); + expect(renewalEvents()).toEqual([]); + active.worker._emit('message', { type: 'initResult', requestId: active.requestId, success: true }); + await active.initPromise; + + await request('renewal-with-lifetime'); + getSession.mockResolvedValueOnce({ ...session, accessToken: 'opaque-test-token' }); + await request('opaque-renewal'); + getSession.mockResolvedValueOnce(undefined); + await request('missing-session'); + getSession.mockResolvedValueOnce({ ...session, account: { ...account, id: 'different-account' } }); + await request('identity-mismatch'); + readEnvironment.mockReturnValueOnce({ ...environment, providerId: 'microsoft-sovereign-cloud' }); + await request('provider-changed'); + getSession.mockRejectedValueOnce(new Error('test provider failure')); + await request('refresh-failed'); + getSession.mockRejectedValueOnce(new UserCancelledError()); + await request('canceled-lookup'); + const driverAbortFlag = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT); + getSession.mockImplementationOnce(async () => { + Atomics.store(new Int32Array(driverAbortFlag), 0, 1); + return session; + }); + active.worker._emit('message', { type: 'tokenRequest', requestId: 'driver-stopped-waiting', driverAbortFlag }); + await onTokenRequest.mock.results.at(-1)?.value; + ClustersClient.invalidate(clusterId); + await expect(request('stale-lookup')).rejects.toBeInstanceOf(UserCancelledError); + + const surface = persistent ? 'shell' : 'playground'; + expect(renewalEvents().map(({ telemetry, error }) => [telemetry.properties, telemetry.measurements, error])) + .toEqual([ + [{ surface, renewalOutcome: 'returned', result: 'Succeeded' }, { tokenLifetimeSeconds: 3600, duration: 0 }, undefined], + [{ surface, renewalOutcome: 'returned', result: 'Succeeded' }, { duration: 0 }, undefined], + [{ surface, renewalOutcome: 'noSession', result: 'Succeeded' }, { duration: 0 }, undefined], + [{ surface, renewalOutcome: 'identityMismatch', result: 'Succeeded' }, { duration: 0 }, undefined], + [{ surface, renewalOutcome: 'noSession', result: 'Succeeded' }, { duration: 0 }, undefined], + [{ surface, renewalOutcome: 'failed', result: 'Succeeded' }, { duration: 0 }, undefined], + ]); + } finally { + manager.dispose(); + getSession.mockRestore(); + resolveResource.mockRestore(); + readEnvironment.mockRestore(); + } + }); + it.each(['signInRequired', 'identityMismatch', 'destinationRejected', 'refreshFailed'] as const)( 'reconstructs %s at both boundaries and marks a warm worker broken', async (reason): Promise => { diff --git a/src/documentdb/playground/WorkerSessionManager.ts b/src/documentdb/playground/WorkerSessionManager.ts index ff9319695..4b19ec956 100644 --- a/src/documentdb/playground/WorkerSessionManager.ts +++ b/src/documentdb/playground/WorkerSessionManager.ts @@ -102,6 +102,7 @@ export interface WorkerSessionCallbacks { isCurrent: () => boolean, timings?: ConnectionStartupTimings, traceContext?: AuthTraceContext, + postStartup?: boolean, ) => Promise; /** Called when the worker exits (crash or termination). */ onWorkerExit?: (exitCode: number) => void; @@ -755,6 +756,8 @@ export class WorkerSessionManager implements vscode.Disposable { isCurrent, this._startup?.costTimings, connection, + // Snapshot at receipt: time spent queued in the relay cannot make a startup lookup a renewal. + this._workerState === 'ready' || this._workerState === 'executing', ); } catch (error) { if (isCurrent()) { diff --git a/src/documentdb/playground/playgroundWorker.test.ts b/src/documentdb/playground/playgroundWorker.test.ts index c70f47710..5bed4ac93 100644 --- a/src/documentdb/playground/playgroundWorker.test.ts +++ b/src/documentdb/playground/playgroundWorker.test.ts @@ -128,11 +128,21 @@ describe('playground worker OIDC configuration at the driver boundary', () => { if (!callback) { throw new Error('Expected the OIDC callback'); } - const token = callback({ version: 1, timeoutContext: new AbortController().signal }); + const controller = new AbortController(); + const token = callback({ version: 1, timeoutContext: controller.signal }); const request = transport.postMessage.mock.calls .map((call) => call[0] as WorkerToMainMessage) .find((message) => message.type === 'tokenRequest'); expect(request).toBeDefined(); + if (authMechanism === 'MicrosoftEntraID') { + expect(request?.driverAbortFlag).toBeInstanceOf(SharedArrayBuffer); + const abortFlag = new Int32Array(request!.driverAbortFlag!); + expect(Atomics.load(abortFlag, 0)).toBe(0); + controller.abort(); + expect(Atomics.load(abortFlag, 0)).toBe(1); + } else { + expect(request?.driverAbortFlag).toBeUndefined(); + } receive({ type: 'tokenResponse', requestId: request!.requestId, accessToken: 'dummy-token' }); await expect(token).resolves.toMatchObject({ accessToken: 'dummy-token', expiresInSeconds: 3500 }); }, diff --git a/src/documentdb/playground/playgroundWorker.ts b/src/documentdb/playground/playgroundWorker.ts index 1da8a4474..2fb915e93 100644 --- a/src/documentdb/playground/playgroundWorker.ts +++ b/src/documentdb/playground/playgroundWorker.ts @@ -209,17 +209,32 @@ async function handleInit(msg: Extract): connectionString, policy, baseOptions: options, - oidcCallback: async (): Promise<{ accessToken: string; expiresInSeconds: number }> => { + oidcCallback: async ({ timeoutContext }): Promise<{ accessToken: string; expiresInSeconds: number }> => { const requestId = randomUUID(); const tokenPromise = new Promise((resolve, reject) => { pendingTokenRequests.set(requestId, { resolve, reject }); }); + const driverAbortFlag = + !usesManagedIdentity && timeoutContext + ? new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT) + : undefined; + const abortFlag = driverAbortFlag && new Int32Array(driverAbortFlag); + const markAborted = (): void => { + if (abortFlag) Atomics.store(abortFlag, 0, 1); + }; + if (abortFlag) { + timeoutContext.addEventListener('abort', markAborted, { once: true }); + if (timeoutContext.aborted) { + markAborted(); + } + } const tokenRequest: WorkerToMainMessage = { type: 'tokenRequest', requestId, tenantId: msg.tenantId, source: usesManagedIdentity ? 'managedIdentity' : 'vscode', clientId: usesManagedIdentity ? msg.managedIdentityClientId : undefined, + ...(driverAbortFlag ? { driverAbortFlag } : {}), }; reportProgress('acquiringToken'); reportTiming('tokenWait', requestId, true); @@ -228,6 +243,9 @@ async function handleInit(msg: Extract): try { accessToken = await tokenPromise; } finally { + if (abortFlag) { + timeoutContext.removeEventListener('abort', markAborted); + } reportTiming('tokenWait', requestId, false); } reportProgress('authenticating'); diff --git a/src/documentdb/playground/workerTypes.ts b/src/documentdb/playground/workerTypes.ts index ddf017718..9d49b622b 100644 --- a/src/documentdb/playground/workerTypes.ts +++ b/src/documentdb/playground/workerTypes.ts @@ -229,6 +229,8 @@ export type WorkerToMainMessage = readonly source?: 'vscode' | 'managedIdentity'; /** Client ID of a user-assigned managed identity, when `source` is 'managedIdentity'. */ readonly clientId?: string; + /** One shared Int32 set to 1 if the driver stops waiting for this Entra lookup. Telemetry only. */ + readonly driverAbortFlag?: SharedArrayBuffer; } | { readonly type: 'log'; diff --git a/src/documentdb/shell/ShellSessionManager.ts b/src/documentdb/shell/ShellSessionManager.ts index 01eda6c82..47e9c1974 100644 --- a/src/documentdb/shell/ShellSessionManager.ts +++ b/src/documentdb/shell/ShellSessionManager.ts @@ -140,12 +140,20 @@ export class ShellSessionManager implements vscode.Disposable { break; } }, - onTokenRequest: async (request, post, isCurrent, timings, trace) => { + onTokenRequest: async (request, post, isCurrent, timings, trace, postStartup) => { const relay = this._relay; // Warm Shells survive host-only invalidation. Fence each refresh at receipt; // startup still uses the epoch captured before opening the connection. const epoch = this._initialized ? ClustersClient.getEpoch(this._connectionInfo.clusterId) : relay?.epoch; - await relay?.relay(request, post, () => this._relay === relay && isCurrent(), timings, trace, epoch); + await relay?.relay( + request, + post, + () => this._relay === relay && isCurrent(), + timings, + trace, + postStartup, + epoch, + ); }, onWorkerExit: callbacks?.onWorkerExit, }; From 9c73b7d62b1edc0930d0edeeee59b37adbf147f7 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 06:51:23 +0000 Subject: [PATCH 02/15] docs: document connection lifecycle (WI-10) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/skills/error-translation/SKILL.md | 23 ++++++ .../skills/tree-cluster-architecture/SKILL.md | 30 ++++++- CHANGELOG.md | 10 +++ .../features/connection-lifecycle/README.md | 35 +++++++- .../connection-lifecycle/decisions.md | 7 +- docs/index.md | 1 + docs/release-notes/1.2.md | 80 +++++++++++++++++++ docs/user-manual/connecting-to-databases.md | 57 +++++++++++++ docs/user-manual/interactive-shell.md | 5 +- docs/user-manual/managing-azure-discovery.md | 1 + docs/user-manual/query-playground.md | 4 +- 11 files changed, 247 insertions(+), 6 deletions(-) create mode 100644 docs/release-notes/1.2.md diff --git a/.github/skills/error-translation/SKILL.md b/.github/skills/error-translation/SKILL.md index 692077e78..279e17a8e 100644 --- a/.github/skills/error-translation/SKILL.md +++ b/.github/skills/error-translation/SKILL.md @@ -28,6 +28,28 @@ for, and errors that are already obsolete by the time they appear. Anything with a side effect belongs at the call site, which alone knows whether the user is watching, whether the operation was a read or a write, and which surface is right. +## Connection-lifecycle errors + +The lifecycle uses four typed error families. Preserve their classes and original `cause`; C-2 +types are contracts, not prose to infer from a message: + +| Error | Meaning | +| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | +| `EntraSignInRequiredError` | Silent acquisition returned no session or the configured authentication provider changed; `reason` is `noSession` or `providerChanged`. | +| `EntraIdentityMismatchError` | Interactive acquisition returned a different Microsoft account from the pinned one. | +| `TokenCallbackError` | Any other OIDC callback throw for Microsoft Entra ID or managed identity. Its bounded `authMethod` records which one, and `cause` retains the original failure. | +| `ConnectionUnavailableError { reason }` | A bound client cannot be used. The reason is `signInRequired`, `credentialsRejected`, `credentialsMissing`, `credentialsUpdating`, `credentialsChanged`, `identityChanged`, `userDisconnected`, `connectionRemoved`, or `unreachable`. | + +Register `EntraSignInRequiredErrorExplainer` with provider id `entraSignInRequired` before the +general Entra explainer because the first explanation wins. That provider follows cyclic-safe +`cause` links and `MongoServerSelectionError.reason.servers[*].error`, and recognizes only the +typed sign-in-required and identity-mismatch errors. It explains those failures without exposing +private causes and asks the user to sign in with the original account when identities differ. + +Do not translate `ConnectionUnavailableError` through an infrastructure provider. The call site +knows whether the right response is a tree recovery action, a disabled webview dialog, or bounded +shell or playground output. Preserve the `reason`; webviews map it to **Retry** or **Close view**. + ## Adding a provider Implement `ErrorExplanationProvider` and register it in @@ -193,5 +215,6 @@ l10n.t('The container was removed outside VS Code.') - [errorExplanationService.ts](../../../src/services/errorExplanationService.ts) - [connectionReachabilityService.ts](../../../src/services/connectionReachabilityService.ts) prepares a connection _before_ connecting; this service explains a failure _afterwards_ +- [EntraSignInRequiredErrorExplainer.ts](../../../src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts) - [tree-cluster-architecture](../tree-cluster-architecture/SKILL.md) for `clusterId` versus `treeId` - [telemetry-instrumentation](../telemetry-instrumentation/SKILL.md) diff --git a/.github/skills/tree-cluster-architecture/SKILL.md b/.github/skills/tree-cluster-architecture/SKILL.md index fa8153e17..37642b9a4 100644 --- a/.github/skills/tree-cluster-architecture/SKILL.md +++ b/.github/skills/tree-cluster-architecture/SKILL.md @@ -63,6 +63,21 @@ Rules: - Never assume a stable ID is also a tree path unless the provider explicitly guarantees `clusterId === treeId`. - Never change tree construction without checking reverse lookup from `clusterId`. +## Connection Binding Contract + +A long-lived surface binds to `{ clusterId, fingerprint, generation }`, not to a `ClustersClient` +instance. Resolve the client for every operation through the binding with +`ClustersClient.resolveBoundClient()` or `runWithClient()`. Never retain a `ClustersClient` in view, +router, shell, playground, task, or clipboard state. + +- A new generation with the same fingerprint is a transparent same-connection replacement. +- A different fingerprint is an identity or settings change. Never rebind an existing surface. +- Check latches and the binding again at operation and async-reply boundaries. +- An operation may hold the resolved client only for the duration of that operation. A stale reply + must not mutate the new connection or replay a failed write. +- Shell and playground workers may keep their own connection, but pin the originating identity and + obey the same fingerprint and epoch checks when they respawn. + ## Design Rendering and Lookup Together When adding a cluster hierarchy or a tree/list mode, specify these four functions before coding: @@ -194,10 +209,19 @@ actions such as "Update credentials…" via `errorRecoveryActions` Keep a fixed relative order: configuration/targeted repairs, diagnosis/inspection, shell, destructive recovery, and **Retry always last** (including "Retry setup…"). -Providers prepend repairs; Update connection string precedes Update credentials when both exist. +Providers prepend repairs; **Update connection string** precedes **Update credentials** when both +exist. Then `ClusterItemBase` renders **Retry sign-in** when a verified Entra identity can recover, +followed by **Diagnose connection…** and **Open shell**. **Retry** is last. When **Retry sign-in** or +the stored-credential rejection action replaces Retry, do not add an ordinary Retry row too. Failure classification changes availability, never ordering. When healthy resources coexist with recovery actions, render the healthy resources first and the recovery block last. +A connected cluster's `TreeItem.contextValue` includes the `connected` tag while a client exists +and no lifecycle latch blocks it. Preserve the base context value and use this tag to gate +Disconnect. A user-disconnected cluster renders its single **Reconnect** action instead of database +children; Remove and rejected credentials use their own states and must not be exposed as +user-disconnected. + Do not add a child whose purpose is to show a message (an error label, a "sign-in required" row, a tooltip-only info node), even with an icon. Better wording belongs in the modal and in the Diagnose connection panel, not in the tree. @@ -210,6 +234,8 @@ Before approving a cluster tree change, answer yes to all: - [ ] Base cluster context tag is preserved. - [ ] `clusterId`, `treeId`, and `viewId` have documented owners. - [ ] Credentials and clients use `clusterId` only. +- [ ] Long-lived surfaces retain bindings, not `ClustersClient` instances. +- [ ] Per-operation resolution checks the fingerprint and generation. - [ ] Every rendered layout has a reverse lookup strategy. - [ ] Cluster and collection lookup share one resolver. - [ ] Synthetic ownership is exact and isolated from stored lookup. @@ -217,3 +243,5 @@ Before approving a cluster tree change, answer yes to all: - [ ] A real render-to-lookup round-trip test covers every layout. - [ ] Standard cluster commands work or are explicitly gated off. - [ ] Failures show a modal; tree children are recovery actions only, never error or info rows. +- [ ] Recovery actions keep provider repairs first, diagnosis and shell next, and Retry last. +- [ ] The `connected` context tag gates Disconnect and disappears while a lifecycle latch applies. diff --git a/CHANGELOG.md b/CHANGELOG.md index 699a9e3e8..756d5c6d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Change Log +## 1.2.0 (Unreleased) + +> Draft entries for an unpublished release. They may change before the release is finalized. + +### New Features & Improvements + +- **Resilient Connections**: Renews Microsoft Entra ID tokens silently, refreshes Azure discovery credentials, and replaces closed or transient failed clients with the same binding on a later foreground operation. [#990](https://github.com/microsoft/vscode-documentdb/issues/990), [#1102](https://github.com/microsoft/vscode-documentdb/issues/1102) +- **Explicit Connection Teardown**: Adds Disconnect and Reconnect, a shared disconnect and deletion flow, a Close all or Keep open (disabled) choice, and protection for active copy, export, or import work. [#566](https://github.com/microsoft/vscode-documentdb/issues/566), [#1059](https://github.com/microsoft/vscode-documentdb/issues/1059) +- **Identity-Bound Open Views**: Keeps open views and editor state tied to the connection that created them. Expired sign-in or unavailable connections receive bounded recovery, while changed saved settings require a new view instead of changing identity behind it. [#1102](https://github.com/microsoft/vscode-documentdb/issues/1102) + ## 1.1.0 ### New Features diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index a55a585c0..4a2bc3e23 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -6,13 +6,20 @@ created: 2026-11-19 code: - src/documentdb/ClustersClient.ts - src/documentdb/ClusterSession.ts + - src/documentdb/runWithClient.ts + - src/documentdb/connectionTeardown.ts - src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts + - src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts + - src/documentdb/shell/ShellSessionManager.ts + - src/documentdb/playground/PlaygroundEvaluator.ts - src/tree/documentdb/ClusterItemBase.ts + - src/webviews/components/DisconnectedOverlay.tsx --- # Connection lifecycle -**Status:** planned (iteration 1) · **Issues:** +**Status:** implemented in the feature branch; documentation draft ready; release and final +integration pending · **Issues:** - [#1102](https://github.com/microsoft/vscode-documentdb/issues/1102) - [#1059](https://github.com/microsoft/vscode-documentdb/issues/1059) @@ -41,6 +48,28 @@ defects: Evidence, telemetry and source pointers: [research-findings.md](./research-findings.md). +## Code map + +| Area | Primary implementation | +| ---------------------------------- | ----------------------------------------------------------------------------------------- | +| Client and binding lifecycle | `ClustersClient`, `ClusterSession`, `runWithClient` | +| Entra token renewal and errors | `MicrosoftEntraIDAuthHandler`, `entraSession`, `entraErrors/*`, `entraTokenFailures` | +| Shell and playground token relay | `ShellSessionManager`, `PlaygroundEvaluator`, `WorkerSessionManager`, `playgroundWorker` | +| Disconnect and removal | `connectionTeardown`, Disconnect command, connection and folder removal callers | +| Bound webviews and stale replies | `connectionSurfaces`, `DisconnectedOverlay`, bound-view routers and controllers | +| Tree recovery | `ClusterItemBase`, provider `errorRecoveryActions`, `showClusterConnectFailure` | +| Dashboard lifecycle polling | Cluster Dashboard controller, router and sampler | +| Measurement | established-connection lifecycle telemetry; the pending WI-9 operator volume/dashboard review | + +## WI-10 documentation choice + +The lifecycle manual stays in +[connecting-to-databases.md](../../../user-manual/connecting-to-databases.md) rather than adding a +separate page. The existing page already owns failed-connection recovery, so the continuation is +discoverable without another navigation level. The three requested workflow pages link to that +section. The operator chose no screenshots; no placeholders were added. Release notes and changelog +entries are unpublished drafts and do not represent a shipped release. + ## Intent - **Recover database connections silently** from token expiry and idle drops. For database @@ -111,3 +140,7 @@ See [decisions.md](./decisions.md): | 2026-11-18 | Investigation: code read, telemetry attribution, vscode-cosmosdb comparison | | 2026-11-19 | Operator decisions 0001–0005; implementation plan (iteration 1) | | 2026-11-19 | Decision 0006: delivery model (feature branch, sub-PRs, one release) | +| 2026-11-23 | WI-1 through WI-5 implement renewal, Azure auth, bindings and recovery | +| 2026-11-24 | WI-6 through WI-8 implement bound views, teardown and Dashboard behavior | +| 2026-11-25 | WI-2 review fixes and WI-9 lifecycle measurements | +| 2026-11-26 | WI-10 documentation draft, skill updates and unpublished 1.2.0 notes | diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index 6eeac6991..c1f03bd36 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -18,7 +18,7 @@ created: 2026-11-19 | 0004 | Disconnect lets the user choose: close all affected tabs, or keep them open and disabled | Accepted | Operator position; the default is still open (Q2) | 2026-11-19 | — | | 0005 | Fix stale ARM credentials by upgrading azureauth to v6 (#990), not with a local shim | Accepted | Operator: open to updating dependencies | 2026-11-19 | — | | 0006 | Deliver through `feature/connection-lifecycle` with stacked sub-PRs, ship once | Accepted (amended) | Operator removed the intermediate merge wait | 2026-11-19 | — | -| 0007 | The Disconnect choice is a VS Code modal with nothing remembered; a setting can set the default | Accepted | Operator: modal cannot pre-select; no remembering | 2026-11-19 | — | +| 0007 | The Disconnect choice is a VS Code modal with nothing remembered; a setting can set the default | Accepted (modified by 0018) | Operator: modal cannot pre-select; saved edits are close-only | 2026-11-19 | — | | 0008 | Upgrade the azext stack as high as viable without breaking workflows, using Azure Resources as reference | Accepted | Operator: replaces the "minimal versions" proposal | 2026-11-19 | — | | 0009 | Kubernetes tunnel recovery, cluster ID case handling and wider network-resilience testing move to #1105 | Accepted | Operator: keep 1.2.0 focused; schedule after release | 2026-11-19 | — | | 0010 | Rely on the server to reject expired tokens; replacing a client for the same identity is transparent | Accepted | Operator: no rotation, no out-of-date notices | 2026-11-19 | — | @@ -30,6 +30,7 @@ created: 2026-11-19 | 0016 | Keep disconnected webviews open under a full-view overlay | Accepted (modified by 0017) | Operator chose a simple disabled state with explicit actions | 2026-11-24 | Yes; replaces the inline banner and single-action layout | | 0017 | Limit unavailable webview recovery to Retry and Close view | Accepted (modified by 0018) | Operator wants credential repair in the tree and no extra recovery workflow in a tab | 2026-11-24 | Yes; removes in-view credential repair | | 0018 | Saved connection edits permanently lock existing views | Accepted | Operator prefers simple reconnect for unchanged settings over recovery after edits | 2026-11-24 | Yes; removes same-identity recovery after a saved edit | +| 0019 | Require a fresh Dashboard delete after Disconnect and keep Paste Collection in the tree | Accepted | Operator: a lifecycle change cancels the pending delete and never replays it | 2026-11-24 | — | > Entries below are **semantically** immutable: append new entries rather than rewriting old ones, > and record reversals as a new entry plus a status change above. Heading text is frozen once @@ -199,7 +200,9 @@ operator input on the dev plan's provisional answer A2. - The choice is **not remembered** between uses. - A setting lets users pick a default: `ask` (the default) shows the modal; `closeAll` or `keepOpenDisabled` skips it. The setting never skips the unsaved-edits confirmation. -- The choice applies to Disconnect, Remove Connection and credential updates that change identity. +- The choice applies to Disconnect and Remove Connection. Decision 0018 makes a saved identity or + settings edit close-only instead: existing views keep their contents but are not moved to the + new connection. Rejected: diff --git a/docs/index.md b/docs/index.md index 0a2f4ef79..278519f84 100644 --- a/docs/index.md +++ b/docs/index.md @@ -85,6 +85,7 @@ The User Manual provides guidance on using the extension. It contains detailed d Explore the history of updates and improvements to the extension. Each release brings new features, enhancements, and fixes to improve your experience. +- [1.2 (unpublished draft)](./release-notes/1.2) - [1.1](./release-notes/1.1) - [1.0](./release-notes/1.0), [1.0.1](./release-notes/1.0#patch-release-v101), [1.0.2](./release-notes/1.0#patch-release-v102) - [0.11](./release-notes/0.11), [0.11.1](./release-notes/0.11#patch-release-v0111), [0.11.2](./release-notes/0.11#patch-release-v0112) diff --git a/docs/release-notes/1.2.md b/docs/release-notes/1.2.md new file mode 100644 index 000000000..557e74de9 --- /dev/null +++ b/docs/release-notes/1.2.md @@ -0,0 +1,80 @@ +--- +title: 'v1.2' +parent: 'Release Notes' +nav_order: 1020 +--- + +# DocumentDB extension for Visual Studio Code v1.2 + +> **Unpublished draft:** this page describes planned 1.2.0 behavior for review. It is not a +> statement that version 1.2 has shipped, and the text may change before release. + +Version 1.2 is planned to make database connections survive routine token renewal and idle drops, +while keeping open views safe when credentials, identities, or connection settings change. It also +adds an explicit Disconnect workflow with clear choices for open tabs. + +## What's New in v1.2 (draft) + +### ⭐ Connections That Stay Usable + +Microsoft Entra ID token renewal is planned to remain silent during normal use. The extension keeps +the connection pinned to the account and tenant that established it, including in the Interactive +Shell and Query Playground. Closed clients and recoverable transient failures can be replaced on a +later foreground operation without restarting VS Code. + +When silent sign-in is no longer possible, the extension asks for an explicit action at the surface +where work is happening. The tree offers **Retry sign-in**, while the shell and playground can offer +**Sign in again**. The operation never moves an existing session to a different Microsoft account. + +Azure discovery also renews its Azure Resource Manager credentials rather than retaining a frozen +token from an earlier provider tree. This work addresses +[#990](https://github.com/microsoft/vscode-documentdb/issues/990) and +[#1102](https://github.com/microsoft/vscode-documentdb/issues/1102). + +See [Keep connections usable](https://microsoft.github.io/vscode-documentdb/user-manual/connecting-to-databases#keep-connections-usable). + +### ⭐ Disconnect, Reconnect, and Keep Your Place + +Connected clusters gain a **Disconnect** action. Before ending live work, the extension asks what to +do with open view tabs: **Close all** or **Keep open (disabled)**. A setting can choose either +behavior in advance, while unsaved document changes still require explicit confirmation. + +Retained Collection View, Document View, and Cluster Dashboard contents stay available for +inspection or copying under a connection dialog. **Reconnect** can resume the existing Dashboard for +the same connection. Other retained webviews require **Retry** after reconnecting. Use **Close +view** when the connection changed or was removed. Retry does not replay the operation that failed. + +Disconnect waits when a tracked copy, export, or import is using the cluster. The same teardown +rules apply when a saved connection is deleted, with the additional step of removing its saved +connection and cached credentials. See +[#566](https://github.com/microsoft/vscode-documentdb/issues/566) and +[#1059](https://github.com/microsoft/vscode-documentdb/issues/1059). + +Learn how retained views, shells, and playgrounds resume in the +[connection lifecycle guide](https://microsoft.github.io/vscode-documentdb/user-manual/connecting-to-databases#disconnect-and-reconnect). + +### ⭐ Open Work Stays Bound to Its Original Connection + +Collection View, Document View, the Cluster Dashboard, Interactive Shell, and Query Playground do +not silently switch to new credentials or a different identity. A save with **Update Credentials…** +or **Update Connection String…**, including a password-only change, permanently locks existing +views in the current VS Code window. Their contents remain available for copying, and new work +starts by opening a new view from the tree. + +Same-identity client replacement remains transparent. A different identity, removed connection, or +changed saved settings never inherits an old view's draft or permissions. + +## Key Limits and Improvements + +- **No replay of uncertain writes.** Reconnecting or clicking Retry never resubmits the failed + operation. Check the server before repeating a write that did not report an outcome. +- **Shells and playgrounds keep bounded state.** Disconnect stops their worker connections. Open a + new shell, or re-pick a playground connection, after reconnecting. +- **Follow-up network work is outside this release.** Kubernetes tunnel recreation and broader + network resilience remain tracked in + [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105). + +## Changelog + +See the unpublished draft entry for this release: +[CHANGELOG.md#120](https://github.com/microsoft/vscode-documentdb/blob/main/CHANGELOG.md#120-unreleased) diff --git a/docs/user-manual/connecting-to-databases.md b/docs/user-manual/connecting-to-databases.md index 64811b8cf..00dea4366 100644 --- a/docs/user-manual/connecting-to-databases.md +++ b/docs/user-manual/connecting-to-databases.md @@ -26,3 +26,60 @@ The actions available depend on the connection and the failure: Retry is always last. These shorter labels apply to the recovery rows under a failed cluster; context-menu and Command Palette titles can differ. + +## Keep connections usable + +The extension normally recovers from an expired Microsoft Entra ID token or an idle connection +without restarting VS Code. Silent recovery uses the account and tenant that established the +connection. It does not open a sign-in prompt from a background refresh. + +If Microsoft sign-in can no longer be renewed, the tree offers **Retry sign-in**. The Interactive +Shell and Query Playground can instead offer **Sign in again**. Sign in with the identity originally +used for that connection. The old view is not moved to a different account. + +## Disconnect and reconnect + +Right-click a connected cluster and select **Disconnect** to end its live connections. If a copy, +export, or import is using the cluster, the operation continues and Disconnect is blocked until that +task finishes or you stop it. + +When open connection views exist and the setting `documentDB.connections.openTabsOnDisconnect` is +`ask`, the **Disconnect?** modal offers: + +- **Close all**, which closes open connection views. Closing a dirty Document View first asks + whether to **Discard changes**. +- **Keep open (disabled)**, which keeps view contents but prevents database operations. + +This choice applies to Collection View, Document View, and Cluster Dashboard tabs. It does not close +the Interactive Shell terminal or the Query Playground file; Disconnect stops their database +workers. + +The setting can use `closeAll` or `keepOpenDisabled` as a default instead of showing the choice each +time. It never bypasses the unsaved-document confirmation. **Delete Connection…** uses the same +choice, but also removes the saved connection and its cached credentials. + +A retained Collection View, Document View, or Cluster Dashboard is covered by a dialog that explains +why it is unavailable: + +- Select **Retry** after repairing or reconnecting the connection. Retry checks the binding and + does not replay the operation that failed. +- Select **Close view** to close the tab. A dirty Document View warns before closing. +- Use the **X** to dismiss the dialog when you need to copy from the view. Database operations stay + disabled, and the next operation shows the dialog again. + +Use the cluster's **Reconnect** action in the tree to restore the same connection. The Dashboard can +resume after that reconnect; other retained webviews require **Retry**. An Interactive Shell prints +**Disconnected** and stops its worker, then requires a new shell from the tree. A retained Query +Playground requires you to reconnect and re-pick its connection before running it again. + +## After changing connection details + +Saving a change with **Update Credentials…** or **Update Connection String…** keeps the old view's +contents available for inspection or copying, but the saved change permanently locks that existing +view in this VS Code window. This includes a password-only edit. The dialog offers **Close view**; +open a new view from the tree to use the saved settings. + +The same rule applies to an Interactive Shell or Query Playground bound to the previous settings: +do not continue by switching identities inside the old session. Open a new shell or re-pick the +playground connection from the tree. Cancelling an edit, or saving without changing stored details, +does not lock existing sessions. diff --git a/docs/user-manual/interactive-shell.md b/docs/user-manual/interactive-shell.md index 09ca684ab..cbb8ffcca 100644 --- a/docs/user-manual/interactive-shell.md +++ b/docs/user-manual/interactive-shell.md @@ -54,6 +54,9 @@ Type "help" for available commands. myDatabase> ``` +For token renewal, Microsoft sign-in recovery, Disconnect, and the limits of reusing an existing +shell after a connection change, see [Keep connections usable](./connecting-to-databases#keep-connections-usable). + ## Shell Commands The following built-in commands are available at the prompt: @@ -250,4 +253,4 @@ The help output also prints the full Settings search query for manual access. --- -> **Related**: [Query Playground](./query-playground) | [How It Works Behind the Scenes](./query-runtime) +> **Related**: [Query Playground](./query-playground) | [Connection lifecycle](./connecting-to-databases#keep-connections-usable) | [How It Works Behind the Scenes](./query-runtime) diff --git a/docs/user-manual/managing-azure-discovery.md b/docs/user-manual/managing-azure-discovery.md index d5c574d46..16d9d9214 100644 --- a/docs/user-manual/managing-azure-discovery.md +++ b/docs/user-manual/managing-azure-discovery.md @@ -178,3 +178,4 @@ When adding a new connection via the **"Add New Connection"** wizard: - [Azure Cosmos DB for MongoDB (RU) Service Discovery](./service-discovery-azure-cosmosdb-for-mongodb-ru) - [Azure DocumentDB Service Discovery](./service-discovery-azure-cosmosdb-for-mongodb-vcore) - [Azure VMs (DocumentDB) Service Discovery](./service-discovery-azure-vms) +- [Connection lifecycle, sign-in renewal, and teardown](./connecting-to-databases#keep-connections-usable) diff --git a/docs/user-manual/query-playground.md b/docs/user-manual/query-playground.md index a5bd3c7d4..de20d9cbd 100644 --- a/docs/user-manual/query-playground.md +++ b/docs/user-manual/query-playground.md @@ -38,6 +38,8 @@ There are several ways to open a new Query Playground: The three inline icons next to each collection node are (from left to right): Open Collection View, **New Query Playground**, and Open Interactive Shell. When a playground opens, a CodeLens header at the top displays the connection status, showing which cluster and database the file is connected to. +If the connection expires or is disconnected, see [Keep connections usable](./connecting-to-databases#keep-connections-usable) +for the exact sign-in and reconnect behavior. ## Writing Queries @@ -206,4 +208,4 @@ or use `.maxTimeMS()` on a supported query to set a server-side limit. --- -> **Related**: [Interactive Shell](./interactive-shell) | [How It Works Behind the Scenes](./query-runtime) +> **Related**: [Interactive Shell](./interactive-shell) | [Connection lifecycle](./connecting-to-databases#keep-connections-usable) | [How It Works Behind the Scenes](./query-runtime) From 668ead86ad298a629594a553c0595c125fa6ef43 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 06:52:38 +0000 Subject: [PATCH 03/15] docs: record lifecycle docs preview and pending ingestion Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 21acee7d1..990625223 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1876,7 +1876,8 @@ one loop. follows the published client; worker eligibility is captured when the ready or executing worker requests the token. Neither uses the first callback as a startup proxy. - Case 1 passed: `npm run build` and 349 focused tests in 8 files. Ingestion is **pending**; the - [telemetry queries](../telemetry.md) and dashboard scope/volume checks are for the operator. + [telemetry queries](../telemetry.md) are ready to run. The dashboard worktree has unrelated + changes in progress and was left untouched. --- @@ -1902,6 +1903,11 @@ one loop. **Progress:** +- The operator chose text-only 1.2.0 release notes. The user manual extends + `connecting-to-databases.md` rather than adding a second page. +- The local GitHub Pages build rendered the manual and draft release notes. The three + manual links and the release index link resolve, and the internal feature docs stay excluded. + --- ## PR F: `feature/connection-lifecycle` → `main` @@ -1926,4 +1932,5 @@ one loop. # Outcome -_To be written at hand-over._ +- **WI-9 telemetry: pending ingestion.** Run the [feature queries](../telemetry.md) on + pre-release data before CP-5. Record the packaged operator validation here at OP-6. From c785240ab2be33d13901eb21f174c09b4c2eb9d8 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 07:04:48 +0000 Subject: [PATCH 04/15] docs: record PR7 pre-review findings for author decisions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../01-pr7-telemetry-and-docs-review.md | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md new file mode 100644 index 000000000..55fbe1113 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md @@ -0,0 +1,59 @@ +# PR7 pre-review: Connection recovery telemetry and docs + +[PR #1135](https://github.com/microsoft/vscode-documentdb/pull/1135) · WI-9 and WI-10 · reviewed head `668ead86a` + +Claude Opus 5.5 performed the first pass. OpenAI GPT-6.2-Sol independently validated the +findings and added two. That run used long context; the standard-context verification +required by CONTRIBUTING §6.1 remains open. There were no Copilot threads when checked. +Neither reviewer found a runtime issue in the bounded renewal emitter. Neither ran the +queries against live data. + +## F1. The baseline can show a false drop in classified failures (high for WI-9) + +The [before/after query](../telemetry.md#comparable-late-failures-before-and-after-release) +uses error fields that the new tree `connect` path masks but the baseline did not. The +same failure can move to the unclassified bucket without any change in its frequency. +Tree expansion can also return recovery actions as a normal result. + +**Recommendation:** Compare only stable RPC procedures and versions that share the same +`causeType` scheme, with the same exposure rules for both cohorts. Keep unclassified +counts visible and label tree data as descriptive, not comparable. If no comparable +cohort has enough exposure, report insufficient evidence. Do not change runtime +telemetry or relax redaction. + +**Author decision:** Pending. + +## F2. Disconnect does not wait behind an active task (medium) + +The [release notes](../../../../release-notes/1.2.md) say Disconnect waits, and the +[manual](../../../../user-manual/connecting-to-databases.md#disconnect-and-reconnect) +does not explicitly tell the user to retry. The command refuses teardown and leaves +both the task and the connection running. + +**Recommendation:** State in both pages that the user must try Disconnect again after +the task finishes or is stopped. No command change. + +**Author decision:** Pending. + +## F3. Recovery rows can inflate replacement success counts (medium) + +The [replacement query](../telemetry.md) excludes cached failures, but a first failed +tree expansion can return recovery rows while its event still reports success. It can +already carry the replacement generation at that point. + +**Recommendation:** Exclude both first-time and cached recovery rows. Count confirmed +recovery only for operations whose success indicates that database work succeeded. + +**Author decision:** Pending. + +## F4. A retained Dashboard can still require Retry (medium) + +The [manual](../../../../user-manual/connecting-to-databases.md#disconnect-and-reconnect) +and [release notes](../../../../release-notes/1.2.md) imply that only other views need +Retry. The Dashboard retries automatically only if reconnect opens the already +bound panel. Auto-open can be disabled. + +**Recommendation:** Describe the conditional automatic retry and tell users to select +**Retry** if the Dashboard stays disabled. No behavior change. + +**Author decision:** Pending. From fe91067a8058a8ff01caa849182f0636e7e3aaca Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 11:24:25 +0000 Subject: [PATCH 05/15] docs: compare only stable RPC failure signatures and count verified expansions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/telemetry.md | 59 +++++++++++-------- 1 file changed, 34 insertions(+), 25 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/telemetry.md b/docs/ai-and-plans/features/connection-lifecycle/telemetry.md index fc43cb78a..cea396b73 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/telemetry.md +++ b/docs/ai-and-plans/features/connection-lifecycle/telemetry.md @@ -15,7 +15,7 @@ for the two cohorts. Use equal, complete UTC windows, with a gap if the rollout let ReleaseAt = startofday(ago(7d)); // Replace with rollout boundary for this comparison. let Window = 7d; let RolloutGap = 0d; -let BaselineVersion = "1.1.1"; +let BaselineVersion = "1.1.0"; let ReleaseVersion = "1.2.0"; let BeforeEnd = ReleaseAt - RolloutGap; let AfterStart = ReleaseAt + RolloutGap; @@ -35,13 +35,12 @@ let Events = let Operations = Events | where inWindow + | extend parentContext = tostring(customDimensions.parentNodeContext) | extend family = case( eventScope == "connect", "connect", eventScope startswith "documentdb.rpc.", "rpc", (eventScope == "getchildren" or eventScope endswith ".getchildren") - and isnotempty(tostring(customDimensions.parentNodeContext)) - and tostring(customDimensions.parentNodeContext) !~ "root" - and tostring(customDimensions.usedCachedErrorNode) !~ "true", "getchildren", + and isnotempty(parentContext) and parentContext !~ "root", "getchildren", "") | where isnotempty(family) | extend connectionResult = tolower(tostring(customDimensions.connectionResult)) @@ -53,15 +52,16 @@ let Operations = | extend ageMs = todouble(customMeasurements.connectionAgeMs), generation = tolong(customMeasurements.clientGeneration), failureKind = tostring(customDimensions.connectionFailureKind), - failureType = coalesce(tostring(customDimensions.causeType), tostring(customDimensions.error)), - failureMessage = tostring(customDimensions.errorMessage) + failureType = tostring(customDimensions.causeType), + recoveryRows = tostring(customDimensions.usedCachedErrorNode) =~ "true" + or tostring(customDimensions.cachedErrorNode) =~ "true" | extend signature = case( operationResult != "failed", "", + family != "rpc", "notClassified", failureType in~ ("18", "391", "AuthenticationFailed", "Unauthorized", "EntraSignInRequiredError", "EntraIdentityMismatchError"), "auth", failureType in~ ("MongoNotConnectedError", "MongoTopologyClosedError"), "closedClient", - failureType in~ ("MongoNetworkError", "MongoNetworkTimeoutError", "ECONNRESET", "EPIPE") - or failureMessage matches regex @"(?i)\bconnection \d+ to .+ closed\b", "socket", + failureType in~ ("MongoNetworkError", "MongoNetworkTimeoutError", "ECONNRESET", "EPIPE"), "socket", "otherOrUnclassified"); ``` @@ -94,10 +94,11 @@ surface to check the observed volume against the telemetry budget. No lookups me ## Post-release outcomes by client age and generation -Successes on generation 2 or above show the replacement served an operation; they are not a count -of unique recoveries or proof that renewal triggered recovery. Show missing age and generation -explicitly: not every operation has a published client to report. `transient` is broader than -socket failures, so this drilldown keeps the lifecycle kind and the comparable signature separate. +The replacement count uses successful cluster expansions that did not return first-time or +cached recovery rows. Other operations are shown for context only: for example, an RPC can +return a typed unavailable result without reporting an SDK failure. The count is neither +unique recoveries nor proof that renewal triggered them. Not every operation reports client +age or generation; show missing values explicitly. ```kusto Operations @@ -108,20 +109,25 @@ Operations generationBand = case(isnull(generation) or generation < 1, "(missing)", generation == 1, "1", "2+"), lifecycleKind = coalesce(failureKind, "(missing)") | summarize operations = count(), - successfulOnReplacement = countif(operationResult == "succeeded" and generation >= 2) + successfulClusterExpansionsOnReplacement = countif( + family == "getchildren" and tolower(parentContext) matches regex @"\btreeitem_documentdbcluster\b" + and operationResult == "succeeded" and generation >= 2 and not(recoveryRows)) by version, family, ageBand, generationBand, operationResult, lifecycleKind, signature | order by family asc, ageBand asc, generationBand asc ``` ## Comparable late failures before and after release -The baseline lacks client age and generation. Use the **same exposure on both versions**: recorded -non-canceled operations at least one hour after the most recent preceding successful database -startup in a VS Code session whose successful startups all used Entra ID. Only existing session -metadata is used for this historical attribution; no session key or raw failure data is returned. -The warmup is the same on both sides. This is a session-age proxy, not a per-client age or a causal -estimate. It can miss sparse telemetry, mixed-auth sessions, and versions that don't report the -same failure signatures. Do not mix new lifecycle-only classifications into the comparison. +The baseline lacks client age and generation. Compare the same database RPC scopes in versions +that report the same `causeType` scheme. Do not use tree `connect` or expansion counts for this +comparison: their redaction and reporting of failures as recovery rows make the cohorts +incomparable. These are rates of reported RPC failure signatures, not all database failures. + +Use the **same exposure on both versions**: recorded non-canceled calls to each selected +procedure at least one hour after the most recent preceding successful database startup in a +VS Code session whose successful startups all used Entra ID. Only existing session metadata +is used; no session key or raw failure data is returned. The warmup is identical for both cohorts. +This is a session-age proxy, not per-client age or a causal estimate. ```kusto let Startups = materialize( @@ -140,10 +146,12 @@ let EntraSessions = | project cohort, version, sessionKey; Operations | where operationResult in ("succeeded", "failed") +| where eventScope in ("documentdb.rpc.query.mongoclusters.collectionview.runfindquery", + "documentdb.rpc.query.mongoclusters.documentview.getdocumentbyid") | extend sessionKey = coalesce(tostring(customDimensions.VSCodeSessionId), tostring(customDimensions["common.vscodesessionid"])) | where isnotempty(sessionKey) -| project cohort, version, sessionKey, timestamp, family, operationResult, signature +| project cohort, version, sessionKey, timestamp, eventScope, operationResult, signature | serialize operationRow = row_number() | join kind=inner (Startups | join kind=leftsemi (EntraSessions) on cohort, version, sessionKey) on cohort, version, sessionKey @@ -156,15 +164,16 @@ Operations lateSocket = countif(signature == "socket"), lateClosedClient = countif(signature == "closedClient"), otherOrUnclassified = countif(signature == "otherOrUnclassified") - by cohort, version, family + by cohort, version, eventScope | extend authPer1000 = 1000.0 * lateAuth / exposureOperations, socketPer1000 = 1000.0 * lateSocket / exposureOperations, closedClientPer1000 = 1000.0 * lateClosedClient / exposureOperations -| order by family asc, cohort asc +| order by eventScope asc, cohort asc ``` -Compare like families and inspect counts along with rates. A missing cohort/family or no later -operations is insufficient exposure, not a zero failure rate. +Compare the same procedure across cohorts and inspect counts, including unclassified failures, +alongside rates. Missing exposure, or cohorts without comparable signatures, are insufficient +evidence, not zero failures. ## ARM challenge versus final operation result From f7607d0396835a372d259544b95f0a329bb80a91 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 11:24:25 +0000 Subject: [PATCH 06/15] docs: clarify when Disconnect and Dashboard recovery need another action Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/release-notes/1.2.md | 14 ++++++++------ docs/user-manual/connecting-to-databases.md | 9 +++++---- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/docs/release-notes/1.2.md b/docs/release-notes/1.2.md index 557e74de9..5f11b45f8 100644 --- a/docs/release-notes/1.2.md +++ b/docs/release-notes/1.2.md @@ -40,12 +40,14 @@ do with open view tabs: **Close all** or **Keep open (disabled)**. A setting can behavior in advance, while unsaved document changes still require explicit confirmation. Retained Collection View, Document View, and Cluster Dashboard contents stay available for -inspection or copying under a connection dialog. **Reconnect** can resume the existing Dashboard for -the same connection. Other retained webviews require **Retry** after reconnecting. Use **Close -view** when the connection changed or was removed. Retry does not replay the operation that failed. - -Disconnect waits when a tracked copy, export, or import is using the cluster. The same teardown -rules apply when a saved connection is deleted, with the additional step of removing its saved +inspection or copying under a connection dialog. If **Reconnect** automatically opens the retained +Dashboard for the same connection, the Dashboard retries on its own. If it stays disabled, select +**Retry**, as you would in other retained webviews. Use **Close view** when the connection changed or +was removed. Retry does not replay the operation that failed. + +If a tracked copy, export, or import is using the cluster, the task and connection keep running. +Select **Disconnect** again after the task finishes or you stop it. The same teardown rules apply +when a saved connection is deleted, with the additional step of removing its saved connection and cached credentials. See [#566](https://github.com/microsoft/vscode-documentdb/issues/566) and [#1059](https://github.com/microsoft/vscode-documentdb/issues/1059). diff --git a/docs/user-manual/connecting-to-databases.md b/docs/user-manual/connecting-to-databases.md index 00dea4366..48ee537f8 100644 --- a/docs/user-manual/connecting-to-databases.md +++ b/docs/user-manual/connecting-to-databases.md @@ -40,8 +40,8 @@ used for that connection. The old view is not moved to a different account. ## Disconnect and reconnect Right-click a connected cluster and select **Disconnect** to end its live connections. If a copy, -export, or import is using the cluster, the operation continues and Disconnect is blocked until that -task finishes or you stop it. +export, or import is using the cluster, both the task and connection keep running. Select +**Disconnect** again after the task finishes or you stop it. When open connection views exist and the setting `documentDB.connections.openTabsOnDisconnect` is `ask`, the **Disconnect?** modal offers: @@ -67,8 +67,9 @@ why it is unavailable: - Use the **X** to dismiss the dialog when you need to copy from the view. Database operations stay disabled, and the next operation shows the dialog again. -Use the cluster's **Reconnect** action in the tree to restore the same connection. The Dashboard can -resume after that reconnect; other retained webviews require **Retry**. An Interactive Shell prints +Use the cluster's **Reconnect** action in the tree to restore the same connection. If reconnect +automatically opens the retained Dashboard for that connection, it retries on its own. If it +stays disabled, select **Retry**, as you would in other retained webviews. An Interactive Shell prints **Disconnected** and stops its worker, then requires a new shell from the tree. A retained Query Playground requires you to reconnect and re-pick its connection before running it again. From 9a4d23aeeb3e67becdb564be23494fbef88b0364 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 11:32:23 +0000 Subject: [PATCH 07/15] docs: record PR7 review fixes and handoff validation status Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../01-pr7-telemetry-and-docs-review.md | 36 ++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md index 55fbe1113..12410ca3d 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md @@ -21,7 +21,12 @@ counts visible and label tree data as descriptive, not comparable. If no compara cohort has enough exposure, report insufficient evidence. Do not change runtime telemetry or relax redaction. -**Author decision:** Pending. +**Author decision:** Approved as recommended. Limit the rate comparison to stable RPC +scopes; do not add a telemetry field or change redaction. + +**Fixed:** [`fe91067a8`](https://github.com/microsoft/vscode-documentdb/commit/fe91067a8) +limits the classified comparison to two database RPCs and uses `causeType` alone. Tree +events stay descriptive, and unclassified failures remain visible. ## F2. Disconnect does not wait behind an active task (medium) @@ -33,7 +38,10 @@ both the task and the connection running. **Recommendation:** State in both pages that the user must try Disconnect again after the task finishes or is stopped. No command change. -**Author decision:** Pending. +**Author decision:** Approved as recommended. Clarify that the user must retry Disconnect. + +**Fixed:** [`f7607d039`](https://github.com/microsoft/vscode-documentdb/commit/f7607d039) +explains in both pages that the task and connection keep running and the user must retry. ## F3. Recovery rows can inflate replacement success counts (medium) @@ -44,7 +52,12 @@ already carry the replacement generation at that point. **Recommendation:** Exclude both first-time and cached recovery rows. Count confirmed recovery only for operations whose success indicates that database work succeeded. -**Author decision:** Pending. +**Author decision:** Approved as recommended. Do not count first-time or cached recovery +rows as successful replacement operations. + +**Fixed:** [`fe91067a8`](https://github.com/microsoft/vscode-documentdb/commit/fe91067a8) +counts only successful cluster expansions on a replacement generation, excluding both +first-time and cached recovery rows. ## F4. A retained Dashboard can still require Retry (medium) @@ -56,4 +69,19 @@ bound panel. Auto-open can be disabled. **Recommendation:** Describe the conditional automatic retry and tell users to select **Retry** if the Dashboard stays disabled. No behavior change. -**Author decision:** Pending. +**Author decision:** Approved as recommended. Clarify when a retained Dashboard still +needs Retry. + +**Fixed:** [`f7607d039`](https://github.com/microsoft/vscode-documentdb/commit/f7607d039) +explains that the existing Dashboard retries automatically only when Reconnect opens it. +If it stays disabled, select **Retry**. + +## Remaining handoff requirements + +A second validation attempt could not verify its context tier or vendor and did not +review the changes. PR7 remains in draft until standard-context validation is confirmed. +Live query and ingestion verification remains pending for CP-5. + +Local Case 2 passed: formatting, localization check, lint, build, strict workspace +test type-checking, 9,963 tests across 444 suites (one skipped), and VSIX packaging. +No localization strings changed in PR7. From 276adffb0e7e528d73f8857c2eaa91de659d901e Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 11:32:23 +0000 Subject: [PATCH 08/15] style: format PR7 for handoff Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/skills/error-translation/SKILL.md | 10 +- .../features/connection-lifecycle/README.md | 24 +-- .../connection-lifecycle/decisions.md | 4 +- src/commands/signInAgain/signInAgain.test.ts | 5 +- src/documentdb/ClustersClient.test.ts | 20 +- .../playground/PlaygroundEvaluator.ts | 9 +- .../playground/WorkerSessionManager.test.ts | 188 ++++++++++-------- 7 files changed, 157 insertions(+), 103 deletions(-) diff --git a/.github/skills/error-translation/SKILL.md b/.github/skills/error-translation/SKILL.md index 279e17a8e..66577d14e 100644 --- a/.github/skills/error-translation/SKILL.md +++ b/.github/skills/error-translation/SKILL.md @@ -33,11 +33,11 @@ watching, whether the operation was a read or a write, and which surface is righ The lifecycle uses four typed error families. Preserve their classes and original `cause`; C-2 types are contracts, not prose to infer from a message: -| Error | Meaning | -| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | -| `EntraSignInRequiredError` | Silent acquisition returned no session or the configured authentication provider changed; `reason` is `noSession` or `providerChanged`. | -| `EntraIdentityMismatchError` | Interactive acquisition returned a different Microsoft account from the pinned one. | -| `TokenCallbackError` | Any other OIDC callback throw for Microsoft Entra ID or managed identity. Its bounded `authMethod` records which one, and `cause` retains the original failure. | +| Error | Meaning | +| --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `EntraSignInRequiredError` | Silent acquisition returned no session or the configured authentication provider changed; `reason` is `noSession` or `providerChanged`. | +| `EntraIdentityMismatchError` | Interactive acquisition returned a different Microsoft account from the pinned one. | +| `TokenCallbackError` | Any other OIDC callback throw for Microsoft Entra ID or managed identity. Its bounded `authMethod` records which one, and `cause` retains the original failure. | | `ConnectionUnavailableError { reason }` | A bound client cannot be used. The reason is `signInRequired`, `credentialsRejected`, `credentialsMissing`, `credentialsUpdating`, `credentialsChanged`, `identityChanged`, `userDisconnected`, `connectionRemoved`, or `unreachable`. | Register `EntraSignInRequiredErrorExplainer` with provider id `entraSignInRequired` before the diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 4a2bc3e23..b2618eaa9 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -50,16 +50,16 @@ Evidence, telemetry and source pointers: [research-findings.md](./research-findi ## Code map -| Area | Primary implementation | -| ---------------------------------- | ----------------------------------------------------------------------------------------- | -| Client and binding lifecycle | `ClustersClient`, `ClusterSession`, `runWithClient` | -| Entra token renewal and errors | `MicrosoftEntraIDAuthHandler`, `entraSession`, `entraErrors/*`, `entraTokenFailures` | -| Shell and playground token relay | `ShellSessionManager`, `PlaygroundEvaluator`, `WorkerSessionManager`, `playgroundWorker` | -| Disconnect and removal | `connectionTeardown`, Disconnect command, connection and folder removal callers | -| Bound webviews and stale replies | `connectionSurfaces`, `DisconnectedOverlay`, bound-view routers and controllers | -| Tree recovery | `ClusterItemBase`, provider `errorRecoveryActions`, `showClusterConnectFailure` | -| Dashboard lifecycle polling | Cluster Dashboard controller, router and sampler | -| Measurement | established-connection lifecycle telemetry; the pending WI-9 operator volume/dashboard review | +| Area | Primary implementation | +| -------------------------------- | --------------------------------------------------------------------------------------------- | +| Client and binding lifecycle | `ClustersClient`, `ClusterSession`, `runWithClient` | +| Entra token renewal and errors | `MicrosoftEntraIDAuthHandler`, `entraSession`, `entraErrors/*`, `entraTokenFailures` | +| Shell and playground token relay | `ShellSessionManager`, `PlaygroundEvaluator`, `WorkerSessionManager`, `playgroundWorker` | +| Disconnect and removal | `connectionTeardown`, Disconnect command, connection and folder removal callers | +| Bound webviews and stale replies | `connectionSurfaces`, `DisconnectedOverlay`, bound-view routers and controllers | +| Tree recovery | `ClusterItemBase`, provider `errorRecoveryActions`, `showClusterConnectFailure` | +| Dashboard lifecycle polling | Cluster Dashboard controller, router and sampler | +| Measurement | established-connection lifecycle telemetry; the pending WI-9 operator volume/dashboard review | ## WI-10 documentation choice @@ -141,6 +141,6 @@ See [decisions.md](./decisions.md): | 2026-11-19 | Operator decisions 0001–0005; implementation plan (iteration 1) | | 2026-11-19 | Decision 0006: delivery model (feature branch, sub-PRs, one release) | | 2026-11-23 | WI-1 through WI-5 implement renewal, Azure auth, bindings and recovery | -| 2026-11-24 | WI-6 through WI-8 implement bound views, teardown and Dashboard behavior | -| 2026-11-25 | WI-2 review fixes and WI-9 lifecycle measurements | +| 2026-11-24 | WI-6 through WI-8 implement bound views, teardown and Dashboard behavior | +| 2026-11-25 | WI-2 review fixes and WI-9 lifecycle measurements | | 2026-11-26 | WI-10 documentation draft, skill updates and unpublished 1.2.0 notes | diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index c1f03bd36..7f094b03e 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -18,7 +18,7 @@ created: 2026-11-19 | 0004 | Disconnect lets the user choose: close all affected tabs, or keep them open and disabled | Accepted | Operator position; the default is still open (Q2) | 2026-11-19 | — | | 0005 | Fix stale ARM credentials by upgrading azureauth to v6 (#990), not with a local shim | Accepted | Operator: open to updating dependencies | 2026-11-19 | — | | 0006 | Deliver through `feature/connection-lifecycle` with stacked sub-PRs, ship once | Accepted (amended) | Operator removed the intermediate merge wait | 2026-11-19 | — | -| 0007 | The Disconnect choice is a VS Code modal with nothing remembered; a setting can set the default | Accepted (modified by 0018) | Operator: modal cannot pre-select; saved edits are close-only | 2026-11-19 | — | +| 0007 | The Disconnect choice is a VS Code modal with nothing remembered; a setting can set the default | Accepted (modified by 0018) | Operator: modal cannot pre-select; saved edits are close-only | 2026-11-19 | — | | 0008 | Upgrade the azext stack as high as viable without breaking workflows, using Azure Resources as reference | Accepted | Operator: replaces the "minimal versions" proposal | 2026-11-19 | — | | 0009 | Kubernetes tunnel recovery, cluster ID case handling and wider network-resilience testing move to #1105 | Accepted | Operator: keep 1.2.0 focused; schedule after release | 2026-11-19 | — | | 0010 | Rely on the server to reject expired tokens; replacing a client for the same identity is transparent | Accepted | Operator: no rotation, no out-of-date notices | 2026-11-19 | — | @@ -30,7 +30,7 @@ created: 2026-11-19 | 0016 | Keep disconnected webviews open under a full-view overlay | Accepted (modified by 0017) | Operator chose a simple disabled state with explicit actions | 2026-11-24 | Yes; replaces the inline banner and single-action layout | | 0017 | Limit unavailable webview recovery to Retry and Close view | Accepted (modified by 0018) | Operator wants credential repair in the tree and no extra recovery workflow in a tab | 2026-11-24 | Yes; removes in-view credential repair | | 0018 | Saved connection edits permanently lock existing views | Accepted | Operator prefers simple reconnect for unchanged settings over recovery after edits | 2026-11-24 | Yes; removes same-identity recovery after a saved edit | -| 0019 | Require a fresh Dashboard delete after Disconnect and keep Paste Collection in the tree | Accepted | Operator: a lifecycle change cancels the pending delete and never replays it | 2026-11-24 | — | +| 0019 | Require a fresh Dashboard delete after Disconnect and keep Paste Collection in the tree | Accepted | Operator: a lifecycle change cancels the pending delete and never replays it | 2026-11-24 | — | > Entries below are **semantically** immutable: append new entries rather than rewriting old ones, > and record reversals as a new entry plus a status change above. Heading text is frozen once diff --git a/src/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts index f61fbfde9..0afc0eaf6 100644 --- a/src/commands/signInAgain/signInAgain.test.ts +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -26,7 +26,10 @@ const pin = { tenantId: 'tenant', } as const; const clusterId = 'cluster'; -const mocks = vi.hoisted(() => ({ configureAuth: vi.fn(), capturePolicy: vi.fn<(policy: AuthCallerPolicy) => void>() })); +const mocks = vi.hoisted(() => ({ + configureAuth: vi.fn(), + capturePolicy: vi.fn<(policy: AuthCallerPolicy) => void>(), +})); vi.mock('../../documentdb/ClustersClient', () => ({ addEstablishedConnectionContext: vi.fn(), diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 474e4a600..c9f20b9c7 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -1463,10 +1463,16 @@ describe('regular connection startup diagnostics', () => { ); vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockImplementation(configureEntraAuth); vi.spyOn(tokenResource, 'resolveInteractiveTokenResource').mockResolvedValue({ - cloudCategory: 'public', reason: 'host', scope: 'test-scope', resource: 'test-resource', details: {}, + cloudCategory: 'public', + reason: 'host', + scope: 'test-scope', + resource: 'test-resource', + details: {}, }); vi.spyOn(entraSession, 'readEntraSignInEnvironment').mockReturnValue({ - providerId: 'microsoft', cloudName: 'AzureCloud', authority: 'https://login.microsoftonline.com/', + providerId: 'microsoft', + cloudName: 'AzureCloud', + authority: 'https://login.microsoftonline.com/', }); const now = 1_800_000_000; vi.setSystemTime(now * 1000); @@ -1512,8 +1518,14 @@ describe('regular connection startup diagnostics', () => { signal.abort(); await lookup(); - expect(renewalEvents().map(({ telemetry, error }) => [telemetry.properties, telemetry.measurements, error])).toEqual([ - [{ surface: 'extension', renewalOutcome: 'returned', result: 'Succeeded' }, { tokenLifetimeSeconds: 3600, duration: 0 }, undefined], + expect( + renewalEvents().map(({ telemetry, error }) => [telemetry.properties, telemetry.measurements, error]), + ).toEqual([ + [ + { surface: 'extension', renewalOutcome: 'returned', result: 'Succeeded' }, + { tokenLifetimeSeconds: 3600, duration: 0 }, + undefined, + ], [{ surface: 'extension', renewalOutcome: 'returned', result: 'Succeeded' }, { duration: 0 }, undefined], [{ surface: 'extension', renewalOutcome: 'noSession', result: 'Succeeded' }, { duration: 0 }, undefined], ]); diff --git a/src/documentdb/playground/PlaygroundEvaluator.ts b/src/documentdb/playground/PlaygroundEvaluator.ts index 98d5480ae..d2f1c40ee 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.ts @@ -176,7 +176,14 @@ export class PlaygroundEvaluator implements vscode.Disposable { }, onTokenRequest: async (request, post, isCurrent, timings, trace, postStartup) => { const relay = this._relay; - await relay?.relay(request, post, () => this._relay === relay && isCurrent(), timings, trace, postStartup); + await relay?.relay( + request, + post, + () => this._relay === relay && isCurrent(), + timings, + trace, + postStartup, + ); }, onWorkerExit: (exitCode: number) => { ext.outputChannel.debug(`${logPrefix} Worker exited with code ${String(exitCode)}`); diff --git a/src/documentdb/playground/WorkerSessionManager.test.ts b/src/documentdb/playground/WorkerSessionManager.test.ts index 3eef3e5f1..5cc0c5bdb 100644 --- a/src/documentdb/playground/WorkerSessionManager.test.ts +++ b/src/documentdb/playground/WorkerSessionManager.test.ts @@ -16,7 +16,6 @@ import { ext } from '../../extensionVariables'; import { traceAuthFlow, type AuthTraceContext } from '../../utils/authTrace'; import { AuthMethodId } from '../auth/AuthMethod'; import * as tokenResource from '../auth/documentdbTokenResource'; -import * as entraSession from '../auth/entraSession'; import { getRecentEntraTokenFailure, recordEntraTokenFailure, @@ -1054,90 +1053,123 @@ describe('WorkerSessionManager', () => { return { manager, initPromise, requestId: initMessage.requestId, worker }; } - it.each([true, false])('counts only checked post-startup Entra relay outcomes (persistent=%s)', async (persistent) => { - const clusterId = 'test-cluster'; - const environment = { - providerId: 'microsoft', cloudName: 'AzureCloud', authority: 'https://login.microsoftonline.com/', - }; - const readEnvironment = vi.spyOn(entraSession, 'readEntraSignInEnvironment').mockReturnValue(environment); - const resolveResource = vi.spyOn(tokenResource, 'resolveInteractiveTokenResource').mockResolvedValue({ - cloudCategory: 'public', reason: 'host', scope: 'test-scope', resource: 'test-resource', details: {}, - }); - const account = { id: 'test-account', label: 'Test account' }; - const now = 1_800_000_000; - vi.setSystemTime(now * 1000); - const accessToken = `header.${Buffer.from(JSON.stringify({ iat: now - 60, exp: now + 3540 })).toString('base64url')}.signature`; - const session = { id: 'test-session', account, accessToken, scopes: [] }; - const getSession = vi.spyOn(entraSession, 'getEntraSession').mockResolvedValue(session); - const relay = new WorkerTokenRelay( - clusterId, - { - type: 'init', requestId: '', connectionString: 'mongodb://example.mongocluster.cosmos.azure.com/', - clientOptions: {}, databaseName: 'test', authMechanism: AuthMethodId.MicrosoftEntraID, persistent, - }, - ClustersClient.getEpoch(clusterId), - 'relay-id', - undefined, - ); - const onTokenRequest = vi.fn>( - relay.relay.bind(relay), - ); - callbacks.onTokenRequest = onTokenRequest; - const manager = new WorkerSessionManager(callbacks); - try { - const active = await startWorker(persistent, {}, manager); - const request = async (requestId: string): Promise => { - active.worker._emit('message', { type: 'tokenRequest', requestId }); - await onTokenRequest.mock.results.at(-1)?.value; + it.each([true, false])( + 'counts only checked post-startup Entra relay outcomes (persistent=%s)', + async (persistent) => { + const clusterId = 'test-cluster'; + const environment = { + providerId: 'microsoft', + cloudName: 'AzureCloud', + authority: 'https://login.microsoftonline.com/', }; - const renewalEvents = (): RecordedTelemetry[] => - mockTelemetryEvents.filter(({ eventName }) => eventName === 'connection.tokenRenewal'); - await request('startup-lookup'); - await request('another-startup-lookup'); - expect(renewalEvents()).toEqual([]); - active.worker._emit('message', { type: 'initResult', requestId: active.requestId, success: true }); - await active.initPromise; - - await request('renewal-with-lifetime'); - getSession.mockResolvedValueOnce({ ...session, accessToken: 'opaque-test-token' }); - await request('opaque-renewal'); - getSession.mockResolvedValueOnce(undefined); - await request('missing-session'); - getSession.mockResolvedValueOnce({ ...session, account: { ...account, id: 'different-account' } }); - await request('identity-mismatch'); - readEnvironment.mockReturnValueOnce({ ...environment, providerId: 'microsoft-sovereign-cloud' }); - await request('provider-changed'); - getSession.mockRejectedValueOnce(new Error('test provider failure')); - await request('refresh-failed'); - getSession.mockRejectedValueOnce(new UserCancelledError()); - await request('canceled-lookup'); - const driverAbortFlag = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT); - getSession.mockImplementationOnce(async () => { - Atomics.store(new Int32Array(driverAbortFlag), 0, 1); - return session; + const readEnvironment = vi + .spyOn(entraSession, 'readEntraSignInEnvironment') + .mockReturnValue(environment); + const resolveResource = vi.spyOn(tokenResource, 'resolveInteractiveTokenResource').mockResolvedValue({ + cloudCategory: 'public', + reason: 'host', + scope: 'test-scope', + resource: 'test-resource', + details: {}, }); - active.worker._emit('message', { type: 'tokenRequest', requestId: 'driver-stopped-waiting', driverAbortFlag }); - await onTokenRequest.mock.results.at(-1)?.value; - ClustersClient.invalidate(clusterId); - await expect(request('stale-lookup')).rejects.toBeInstanceOf(UserCancelledError); - - const surface = persistent ? 'shell' : 'playground'; - expect(renewalEvents().map(({ telemetry, error }) => [telemetry.properties, telemetry.measurements, error])) - .toEqual([ - [{ surface, renewalOutcome: 'returned', result: 'Succeeded' }, { tokenLifetimeSeconds: 3600, duration: 0 }, undefined], + const account = { id: 'test-account', label: 'Test account' }; + const now = 1_800_000_000; + vi.setSystemTime(now * 1000); + const accessToken = `header.${Buffer.from(JSON.stringify({ iat: now - 60, exp: now + 3540 })).toString('base64url')}.signature`; + const session = { id: 'test-session', account, accessToken, scopes: [] }; + const getSession = vi.spyOn(entraSession, 'getEntraSession').mockResolvedValue(session); + const relay = new WorkerTokenRelay( + clusterId, + { + type: 'init', + requestId: '', + connectionString: 'mongodb://example.mongocluster.cosmos.azure.com/', + clientOptions: {}, + databaseName: 'test', + authMechanism: AuthMethodId.MicrosoftEntraID, + persistent, + }, + ClustersClient.getEpoch(clusterId), + 'relay-id', + undefined, + ); + const onTokenRequest = vi.fn>( + relay.relay.bind(relay), + ); + callbacks.onTokenRequest = onTokenRequest; + const manager = new WorkerSessionManager(callbacks); + try { + const active = await startWorker(persistent, {}, manager); + const request = async (requestId: string): Promise => { + active.worker._emit('message', { type: 'tokenRequest', requestId }); + await onTokenRequest.mock.results.at(-1)?.value; + }; + const renewalEvents = (): RecordedTelemetry[] => + mockTelemetryEvents.filter(({ eventName }) => eventName === 'connection.tokenRenewal'); + await request('startup-lookup'); + await request('another-startup-lookup'); + expect(renewalEvents()).toEqual([]); + active.worker._emit('message', { type: 'initResult', requestId: active.requestId, success: true }); + await active.initPromise; + + await request('renewal-with-lifetime'); + getSession.mockResolvedValueOnce({ ...session, accessToken: 'opaque-test-token' }); + await request('opaque-renewal'); + getSession.mockResolvedValueOnce(undefined); + await request('missing-session'); + getSession.mockResolvedValueOnce({ ...session, account: { ...account, id: 'different-account' } }); + await request('identity-mismatch'); + readEnvironment.mockReturnValueOnce({ ...environment, providerId: 'microsoft-sovereign-cloud' }); + await request('provider-changed'); + getSession.mockRejectedValueOnce(new Error('test provider failure')); + await request('refresh-failed'); + getSession.mockRejectedValueOnce(new UserCancelledError()); + await request('canceled-lookup'); + const driverAbortFlag = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT); + getSession.mockImplementationOnce(async () => { + Atomics.store(new Int32Array(driverAbortFlag), 0, 1); + return session; + }); + active.worker._emit('message', { + type: 'tokenRequest', + requestId: 'driver-stopped-waiting', + driverAbortFlag, + }); + await onTokenRequest.mock.results.at(-1)?.value; + ClustersClient.invalidate(clusterId); + await expect(request('stale-lookup')).rejects.toBeInstanceOf(UserCancelledError); + + const surface = persistent ? 'shell' : 'playground'; + expect( + renewalEvents().map(({ telemetry, error }) => [ + telemetry.properties, + telemetry.measurements, + error, + ]), + ).toEqual([ + [ + { surface, renewalOutcome: 'returned', result: 'Succeeded' }, + { tokenLifetimeSeconds: 3600, duration: 0 }, + undefined, + ], [{ surface, renewalOutcome: 'returned', result: 'Succeeded' }, { duration: 0 }, undefined], [{ surface, renewalOutcome: 'noSession', result: 'Succeeded' }, { duration: 0 }, undefined], - [{ surface, renewalOutcome: 'identityMismatch', result: 'Succeeded' }, { duration: 0 }, undefined], + [ + { surface, renewalOutcome: 'identityMismatch', result: 'Succeeded' }, + { duration: 0 }, + undefined, + ], [{ surface, renewalOutcome: 'noSession', result: 'Succeeded' }, { duration: 0 }, undefined], [{ surface, renewalOutcome: 'failed', result: 'Succeeded' }, { duration: 0 }, undefined], ]); - } finally { - manager.dispose(); - getSession.mockRestore(); - resolveResource.mockRestore(); - readEnvironment.mockRestore(); - } - }); + } finally { + manager.dispose(); + getSession.mockRestore(); + resolveResource.mockRestore(); + readEnvironment.mockRestore(); + } + }, + ); it.each(['signInRequired', 'identityMismatch', 'destinationRejected', 'refreshFailed'] as const)( 'reconstructs %s at both boundaries and marks a warm worker broken', From 9164b2b7187744f89df4059077be609881c7f4f3 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 12:41:07 +0000 Subject: [PATCH 09/15] Clarify what a returned worker relay outcome means Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/telemetry.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/telemetry.md b/docs/ai-and-plans/features/connection-lifecycle/telemetry.md index cea396b73..cee795c90 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/telemetry.md +++ b/docs/ai-and-plans/features/connection-lifecycle/telemetry.md @@ -67,9 +67,11 @@ let Operations = ## Daily database token lookups and lifetime -`connection.tokenRenewal` counts completed post-startup Entra database token lookups on the extension, -Shell, and Playground. `returned` means a token passed the callback's checks; it does **not** mean the -token changed, MSAL made a network request, or the database accepted the token. Lifetime is the +`connection.tokenRenewal` counts post-startup Entra database token lookup outcomes. For `extension`, +`returned` means the token passed the host callback's checks. For `shell` and `playground`, it means +the host checked and sent a token response; the worker can still reject or discard it before its +callback completes. On any surface, `returned` does **not** mean the token changed, MSAL made a +network request, or the database accepted the token. Lifetime is the JWT's positive `exp − iat` in seconds, not its remaining validity. An opaque or invalid lifetime is missing, not zero. Compare returned rows with and without a lifetime; failures don't have one. From b5d414ddda0658bffff0206fc99358b8c791ba96 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 12:41:15 +0000 Subject: [PATCH 10/15] Describe the tree expansion metric by entry generation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/telemetry.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/telemetry.md b/docs/ai-and-plans/features/connection-lifecycle/telemetry.md index cee795c90..0b8faa146 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/telemetry.md +++ b/docs/ai-and-plans/features/connection-lifecycle/telemetry.md @@ -96,11 +96,13 @@ surface to check the observed volume against the telemetry budget. No lookups me ## Post-release outcomes by client age and generation -The replacement count uses successful cluster expansions that did not return first-time or -cached recovery rows. Other operations are shown for context only: for example, an RPC can -return a typed unavailable result without reporting an SDK failure. The count is neither -unique recoveries nor proof that renewal triggered them. Not every operation reports client -age or generation; show missing values explicitly. +`successfulExpansionsEnteringGen2Plus` counts successful cluster expansions that reported +generation 2 or later **at entry** and did not return first-time or cached recovery rows. It +does not count an expansion that enters on generation 1 and replaces it during the operation. +Discovery expansions do not report a generation here. The count is neither unique recoveries nor +proof that renewal triggered them. Other operations are shown for context only: an RPC can return a +typed unavailable result without reporting an SDK failure. Missing ages and generations are shown +explicitly. ```kusto Operations @@ -111,7 +113,7 @@ Operations generationBand = case(isnull(generation) or generation < 1, "(missing)", generation == 1, "1", "2+"), lifecycleKind = coalesce(failureKind, "(missing)") | summarize operations = count(), - successfulClusterExpansionsOnReplacement = countif( + successfulExpansionsEnteringGen2Plus = countif( family == "getchildren" and tolower(parentContext) matches regex @"\btreeitem_documentdbcluster\b" and operationResult == "succeeded" and generation >= 2 and not(recoveryRows)) by version, family, ageBand, generationBand, operationResult, lifecycleKind, signature From 380a6633d29e8dd4db83c2b03b44a5b1766c45ca Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 12:41:37 +0000 Subject: [PATCH 11/15] Defer the incomparable cross-release failure metric Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/README.md | 1 + .../connection-lifecycle/decisions.md | 12 +++ .../iterations/01-dev-plan.md | 6 +- .../01-pr7-telemetry-and-docs-review.md | 8 +- .../connection-lifecycle/telemetry.md | 97 ++++--------------- 5 files changed, 42 insertions(+), 82 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index b2618eaa9..7421adc26 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -132,6 +132,7 @@ See [decisions.md](./decisions.md): - 0017 limit unavailable webview recovery to Retry and Close view. - 0018 saved connection edits permanently lock existing views. - 0019 require a fresh Dashboard delete after Disconnect and retain tree-only Paste. +- 0020 defer the late-failure comparison across releases and retain descriptive telemetry. ## Timeline diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index 7f094b03e..be01e97b3 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -31,6 +31,7 @@ created: 2026-11-19 | 0017 | Limit unavailable webview recovery to Retry and Close view | Accepted (modified by 0018) | Operator wants credential repair in the tree and no extra recovery workflow in a tab | 2026-11-24 | Yes; removes in-view credential repair | | 0018 | Saved connection edits permanently lock existing views | Accepted | Operator prefers simple reconnect for unchanged settings over recovery after edits | 2026-11-24 | Yes; removes same-identity recovery after a saved edit | | 0019 | Require a fresh Dashboard delete after Disconnect and keep Paste Collection in the tree | Accepted | Operator: a lifecycle change cancels the pending delete and never replays it | 2026-11-24 | — | +| 0020 | Defer the cross-release comparison of late failures | Accepted | Operator: keep descriptive telemetry and defer the comparison | 2026-11-26 | Yes; removes the WI-9 before/after comparison for 1.2.0 | > Entries below are **semantically** immutable: append new entries rather than rewriting old ones, > and record reversals as a new entry plus a status change above. Heading text is frozen once @@ -490,3 +491,14 @@ in the tree only. Copy stores a tree reference, not a snapshot of the data or credentials. The later tree Paste uses the current connection; it does not resume a Dashboard operation. Binding the whole clipboard and index-copy flow was not part of this change. + +## 0020. Defer the cross-release comparison of late failures + +The operator chose to keep descriptive telemetry and defer the WI-9 before/after comparison +for 1.2.0. Auth and closed-client unavailability can now be returned as normal RPC responses, +which the SDK records as successes without a failure signature. An apparent drop across releases +could be a reporting change rather than improved recovery. + +Keep renewal, client age and entry generation, and ARM challenge queries for a single version. +Do not add an instrumentation path or keep a socket-only comparison in this release. CP-5 still +checks pre-release ingestion and records that the late-failure trend is unmeasured. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 990625223..41501d54e 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1878,6 +1878,9 @@ one loop. - Case 1 passed: `npm run build` and 349 focused tests in 8 files. Ingestion is **pending**; the [telemetry queries](../telemetry.md) are ready to run. The dashboard worktree has unrelated changes in progress and was left untouched. +- PR7 review superseded the before/after comparison in items 2 and 5. Auth and closed-client + unavailability are not measured equivalently across releases. The operator deferred the + comparison and kept descriptive telemetry for CP-5 ([decision 0020](../decisions.md#0020-defer-the-cross-release-comparison-of-late-failures)). --- @@ -1933,4 +1936,5 @@ one loop. # Outcome - **WI-9 telemetry: pending ingestion.** Run the [feature queries](../telemetry.md) on - pre-release data before CP-5. Record the packaged operator validation here at OP-6. + pre-release data before CP-5. The cross-release trend is unmeasured for 1.2.0. Record the + packaged operator validation here at OP-6. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md index 12410ca3d..0138ae079 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md @@ -10,8 +10,8 @@ queries against live data. ## F1. The baseline can show a false drop in classified failures (high for WI-9) -The [before/after query](../telemetry.md#comparable-late-failures-before-and-after-release) -uses error fields that the new tree `connect` path masks but the baseline did not. The +The original before/after query used error fields that the new tree `connect` path masks but +the baseline did not. The same failure can move to the unclassified bucket without any change in its frequency. Tree expansion can also return recovery actions as a normal result. @@ -28,6 +28,10 @@ scopes; do not add a telemetry field or change redaction. limits the classified comparison to two database RPCs and uses `causeType` alone. Tree events stay descriptive, and unclassified failures remain visible. +**Superseded by Copilot follow-up:** The RPCs can also return typed unavailability normally, +which is reported as SDK success. The operator [deferred the comparison](../decisions.md#0020-defer-the-cross-release-comparison-of-late-failures) +and retained descriptive telemetry for 1.2.0. + ## F2. Disconnect does not wait behind an active task (medium) The [release notes](../../../../release-notes/1.2.md) say Disconnect waits, and the diff --git a/docs/ai-and-plans/features/connection-lifecycle/telemetry.md b/docs/ai-and-plans/features/connection-lifecycle/telemetry.md index 0b8faa146..fd9b2c274 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/telemetry.md +++ b/docs/ai-and-plans/features/connection-lifecycle/telemetry.md @@ -8,33 +8,23 @@ created: 2026-11-25 # Connection lifecycle telemetry **Pending ingestion verification.** Run these queries in the extension's Application Insights Logs workspace. -Paste the common setup before any one query body. Set the deployment timestamp and actual extension versions -for the two cohorts. Use equal, complete UTC windows, with a gap if the rollout was gradual. +Paste the common setup before any one query body. Set the actual extension version (including +the prerelease suffix for CP-5) and UTC window to inspect. ```kusto -let ReleaseAt = startofday(ago(7d)); // Replace with rollout boundary for this comparison. -let Window = 7d; -let RolloutGap = 0d; -let BaselineVersion = "1.1.0"; +let StartAt = startofday(ago(7d)); +let EndAt = StartAt + 7d; let ReleaseVersion = "1.2.0"; -let BeforeEnd = ReleaseAt - RolloutGap; -let AfterStart = ReleaseAt + RolloutGap; -let Warmup = 1d; let Events = customEvents - | where timestamp >= BeforeEnd - Window - Warmup and timestamp < AfterStart + Window + | where timestamp >= StartAt and timestamp < EndAt | extend version = coalesce(tostring(customDimensions["common.extversion"]), tostring(customDimensions.extensionVersion), tostring(column_ifexists("application_Version", "")), "(missing)") - | extend cohort = case( - version == BaselineVersion and timestamp >= BeforeEnd - Window - Warmup and timestamp < BeforeEnd, "before", - version == ReleaseVersion and timestamp >= AfterStart - Warmup and timestamp < AfterStart + Window, "after", "") - | where isnotempty(cohort) - | extend inWindow = iff(cohort == "before", timestamp >= BeforeEnd - Window, timestamp >= AfterStart) + | where version == ReleaseVersion | extend eventScope = tolower(extract(@"([^/]+)$", 1, name)), sdkResult = tolower(tostring(customDimensions.result)); let Operations = Events - | where inWindow | extend parentContext = tostring(customDimensions.parentNodeContext) | extend family = case( eventScope == "connect", "connect", @@ -77,7 +67,7 @@ missing, not zero. Compare returned rows with and without a lifetime; failures d ```kusto Events -| where inWindow and eventScope == "connection.tokenrenewal" +| where eventScope == "connection.tokenrenewal" | extend surface = coalesce(tostring(customDimensions.surface), "(missing)"), outcome = coalesce(tostring(customDimensions.renewalOutcome), "(missing)"), lifetime = todouble(customMeasurements.tokenLifetimeSeconds) @@ -86,7 +76,7 @@ Events lifetimeSamples = countif(isnotnull(lifetime)), missingLifetime = countif(isnull(lifetime)), percentiles(lifetime, 50, 90) - by cohort, version, day = bin(timestamp, 1d), surface, outcome + by version, day = bin(timestamp, 1d), surface, outcome | order by day asc, surface asc, outcome asc ``` @@ -94,7 +84,7 @@ This is background activity: exclude `connection.tokenrenewal` from active-use e Expect roughly one lookup per active Entra client-hour, not one per operation. Use daily counts by surface to check the observed volume against the telemetry budget. No lookups means no evidence. -## Post-release outcomes by client age and generation +## Observed outcomes by client age and entry generation `successfulExpansionsEnteringGen2Plus` counts successful cluster expansions that reported generation 2 or later **at entry** and did not return first-time or cached recovery rows. It @@ -106,7 +96,6 @@ explicitly. ```kusto Operations -| where cohort == "after" | extend ageBand = case( isnull(ageMs) or ageMs < 0, "(missing)", ageMs < 3600000, "<1h", ageMs < 7200000, "1–2h", ageMs < 14400000, "2–4h", "4h+"), @@ -120,64 +109,14 @@ Operations | order by family asc, ageBand asc, generationBand asc ``` -## Comparable late failures before and after release +## Cross-release comparison deferred -The baseline lacks client age and generation. Compare the same database RPC scopes in versions -that report the same `causeType` scheme. Do not use tree `connect` or expansion counts for this -comparison: their redaction and reporting of failures as recovery rows make the cohorts -incomparable. These are rates of reported RPC failure signatures, not all database failures. - -Use the **same exposure on both versions**: recorded non-canceled calls to each selected -procedure at least one hour after the most recent preceding successful database startup in a -VS Code session whose successful startups all used Entra ID. Only existing session metadata -is used; no session key or raw failure data is returned. The warmup is identical for both cohorts. -This is a session-age proxy, not per-client age or a causal estimate. - -```kusto -let Startups = materialize( - Events - | where eventScope == "connect.startup" and tostring(customDimensions.startupOutcome) =~ "succeeded" - | extend sessionKey = coalesce(tostring(customDimensions.VSCodeSessionId), - tostring(customDimensions["common.vscodesessionid"])), - authMethod = tostring(customDimensions.authMethod) - | where isnotempty(sessionKey) - | project cohort, version, sessionKey, startupAt = timestamp, authMethod -); -let EntraSessions = - Startups - | summarize otherAuth = countif(authMethod !~ "MicrosoftEntraID") by cohort, version, sessionKey - | where otherAuth == 0 - | project cohort, version, sessionKey; -Operations -| where operationResult in ("succeeded", "failed") -| where eventScope in ("documentdb.rpc.query.mongoclusters.collectionview.runfindquery", - "documentdb.rpc.query.mongoclusters.documentview.getdocumentbyid") -| extend sessionKey = coalesce(tostring(customDimensions.VSCodeSessionId), - tostring(customDimensions["common.vscodesessionid"])) -| where isnotempty(sessionKey) -| project cohort, version, sessionKey, timestamp, eventScope, operationResult, signature -| serialize operationRow = row_number() -| join kind=inner (Startups | join kind=leftsemi (EntraSessions) on cohort, version, sessionKey) - on cohort, version, sessionKey -| where startupAt <= timestamp -| summarize arg_max(startupAt, *) by operationRow -| where timestamp - startupAt >= 1h -| summarize exposureOperations = count(), - failedOperations = countif(operationResult == "failed"), - lateAuth = countif(signature == "auth"), - lateSocket = countif(signature == "socket"), - lateClosedClient = countif(signature == "closedClient"), - otherOrUnclassified = countif(signature == "otherOrUnclassified") - by cohort, version, eventScope -| extend authPer1000 = 1000.0 * lateAuth / exposureOperations, - socketPer1000 = 1000.0 * lateSocket / exposureOperations, - closedClientPer1000 = 1000.0 * lateClosedClient / exposureOperations -| order by eventScope asc, cohort asc -``` - -Compare the same procedure across cohorts and inspect counts, including unclassified failures, -alongside rates. Missing exposure, or cohorts without comparable signatures, are insufficient -evidence, not zero failures. +In 1.2.0, a database RPC can return auth or closed-client unavailability as a normal +response, recorded as `Succeeded` without `causeType`. Older versions could report the same +outcome as an RPC failure. Matching procedures and signatures therefore does not make the +counts comparable. Use the queries here to describe a single release and verify ingestion, +not to claim that late failures fell. The comparison and any additional instrumentation are +deferred; see [decision 0020](./decisions.md#0020-defer-the-cross-release-comparison-of-late-failures). ## ARM challenge versus final operation result @@ -190,12 +129,12 @@ Zero observed challenges is inconclusive. ```kusto Events -| where inWindow and tostring(customDimensions.challenge) =~ "true" +| where tostring(customDimensions.challenge) =~ "true" | extend challengeOutcome = tolower(tostring(customDimensions.challengeSuccess)) | extend challengeOutcome = case(challengeOutcome == "true", "tokenAcquired", challengeOutcome == "false", "noToken", "(missing)"), finalResult = coalesce(sdkResult, "(missing)") | summarize challengedOperations = count() - by cohort, version, day = bin(timestamp, 1d), eventScope, challengeOutcome, finalResult + by version, day = bin(timestamp, 1d), eventScope, challengeOutcome, finalResult | order by day asc, eventScope asc ``` From 09848fcf2cf0712e49cebf100f033ebc037e4c72 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 12:41:51 +0000 Subject: [PATCH 12/15] Document how workers resume after an unchanged reconnect Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/release-notes/1.2.md | 5 +++-- docs/user-manual/connecting-to-databases.md | 9 ++++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/release-notes/1.2.md b/docs/release-notes/1.2.md index 5f11b45f8..90e46d95e 100644 --- a/docs/release-notes/1.2.md +++ b/docs/release-notes/1.2.md @@ -70,8 +70,9 @@ changed saved settings never inherits an old view's draft or permissions. - **No replay of uncertain writes.** Reconnecting or clicking Retry never resubmits the failed operation. Check the server before repeating a write that did not report an outcome. -- **Shells and playgrounds keep bounded state.** Disconnect stops their worker connections. Open a - new shell, or re-pick a playground connection, after reconnecting. +- **Resume in the same shell or playground.** After reconnecting with unchanged settings, run + again in the existing terminal or file. Scrollback and query text stay, but worker-local state + such as variables is lost. - **Follow-up network work is outside this release.** Kubernetes tunnel recreation and broader network resilience remain tracked in [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105). diff --git a/docs/user-manual/connecting-to-databases.md b/docs/user-manual/connecting-to-databases.md index 48ee537f8..2c427f0c0 100644 --- a/docs/user-manual/connecting-to-databases.md +++ b/docs/user-manual/connecting-to-databases.md @@ -69,9 +69,12 @@ why it is unavailable: Use the cluster's **Reconnect** action in the tree to restore the same connection. If reconnect automatically opens the retained Dashboard for that connection, it retries on its own. If it -stays disabled, select **Retry**, as you would in other retained webviews. An Interactive Shell prints -**Disconnected** and stops its worker, then requires a new shell from the tree. A retained Query -Playground requires you to reconnect and re-pick its connection before running it again. +stays disabled, select **Retry**, as you would in other retained webviews. + +After reconnecting to the same connection with unchanged settings, run a command in the existing +Interactive Shell or run the retained Query Playground again. No new terminal or connection pick +is needed. The terminal scrollback and Playground text remain, but worker-local state such as +variables and open cursors is lost. Interrupted commands are not replayed. ## After changing connection details From 3f6f4d6d6117aa7d709d4ff73f536150b342f6f9 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 12:42:08 +0000 Subject: [PATCH 13/15] Distinguish saved-edit behavior for views and workers Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/release-notes/1.2.md | 16 ++++++++-------- docs/user-manual/connecting-to-databases.md | 20 +++++++++++--------- 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/docs/release-notes/1.2.md b/docs/release-notes/1.2.md index 90e46d95e..24aa55459 100644 --- a/docs/release-notes/1.2.md +++ b/docs/release-notes/1.2.md @@ -57,14 +57,14 @@ Learn how retained views, shells, and playgrounds resume in the ### ⭐ Open Work Stays Bound to Its Original Connection -Collection View, Document View, the Cluster Dashboard, Interactive Shell, and Query Playground do -not silently switch to new credentials or a different identity. A save with **Update Credentials…** -or **Update Connection String…**, including a password-only change, permanently locks existing -views in the current VS Code window. Their contents remain available for copying, and new work -starts by opening a new view from the tree. - -Same-identity client replacement remains transparent. A different identity, removed connection, or -changed saved settings never inherits an old view's draft or permissions. +Saving changes with **Update Credentials…** or **Update Connection String…**, even just a password, +permanently disables operations in existing Collection View, Document View, and Cluster Dashboard +tabs. You can still copy their contents. Open a new view from the tree to use the saved settings. + +Shell and Playground are different: a Shell you choose to leave running can keep its previous +settings, and a restarted worker can use a password-only update without a new terminal or connection +pick. A different host, user, or identity requires a new Shell or an explicit Playground connection +pick. ## Key Limits and Improvements diff --git a/docs/user-manual/connecting-to-databases.md b/docs/user-manual/connecting-to-databases.md index 2c427f0c0..bbb754b92 100644 --- a/docs/user-manual/connecting-to-databases.md +++ b/docs/user-manual/connecting-to-databases.md @@ -78,12 +78,14 @@ variables and open cursors is lost. Interrupted commands are not replayed. ## After changing connection details -Saving a change with **Update Credentials…** or **Update Connection String…** keeps the old view's -contents available for inspection or copying, but the saved change permanently locks that existing -view in this VS Code window. This includes a password-only edit. The dialog offers **Close view**; -open a new view from the tree to use the saved settings. - -The same rule applies to an Interactive Shell or Query Playground bound to the previous settings: -do not continue by switching identities inside the old session. Open a new shell or re-pick the -playground connection from the tree. Cancelling an edit, or saving without changing stored details, -does not lock existing sessions. +Saving a change with **Update Credentials…** or **Update Connection String…** permanently disables +database operations in the existing Collection View, Document View, and Cluster Dashboard tabs. +This includes a password-only edit. Their contents remain available for inspection or copying. +Select **Close view** and open a new view from the tree to use the saved settings. + +Shell and Playground follow different rules. If you choose to keep a running Shell connected when +prompted, its worker can continue using the previous settings. After a password-only edit, a new +worker can use the updated password in the existing terminal or Playground without a new connection +pick. To use a different host, user, or sign-in identity, open a new Shell or explicitly select the +connection again in the Playground. Cancelling an edit or saving unchanged settings does not lock +the open views. From 31195bfb5e0f991f21a7af88a6ffa991f72b0e71 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 12:43:01 +0000 Subject: [PATCH 14/15] Fence Entra renewal telemetry with the current lookup epoch Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/commands/signInAgain/signInAgain.test.ts | 15 ++++--- src/commands/signInAgain/signInAgain.ts | 6 +-- src/documentdb/ClustersClient.test.ts | 45 ++++++++++++++++--- src/documentdb/ClustersClient.ts | 18 ++++---- .../auth/MicrosoftEntraIDAuthHandler.test.ts | 8 ++-- .../auth/MicrosoftEntraIDAuthHandler.ts | 17 ++++--- src/documentdb/auth/authCallerPolicy.ts | 4 +- 7 files changed, 76 insertions(+), 37 deletions(-) diff --git a/src/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts index 0afc0eaf6..b6bffabc0 100644 --- a/src/commands/signInAgain/signInAgain.test.ts +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -118,21 +118,22 @@ describe('signInAgain', () => { vi.mocked(getEntraSession).mockResolvedValueOnce({ account: { id: pin.accountId, label: pin.accountLabel }, } as vscode.AuthenticationSession); - const isCurrentForTokenRenewal = vi.fn(() => true); + const getTokenLookupEpoch = vi.fn<() => number | undefined>(() => 1); vi.mocked(ClustersClient.startAfterSignIn).mockImplementationOnce(async () => { const [policy] = mocks.capturePolicy.mock.lastCall!; - expect(policy.canObserveTokenLookup?.()).toBe(false); - return { isCurrentForTokenRenewal } as unknown as ClustersClient; + expect(policy.getTokenLookupEpoch?.()).toBeUndefined(); + return { getTokenLookupEpoch } as unknown as ClustersClient; }); await signInAgain(actionContext(), { clusterId }); const [policy] = mocks.capturePolicy.mock.lastCall!; expect(policy.onTokenLookup).toBeTypeOf('function'); - expect(policy.canObserveTokenLookup?.()).toBe(true); - expect(isCurrentForTokenRenewal).toHaveBeenCalledExactlyOnceWith(1); - isCurrentForTokenRenewal.mockReturnValue(false); - expect(policy.canObserveTokenLookup?.()).toBe(false); + expect(policy.getTokenLookupEpoch?.()).toBe(1); + getTokenLookupEpoch.mockReturnValue(2); + expect(policy.getTokenLookupEpoch?.()).toBe(2); + getTokenLookupEpoch.mockReturnValue(undefined); + expect(policy.getTokenLookupEpoch?.()).toBeUndefined(); }); it.each([undefined, new Error('User did not consent to login.')])( diff --git a/src/commands/signInAgain/signInAgain.ts b/src/commands/signInAgain/signInAgain.ts index aafc148c3..aa5c6b6d5 100644 --- a/src/commands/signInAgain/signInAgain.ts +++ b/src/commands/signInAgain/signInAgain.ts @@ -121,12 +121,12 @@ async function signInAgainInternal( }; let starting = false; - let established: { client: ClustersClient; epoch: number } | undefined; + let establishedClient: ClustersClient | undefined; try { const handler = new MicrosoftEntraIDAuthHandler(credentials, { interactive: false, pinnedEntraIdentity: identity, - canObserveTokenLookup: () => established?.client.isCurrentForTokenRenewal(established.epoch) ?? false, + getTokenLookupEpoch: () => establishedClient?.getTokenLookupEpoch(), onTokenLookup: (observation) => emitTokenRenewal('extension', observation), }); const auth = await handler.configureAuth(undefined, undefined, async (request) => { @@ -170,7 +170,7 @@ async function signInAgainInternal( reportClosed(); return undefined; } - established = { client, epoch: startupEpoch }; + establishedClient = client; if ( ClustersClient.getExistingClient(clusterId) === client && !ClustersClient.getLatchReason(clusterId) && diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index c9f20b9c7..d19919e2a 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -1444,7 +1444,7 @@ describe('regular connection startup diagnostics', () => { const policy = { interactive, ...(interactive - ? { canObserveTokenLookup: expect.any(Function), onTokenLookup: expect.any(Function) } + ? { getTokenLookupEpoch: expect.any(Function), onTokenLookup: expect.any(Function) } : {}), }; expect(factory).toHaveBeenCalledWith(authMethod, expect.objectContaining({ clusterId }), policy); @@ -1455,7 +1455,7 @@ describe('regular connection startup diagnostics', () => { }, ); - it('counts completed Entra lookups only after startup, independent of database acceptance', async () => { + it('counts completed Entra lookups on the current client, independent of database acceptance', async () => { CredentialCache.setAuthCredentials( clusterId, AuthMethodId.MicrosoftEntraID, @@ -1480,15 +1480,16 @@ describe('regular connection startup diagnostics', () => { const account = { id: 'test-account', label: 'Test account' }; const session = { id: 'test-session', account, accessToken: timedToken, scopes: [] }; const getSession = vi.spyOn(entraSession, 'getEntraSession').mockResolvedValue(session); - const signal = new AbortController(); - const lookup = async (timeoutContext = signal.signal): Promise => { + const getCallback = (): NonNullable => { const options = vi.mocked(MongoClient).mock.lastCall?.[1]; const callback = options?.authMechanismProperties?.OIDC_CALLBACK; if (!callback) { throw new Error('Expected an OIDC callback'); } - return await callback({ version: 1, timeoutContext }); + return callback; }; + const params = { version: 1, timeoutContext: new AbortController().signal } as const; + const lookup = (): Promise => getCallback()(params); const renewalEvents = (): RecordedTelemetry[] => mockTelemetryEvents.filter(({ eventName }) => eventName === 'connection.tokenRenewal'); const serverRejection = new MongoServerError({ code: 18, message: 'test server rejection' }); @@ -1516,8 +1517,7 @@ describe('regular connection startup diagnostics', () => { getSession.mockResolvedValueOnce(undefined); await expect(lookup()).rejects.toBeInstanceOf(EntraSignInRequiredError); - signal.abort(); - await lookup(); + await getCallback()({ ...params, timeoutContext: AbortSignal.abort() }); expect( renewalEvents().map(({ telemetry, error }) => [telemetry.properties, telemetry.measurements, error]), ).toEqual([ @@ -1529,6 +1529,37 @@ describe('regular connection startup diagnostics', () => { [{ surface: 'extension', renewalOutcome: 'returned', result: 'Succeeded' }, { duration: 0 }, undefined], [{ surface: 'extension', renewalOutcome: 'noSession', result: 'Succeeded' }, { duration: 0 }, undefined], ]); + + const didStart = deferred(); + const finish = deferred(); + getSession.mockImplementationOnce(async () => { + didStart.resolve(); + await finish.promise; + return session; + }); + const spanningSave = lookup(); + await didStart.promise; + // An unchanged save latches and unlatches without retiring this client. + ClustersClient.latch(clusterId, 'credentialsUpdating'); + await lookup(); + ClustersClient.unlatch(clusterId); + finish.resolve(); + await spanningSave; + expect(renewalEvents()).toHaveLength(3); + expect(ClustersClient.getExistingClient(clusterId)).toBe(client); + + await lookup(); + expect(renewalEvents()).toHaveLength(4); + + const retiredLookup = getCallback(); + ClustersClient.reportFailure(client.binding, new MongoNotConnectedError('driver closed')); + await retiredLookup(params); + expect(await ClustersClient.getClient(clusterId)).not.toBe(client); + await retiredLookup(params); + const closedLookup = getCallback(); + await ClustersClient.deleteClient(clusterId); + await closedLookup(params); + expect(renewalEvents()).toHaveLength(4); }); it('passes its startup ID to auth configuration', async (): Promise => { diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 51820ad68..b4e960bba 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -636,7 +636,7 @@ export class ClustersClient { ...(pinnedEntraIdentity ? { pinnedEntraIdentity } : {}), ...(authMethod === AuthMethodId.MicrosoftEntraID ? { - canObserveTokenLookup: () => this.isCurrentForTokenRenewal(epoch), + getTokenLookupEpoch: () => this.getTokenLookupEpoch(), onTokenLookup: (observation) => emitTokenRenewal('extension', observation), } : {}), @@ -1142,13 +1142,15 @@ export class ClustersClient { return !this._closed && this._replacement === undefined; } - public isCurrentForTokenRenewal(epoch: number): boolean { - return ( - !this._closed && - ClustersClient.getExistingClient(this.clusterId) === this && - ClustersClient.getEpoch(this.clusterId) === epoch && - !ClustersClient.getLatchReason(this.clusterId) - ); + public getTokenLookupEpoch(): number | undefined { + if ( + !this.canReuse() || + ClustersClient.getExistingClient(this.clusterId) !== this || + ClustersClient.getLatchReason(this.clusterId) + ) { + return undefined; + } + return ClustersClient.getEpoch(this.clusterId); } public static hasReusableClient(clusterId: string): boolean { diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts index 31061882a..a6713232a 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts @@ -284,7 +284,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { const onTokenLookup = vi.fn(); const handler = new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), - { interactive: true, onTokenLookup }, + { interactive: true, getTokenLookupEpoch: () => 0, onTokenLookup }, ); const { options, verifiedIdentity } = await handler.configureAuth(undefined, { startupCorrelationId: 'startup-id', @@ -402,7 +402,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { const onCallbackTokenObserved = vi.fn>(); const { options } = await new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), - { interactive: true, onTokenLookup, observer: { onCallbackTokenObserved } }, + { interactive: true, getTokenLookupEpoch: () => 0, onTokenLookup, observer: { onCallbackTokenObserved } }, ).configureAuth(); if (failure === 'providerChanged') { getConfiguredAuthProviderId.mockReturnValue('microsoft-sovereign-cloud'); @@ -477,7 +477,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { const onTokenLookup = vi.fn(); const { options } = await new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), - { interactive: true, onTokenLookup }, + { interactive: true, getTokenLookupEpoch: () => 0, onTokenLookup }, ).configureAuth(); recordEntraTokenFailure('cluster-1', { cloudCategory: 'custom', authMethod: 'interactive' }); const priorFailure = getRecentEntraTokenFailure('cluster-1'); @@ -604,7 +604,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { const onCallbackTokenObserved = vi.fn>(); const { options } = await new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), - { interactive: true, onTokenLookup, observer: { onCallbackTokenObserved } }, + { interactive: true, getTokenLookupEpoch: () => 0, onTokenLookup, observer: { onCallbackTokenObserved } }, ).configureAuth(); const cause = new Error('AADSTS65002: private-cause'); getSessionFromVSCode.mockRejectedValueOnce(cause); diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts index 67bc5f271..edff7db94 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts @@ -69,11 +69,12 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { notifyAuthPhaseObserver(this.policy.observer, notify); } - private canObserveTokenLookup(): boolean { + private getTokenLookupEpoch(): number | undefined { try { - return this.policy.onTokenLookup !== undefined && (this.policy.canObserveTokenLookup?.() ?? true); + return this.policy.onTokenLookup ? this.policy.getTokenLookupEpoch?.() : undefined; } catch { - return false; + // Telemetry eligibility must not affect authentication. + return undefined; } } @@ -286,9 +287,13 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { const callback = properties?.OIDC_CALLBACK; if ((this.policy.onTokenLookup || this.policy.observer?.onCallbackTokenObserved) && properties && callback) { properties.OIDC_CALLBACK = async (params): Promise => { - const observe = this.canObserveTokenLookup(); + const lookupEpoch = this.getTokenLookupEpoch(); const notifyLookup = (observation: EntraTokenLookupObservation): void => { - if (observe && !params.timeoutContext?.aborted && this.canObserveTokenLookup()) { + if ( + lookupEpoch !== undefined && + !params.timeoutContext?.aborted && + this.getTokenLookupEpoch() === lookupEpoch + ) { try { this.policy.onTokenLookup?.(observation); } catch { @@ -299,7 +304,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { try { // Report acquisition only after the configured callback re-checks destination trust. const response = await callback(params); - if (observe) { + if (lookupEpoch !== undefined) { const lifetimeSeconds = jwtLifetimeSeconds(readJwtTimes(response.accessToken)); notifyLookup({ outcome: 'returned', diff --git a/src/documentdb/auth/authCallerPolicy.ts b/src/documentdb/auth/authCallerPolicy.ts index a000992ed..a28b149f4 100644 --- a/src/documentdb/auth/authCallerPolicy.ts +++ b/src/documentdb/auth/authCallerPolicy.ts @@ -45,8 +45,8 @@ export interface AuthCallerPolicy { readonly interactive: boolean; readonly pinnedEntraIdentity?: VerifiedEntraIdentity; readonly observer?: AuthPhaseObserver; - /** Entra only. Check at callback entry and completion to exclude startup and obsolete clients. */ - readonly canObserveTokenLookup?: () => boolean; + /** Entra only. Returns the current client epoch, or undefined if renewal telemetry is not eligible. */ + readonly getTokenLookupEpoch?: () => number | undefined; readonly onTokenLookup?: (observation: EntraTokenLookupObservation) => void; } From e70ab7cf67398575d45fce3b643f7a45273dc6ea Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 12:49:13 +0000 Subject: [PATCH 15/15] Format the connection lifecycle decision table Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/ai-and-plans/features/connection-lifecycle/decisions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index be01e97b3..89641b895 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -31,7 +31,7 @@ created: 2026-11-19 | 0017 | Limit unavailable webview recovery to Retry and Close view | Accepted (modified by 0018) | Operator wants credential repair in the tree and no extra recovery workflow in a tab | 2026-11-24 | Yes; removes in-view credential repair | | 0018 | Saved connection edits permanently lock existing views | Accepted | Operator prefers simple reconnect for unchanged settings over recovery after edits | 2026-11-24 | Yes; removes same-identity recovery after a saved edit | | 0019 | Require a fresh Dashboard delete after Disconnect and keep Paste Collection in the tree | Accepted | Operator: a lifecycle change cancels the pending delete and never replays it | 2026-11-24 | — | -| 0020 | Defer the cross-release comparison of late failures | Accepted | Operator: keep descriptive telemetry and defer the comparison | 2026-11-26 | Yes; removes the WI-9 before/after comparison for 1.2.0 | +| 0020 | Defer the cross-release comparison of late failures | Accepted | Operator: keep descriptive telemetry and defer the comparison | 2026-11-26 | Yes; removes the WI-9 before/after comparison for 1.2.0 | > Entries below are **semantically** immutable: append new entries rather than rewriting old ones, > and record reversals as a new entry plus a status change above. Heading text is frozen once