diff --git a/cloud/apps/sandbox-control/src/chatgpt-relay.ts b/cloud/apps/sandbox-control/src/chatgpt-relay.ts index 3a98ce62ee8..0f2a4a1b13b 100644 --- a/cloud/apps/sandbox-control/src/chatgpt-relay.ts +++ b/cloud/apps/sandbox-control/src/chatgpt-relay.ts @@ -22,7 +22,6 @@ export function createIdTokenSource(config: { serviceAccountJson: string; audien const doFetch = config.fetch ?? fetch const now = config.now ?? Date.now let cached: { value: string; expiresAt: number } | null = null - let pending: Promise | null = null let signingKey: CryptoKey | null = null async function mint(): Promise { let account: z.infer @@ -60,10 +59,9 @@ export function createIdTokenSource(config: { serviceAccountJson: string; audien if (cached && cached.expiresAt - now() > 5 * 60_000) { return cached.value } - pending ??= mint().finally(() => { - pending = null - }) - return pending + // Each request mints for itself: an in-flight mint shared across requests hangs them all if its own request + // is cancelled (settled-cache.ts). The value, once minted, is shared. + return mint() } } diff --git a/cloud/apps/sandbox-control/src/create-timing.ts b/cloud/apps/sandbox-control/src/create-timing.ts index 77ca597233e..fbbbd7c9239 100644 --- a/cloud/apps/sandbox-control/src/create-timing.ts +++ b/cloud/apps/sandbox-control/src/create-timing.ts @@ -46,26 +46,23 @@ async function recentTiming(db: D1Database, column: 'create_ms' | 'wake_ms'): Pr } const CACHE_MS = 5 * 60_000 -let cache: { db: D1Database; at: number; value: Promise } | null = null +// The settled value only (settled-cache.ts): an in-flight query shared across requests hangs them all if its +// own request is cancelled. +let cache: { db: D1Database; at: number; value: HostedSandboxTiming | undefined } | null = null /** * GET /v1/config is public, so the query runs at most once per isolate every 5 minutes; a failed * read is retried on the next request instead of being cached. */ -export function cachedCreateTiming(db: D1Database, now: number): Promise { +export async function cachedCreateTiming(db: D1Database, now: number): Promise { if (cache && cache.db === db && now - cache.at < CACHE_MS) { return cache.value } - const entry = { - db, - at: now, - value: recentCreateTiming(db).catch(() => { - if (cache === entry) { - cache = null - } - return undefined - }) + try { + const value = await recentCreateTiming(db) + cache = { db, at: now, value } + return value + } catch { + return undefined } - cache = entry - return entry.value } diff --git a/cloud/apps/sandbox-control/src/github-app.ts b/cloud/apps/sandbox-control/src/github-app.ts index 10e4405703c..2047f8a6434 100644 --- a/cloud/apps/sandbox-control/src/github-app.ts +++ b/cloud/apps/sandbox-control/src/github-app.ts @@ -177,7 +177,7 @@ export function createGitHubAppMinter(config: { metadataTokens.set(installationId, token) return token.token } - let requestOwners: { at: number; owners: Promise> } | null = null + let requestOwners: { at: number; owners: Set } | null = null return { getInstallation: (installationId) => installationFor(`/app/installations/${installationId}`), @@ -231,28 +231,20 @@ export function createGitHubAppMinter(config: { } }, - pendingRequestOwners() { - // One app-wide list, shared by every repo-access check for a minute. - if (!requestOwners || now() - requestOwners.at > 60_000) { - const entry = { - at: now(), - owners: (async () => { - const response = await github('GET', '/app/installation-requests?per_page=100') - const body = InstallationRequests.safeParse(await response.json().catch(() => null)) - if (!response.ok || !body.success) { - throw new Error(`github installation requests failed (${response.status})`) - } - return new Set(body.data.map((r) => r.account.login.toLowerCase())) - })() - } - entry.owners.catch(() => { - if (requestOwners === entry) { - requestOwners = null - } - }) - requestOwners = entry + async pendingRequestOwners() { + // One app-wide list, shared by every repo-access check for a minute: the settled list only, never a + // request in flight (an in-flight one shared across requests hangs them all if its request is cancelled). + if (requestOwners && now() - requestOwners.at <= 60_000) { + return requestOwners.owners } - return requestOwners.owners + const response = await github('GET', '/app/installation-requests?per_page=100') + const body = InstallationRequests.safeParse(await response.json().catch(() => null)) + if (!response.ok || !body.success) { + throw new Error(`github installation requests failed (${response.status})`) + } + const owners = new Set(body.data.map((r) => r.account.login.toLowerCase())) + requestOwners = { at: now(), owners } + return owners }, appRequest: (method, path, body) => github(method, path, body), diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index cb0c92e3f32..557d76112e2 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -67,6 +67,7 @@ import { activeGoldenSnapshots, advanceGoldenImages } from './golden-images' import { nearestRegionEnabled, nearestRegions, sandboxRegions, seedRegion, servedRegions } from './regions' import { handleRuntimeBundleRoute, runtimeBundleFor, runtimeBundleUrl } from './runtime-bundles' import { createIdTokenSource, relayingFetch } from './chatgpt-relay' +import { settledCache } from './settled-cache' import { NO_CREDENTIALS, handleEgressProxy, type CredentialBroker, type ProxiedRoute } from './egress-proxy' import { BillingUnavailableError, @@ -596,7 +597,8 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) => // Account credentials per person, decrypted at most once a minute per isolate; an edit or delete drops it. const ACCOUNT_CACHE_MS = 10_000 -const accountCache = new Map }>() +// Settled values only (settled-cache.ts): a shared in-flight promise hangs every request behind a cancelled one. +const accountCache = settledCache<{ value: string | null; suspect: boolean }>(ACCOUNT_CACHE_MS) function cachedAccountCredential( db: D1Database, keyring: Keyring, @@ -604,15 +606,7 @@ function cachedAccountCredential( agent: 'claude' | 'codex', now: number ): Promise<{ value: string | null; suspect: boolean }> { - const key = `${userId}:${agent}` - const hit = accountCache.get(key) - if (hit && now - hit.at < ACCOUNT_CACHE_MS) { - return hit.value - } - const value = readUsableAgentCredentialState(db, keyring, userId, agent, now) - accountCache.set(key, { at: now, value }) - value.catch(() => accountCache.delete(key)) - return value + return accountCache.get(`${userId}:${agent}`, now, () => readUsableAgentCredentialState(db, keyring, userId, agent, now)) } export function forgetAccountCredential(userId: string, agent: 'claude' | 'codex'): void { accountCache.delete(`${userId}:${agent}`) diff --git a/cloud/apps/sandbox-control/src/secrets.ts b/cloud/apps/sandbox-control/src/secrets.ts index de43e3d3176..506ae6c3377 100644 --- a/cloud/apps/sandbox-control/src/secrets.ts +++ b/cloud/apps/sandbox-control/src/secrets.ts @@ -485,6 +485,8 @@ export async function effectiveSecrets( } let cachedKeyring: { source: string; keyring: Promise; failedAt?: number } | null = null +/** The KMS keyring once loaded (a value, never a promise in flight: see kmsKeyring). */ +let kmsReady: { source: string; keyring: Keyring } | null = null /** How long a failed KMS unwrap is remembered, so an outage is not one KMS round trip per request. */ export const KMS_RETRY_AFTER_MS = 10_000 @@ -505,8 +507,14 @@ function kmsKeyring(env: Env, sealFormat: SealFormat, fetcher: typeof fetch | un const plaintextRetiredId = env.SECRETS_KEK_PLAINTEXT_RETIRED_ID const plaintextRetired = plaintextRetiredId ? `${plaintextRetiredId}\n${env.SECRETS_KEK ?? ''}` : '' const source = `kms\n${activeId}\n${env.SECRETS_KMS_KEY ?? ''}\n${env.SECRETS_KEK_WRAPPED ?? ''}\n${env.SECRETS_KEK_RETIRED_WRAPPED ?? ''}\n${plaintextRetired}\n${sealFormat}` + // WORKER-XREQ-PROMISE: only a keyring that has come out of KMS (or a settled failure) is shared. An + // in-flight load is this request's own: shared, a load whose request was cancelled mid-KMS would hang every + // later request in the isolate forever (seen: secret routes through the egress proxy stuck until cancelled). + if (kmsReady?.source === source) { + return Promise.resolve(kmsReady.keyring) + } const cached = cachedKeyring - if (cached?.source === source && (cached.failedAt === undefined || Date.now() - cached.failedAt < KMS_RETRY_AFTER_MS)) { + if (cached?.source === source && cached.failedAt !== undefined && Date.now() - cached.failedAt < KMS_RETRY_AFTER_MS) { return cached.keyring } const load = async (): Promise => { @@ -543,6 +551,9 @@ function kmsKeyring(env: Env, sealFormat: SealFormat, fetcher: typeof fetch | un } } const entry: NonNullable = { source, keyring: load() } + entry.keyring.then((keyring) => { + kmsReady = { source, keyring } + }, () => undefined) entry.keyring.catch((error: unknown) => { entry.failedAt = Date.now() const kms = error instanceof SecretsKmsError ? error : null diff --git a/cloud/apps/sandbox-control/src/session-env.ts b/cloud/apps/sandbox-control/src/session-env.ts index f3cce676a91..d71cab03def 100644 --- a/cloud/apps/sandbox-control/src/session-env.ts +++ b/cloud/apps/sandbox-control/src/session-env.ts @@ -1,6 +1,7 @@ // What one sandbox session's agents see: the resolved secret store (precedence applied), provider // presets filled in, and with egress placeholders on, model keys swapped for placeholders. The same // answer drives the egress allowlist and the proxy's credential routes, at boot and on refresh. +import { settledCache } from './settled-cache' import type { LifecycleDeps } from './lifecycle' import { agentModesFor, withoutSignInCredentials, type AgentMode } from './agent-sources' import { accountProvider } from './account-providers' @@ -46,32 +47,17 @@ export async function resolvedProviderEnv( // decrypt per session-minute instead of per model request. Isolate memory only; a secret edit // drops the sandbox's entry (in this isolate) so a rotated or deleted key stops being sent. const PROVIDER_ENV_CACHE_MS = 60_000 -const providerEnvCache = new Map }>() +// Settled values only (settled-cache.ts): a shared in-flight promise hangs every request behind a cancelled one. +const providerEnvCache = settledCache(PROVIDER_ENV_CACHE_MS) export function cachedProviderEnv(db: D1Database, keyring: Keyring, row: SandboxRow, now: number): Promise { // Visibility is part of the key: sharing a workspace stops its owner's personal keys at once (SEC-5). const key = `${row.id}:${row.session_id ?? ''}:${row.visibility}` - const hit = providerEnvCache.get(key) - if (hit && now - hit.at < PROVIDER_ENV_CACHE_MS) { - return hit.value - } - for (const [cached, entry] of providerEnvCache) { - if (now - entry.at >= PROVIDER_ENV_CACHE_MS) { - providerEnvCache.delete(cached) - } - } - const value = resolvedProviderEnv(db, keyring, row) - providerEnvCache.set(key, { at: now, value }) - value.catch(() => providerEnvCache.delete(key)) - return value + return providerEnvCache.get(key, now, () => resolvedProviderEnv(db, keyring, row)) } export function forgetProviderEnv(sandboxId: string): void { - for (const key of providerEnvCache.keys()) { - if (key.startsWith(`${sandboxId}:`)) { - providerEnvCache.delete(key) - } - } + providerEnvCache.deleteWhere((key) => key.startsWith(`${sandboxId}:`)) } /** Placeholders are switched on for this account (SECRETS_EGRESS_PLACEHOLDERS, minus the per-team kill switch). */ diff --git a/cloud/apps/sandbox-control/src/settled-cache.ts b/cloud/apps/sandbox-control/src/settled-cache.ts new file mode 100644 index 00000000000..09ddb9a2fd1 --- /dev/null +++ b/cloud/apps/sandbox-control/src/settled-cache.ts @@ -0,0 +1,42 @@ +// WORKER-XREQ-PROMISE: an isolate serves many requests, and a promise one request starts is bound to that +// request's I/O. If it is cancelled (its client went away) while the promise waits on D1, KMS or fetch, the +// promise never settles, and every later request awaiting the same promise hangs until the runtime cancels +// it too. Module-level caches must therefore hold settled VALUES only, never in-flight promises: a request +// that misses loads for itself (a few duplicate loads on a cold isolate are the price). + +export type SettledCache = { + /** The cached value while fresh, else `load()` (this request's own), cached once it resolves. */ + get(key: string, now: number, load: () => Promise): Promise + delete(key: string): void + deleteWhere(match: (key: string) => boolean): void +} + +export function settledCache(ttlMs: number, maxEntries = 1000): SettledCache { + const entries = new Map() + return { + async get(key, now, load) { + const hit = entries.get(key) + if (hit && now - hit.at < ttlMs) { + return hit.value + } + const value = await load() + if (entries.size >= maxEntries) { + for (const [stale, entry] of entries) { + if (now - entry.at >= ttlMs) { + entries.delete(stale) + } + } + } + entries.set(key, { at: now, value }) + return value + }, + delete: (key) => void entries.delete(key), + deleteWhere(match) { + for (const key of [...entries.keys()]) { + if (match(key)) { + entries.delete(key) + } + } + } + } +} diff --git a/cloud/apps/sandbox-control/src/share-gateway.ts b/cloud/apps/sandbox-control/src/share-gateway.ts index f568b66ffc6..c80ccfcc02f 100644 --- a/cloud/apps/sandbox-control/src/share-gateway.ts +++ b/cloud/apps/sandbox-control/src/share-gateway.ts @@ -63,8 +63,10 @@ export type ShareGatewayDeps = { } type Resolved = { link: ShareLinkRow; sandbox: SandboxRow } -const linkCache = new Map }>() -const routeCache = new Map }>() +// Settled values only (settled-cache.ts): an in-flight load shared across requests hangs them all if its own +// request is cancelled. +const linkCache = new Map() +const routeCache = new Map() const rates = new Map() export function forgetShareLink(id: string): void { @@ -103,13 +105,13 @@ async function loadResolved(db: D1Database, id: string): Promise { const hit = linkCache.get(id) if (!fresh && hit && now - hit.at < LINK_CACHE_MS) { - return hit.value + return Promise.resolve(hit.value) } prune(linkCache, now, LINK_CACHE_MS) - const value = loadResolved(db, id) - linkCache.set(id, { at: now, value }) - value.catch(() => linkCache.delete(id)) - return value + return loadResolved(db, id).then((value) => { + linkCache.set(id, { at: now, value }) + return value + }) } /** The proxy's public route for this session; adds port 6769 to sandboxes created before share links. */ @@ -118,7 +120,7 @@ function proxyRoute(deps: ShareGatewayDeps, sandbox: SandboxRow): Promise { @@ -134,9 +136,10 @@ function proxyRoute(deps: ShareGatewayDeps, sandbox: SandboxRow): Promise routeCache.delete(key)) - return url + return url.then((value) => { + routeCache.set(key, { at: now, url: value }) + return value + }) } function requestCookies(request: Request): [string, string][] { diff --git a/cloud/apps/sandbox-control/test/secrets-kms.test.ts b/cloud/apps/sandbox-control/test/secrets-kms.test.ts index 1c61e340134..40c94dcea62 100644 --- a/cloud/apps/sandbox-control/test/secrets-kms.test.ts +++ b/cloud/apps/sandbox-control/test/secrets-kms.test.ts @@ -2,7 +2,8 @@ import { createCipheriv, createDecipheriv, generateKeyPairSync, randomBytes, typ import { jwtVerify } from 'jose' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { START_COMMAND } from '../src/sandbox-vm-commands' -import { KMS_RETRY_AFTER_MS } from '../src/secrets' +import { KMS_RETRY_AFTER_MS, keyringFor } from '../src/secrets' +import type { Env } from '../src/env' import { createKeyring } from '../src/secrets-crypto' import { createKekUnwrapper, kekWrapAad, SecretsKmsError } from '../src/secrets-kms' import { createHarness } from './harness' @@ -370,3 +371,20 @@ describe('secret store with SECRETS_KEK_SOURCE=kms', () => { expect(h.raw.prepare('SELECT * FROM secrets').all()).toEqual(before) }) }) + +describe('WORKER-XREQ-PROMISE: no request ever waits on another request’s KMS load', () => { + it('two loads at once on a cold isolate each call KMS; once one has a keyring, later calls reuse it', async () => { + const env = { ...kmsEnv(), SECRETS_KEK_WRAPPED: kms.wrap(K1, 'k1'), SECRETS_KEK_ID: 'k1', SECRETS_KMS_KEY: KEY_NAME } as unknown as Env + // A source no earlier test loaded: a cold keyring. + const cold = { ...env, SECRETS_KEK_RETIRED_WRAPPED: JSON.stringify({ kx: kms.wrap(K2, 'kx') }) } as unknown as Env + const before = kms.state.decrypts + const [a, b] = await Promise.all([keyringFor(cold, kms.fetch)!, keyringFor(cold, kms.fetch)!]) + expect(a).toBeTruthy() + expect(b).toBeTruthy() + // Two keys per load (active + retired) and two loads: neither request waited on the other's. + expect(kms.state.decrypts - before).toBe(4) + const settled = kms.state.decrypts + await keyringFor(cold, kms.fetch) + expect(kms.state.decrypts).toBe(settled) + }) +}) diff --git a/cloud/apps/sandbox-control/test/settled-cache.test.ts b/cloud/apps/sandbox-control/test/settled-cache.test.ts new file mode 100644 index 00000000000..dfcb6582cd7 --- /dev/null +++ b/cloud/apps/sandbox-control/test/settled-cache.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest' +import { settledCache } from '../src/settled-cache' + +describe('settledCache (WORKER-XREQ-PROMISE)', () => { + it('never hands a request another request’s in-flight load; shares the value once settled', async () => { + const cache = settledCache(1000) + let loads = 0 + let release: (value: number) => void = () => {} + const slow = () => new Promise((resolve) => ((loads++), (release = resolve))) + const first = cache.get('k', 0, slow) + // A second request while the first is loading loads for itself. + const second = cache.get('k', 1, async () => (loads++, 2)) + expect(await second).toBe(2) + release(1) + expect(await first).toBe(1) + expect(loads).toBe(2) + // Settled now: fresh hits reuse the value, stale ones load again. + expect(await cache.get('k', 10, async () => (loads++, 3))).toBe(1) + expect(await cache.get('k', 5000, async () => (loads++, 4))).toBe(4) + expect(loads).toBe(3) + }) + + it('a failed load is not cached', async () => { + const cache = settledCache(1000) + await expect(cache.get('k', 0, async () => Promise.reject(new Error('down')))).rejects.toThrow('down') + expect(await cache.get('k', 1, async () => 7)).toBe(7) + }) +})