Merge pull request #801 from nwparker/cloud/no-cross-request-promises

fix(cloud): WORKER-XREQ-PROMISE module caches hold settled values, never another request's in-flight promise
This commit is contained in:
Neil
2026-11-15 14:22:50 -08:00
committed by GitHub
10 changed files with 151 additions and 82 deletions
@@ -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<string> | null = null
let signingKey: CryptoKey | null = null
async function mint(): Promise<string> {
let account: z.infer<typeof ServiceAccount>
@@ -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()
}
}
+10 -13
View File
@@ -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<HostedSandboxTiming | undefined> } | 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<HostedSandboxTiming | undefined> {
export async function cachedCreateTiming(db: D1Database, now: number): Promise<HostedSandboxTiming | undefined> {
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
}
+14 -22
View File
@@ -177,7 +177,7 @@ export function createGitHubAppMinter(config: {
metadataTokens.set(installationId, token)
return token.token
}
let requestOwners: { at: number; owners: Promise<Set<string>> } | null = null
let requestOwners: { at: number; owners: Set<string> } | 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),
+4 -10
View File
@@ -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<string, { at: number; value: Promise<{ value: string | null; suspect: boolean }> }>()
// 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}`)
+12 -1
View File
@@ -485,6 +485,8 @@ export async function effectiveSecrets(
}
let cachedKeyring: { source: string; keyring: Promise<Keyring>; 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<Keyring> => {
@@ -543,6 +551,9 @@ function kmsKeyring(env: Env, sealFormat: SealFormat, fetcher: typeof fetch | un
}
}
const entry: NonNullable<typeof cachedKeyring> = { 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
+5 -19
View File
@@ -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<string, { at: number; value: Promise<ProviderEnv> }>()
// Settled values only (settled-cache.ts): a shared in-flight promise hangs every request behind a cancelled one.
const providerEnvCache = settledCache<ProviderEnv>(PROVIDER_ENV_CACHE_MS)
export function cachedProviderEnv(db: D1Database, keyring: Keyring, row: SandboxRow, now: number): Promise<ProviderEnv> {
// 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). */
@@ -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<V> = {
/** The cached value while fresh, else `load()` (this request's own), cached once it resolves. */
get(key: string, now: number, load: () => Promise<V>): Promise<V>
delete(key: string): void
deleteWhere(match: (key: string) => boolean): void
}
export function settledCache<V>(ttlMs: number, maxEntries = 1000): SettledCache<V> {
const entries = new Map<string, { at: number; value: V }>()
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)
}
}
}
}
}
+14 -11
View File
@@ -63,8 +63,10 @@ export type ShareGatewayDeps = {
}
type Resolved = { link: ShareLinkRow; sandbox: SandboxRow }
const linkCache = new Map<string, { at: number; value: Promise<Resolved | null> }>()
const routeCache = new Map<string, { at: number; url: Promise<string> }>()
// 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<string, { at: number; value: Resolved | null }>()
const routeCache = new Map<string, { at: number; url: string }>()
const rates = new Map<string, { at: number; count: number }>()
export function forgetShareLink(id: string): void {
@@ -103,13 +105,13 @@ async function loadResolved(db: D1Database, id: string): Promise<Resolved | null
function resolve(db: D1Database, id: string, now: number, fresh = false): Promise<Resolved | null> {
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<string
const now = deps.now()
const hit = routeCache.get(key)
if (hit && now - hit.at < ROUTE_CACHE_MS) {
return hit.url
return Promise.resolve(hit.url)
}
prune(routeCache, now, ROUTE_CACHE_MS)
const url = (async () => {
@@ -134,9 +136,10 @@ function proxyRoute(deps: ShareGatewayDeps, sandbox: SandboxRow): Promise<string
}
return added.url
})()
routeCache.set(key, { at: now, url })
url.catch(() => routeCache.delete(key))
return url
return url.then((value) => {
routeCache.set(key, { at: now, url: value })
return value
})
}
function requestCookies(request: Request): [string, string][] {
@@ -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)
})
})
@@ -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<number>(1000)
let loads = 0
let release: (value: number) => void = () => {}
const slow = () => new Promise<number>((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<number>(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)
})
})