Merge remote-tracking branch 'private/cloud/integration' into cloud/integration

This commit is contained in:
Neil
2026-11-09 06:08:17 -08:00
8 changed files with 209 additions and 26 deletions
+5 -3
View File
@@ -4,8 +4,10 @@
#
# - Booted from an environment build (ORCA_ENV_REPO_DIR set): the repo is already cloned with its
# dependencies installed under /vercel/sandbox/repos. Link it as the project (a link, not a move,
# so absolute paths baked into installed dependencies keep working) and bring the requested
# branch up to date. A failed fetch keeps the build's commit: the workspace still opens.
# so absolute paths baked into installed dependencies keep working). No fetch when the build is
# already on the requested branch: Orca fetches the base right before it adds the workspace's
# worktree, so a fetch here would only delay orcad (measured ~0.5-1 s). Another branch is fetched
# and checked out; if that fails the workspace still opens at the build's commit.
# - Otherwise clone ORCA_REPO_URL here so a repo with no commits yet also opens: it gets an empty
# first commit on the requested branch, which Orca needs to create the workspace's worktree.
set -uo pipefail
@@ -28,7 +30,7 @@ first_commit() {
if [ ! -e "$P" ] && [ -n "${ORCA_ENV_REPO_DIR:-}" ] && [ -d "$ROOT/$ORCA_ENV_REPO_DIR/.git" ]; then
ln -s "$ROOT/$ORCA_ENV_REPO_DIR" "$P"
if [ -n "$ref" ]; then
if [ -n "$ref" ] && [ "$(git -C "$P" symbolic-ref --quiet --short HEAD 2>/dev/null)" != "$ref" ]; then
if timeout 60 git "${auth[@]}" -C "$P" fetch --quiet origin "+refs/heads/$ref:refs/remotes/origin/$ref"; then
# -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.
git -C "$P" checkout --quiet -f -B "$ref" "origin/$ref" -- ||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
-- The warm pool asks "was this environment used lately?" on every create and cron tick.
CREATE INDEX IF NOT EXISTS sandboxes_environment_created ON sandboxes (environment_id, created_at);
@@ -23,6 +23,7 @@ import type { GoldenImageProviderApi } from './golden-image-provider'
import { assertStartsOpen, type GuardrailConfig, DEFAULT_GUARDRAILS } from './guardrails'
import { compileNetworkPolicy, gitBasicAuthorization, type CredentialRoute } from './network-policy'
import { ProviderError, type SandboxProviderApi } from './sandbox-provider'
import { ORCAD_PORT, startOrcad } from './sandbox-vm-commands'
import type { Keyring } from './secrets-crypto'
export const BUILD_DEADLINE_MS = 45 * 60_000
@@ -248,7 +249,13 @@ export async function startBuild(deps: BuildDeps, caller: SandboxCaller, environ
return await bootBuild(deps, row, config)
} catch (error) {
const current = (await getBuild(deps.db, environment.id, id)) ?? row
await failBuild(deps, current, 'boot', error instanceof ProviderError ? `provider_${error.status}` : 'boot_failed')
const code =
error instanceof ProviderError
? `provider_${error.status}`
: error instanceof EnvironmentError && error.reason === 'github_unavailable'
? 'github_unavailable'
: 'boot_failed'
await failBuild(deps, current, code === 'github_unavailable' ? 'clone' : 'boot', code)
throw error
}
}
@@ -258,7 +265,13 @@ async function bootBuild(deps: BuildDeps, row: BuildRow, config: BuildConfig): P
const lines: string[] = []
for (const [index, repo] of config.repos.entries()) {
let header = ''
const minted = deps.github ? await deps.github.tokenForRepo(repo.url, row.account_id).catch(() => null) : null
// A minting error is not "public repo": cloning anonymously would end in a misleading 404 (seen live).
const minted = deps.github
? await deps.github.tokenForRepo(repo.url, row.account_id).catch((error: unknown) => {
log('environment_build_github_token_failed', { buildId: row.id, error: String(error).slice(0, 120) })
throw new EnvironmentError('conflict', 409, 'github_unavailable')
})
: null
if (minted) {
const ph = placeholder(row.id, index)
credentials.push({
@@ -400,8 +413,55 @@ async function finalize(deps: BuildDeps, row: BuildRow, exitCode: number): Promi
}
}
/**
* Boot the new image once and require orcad to answer before any workspace gets it: an install script
* that breaks Orca fails its own build instead of every later create. The first boot of a snapshot is
* also its slowest (provider-side hydration), so a user never pays it.
*/
async function smokeBoot(deps: BuildDeps, row: BuildRow, snapshotId: string): Promise<void> {
// Unique per attempt: a recovery pass racing this one must not delete our box (or we theirs).
const name = `${row.provider_name}-smoke-${crypto.getRandomValues(new Uint32Array(1))[0]!.toString(36)}`
try {
const box = await deps.provider.createSandbox({
name,
snapshotId,
vcpus: 2,
region: deps.config.region,
timeoutMs: 5 * 60_000,
ports: [ORCAD_PORT],
networkPolicy: compileNetworkPolicy({ mode: 'allowlist' }),
tags: { orcaEnvBuildSmoke: row.id, orcaEnv: deps.config.environment },
snapshotExpirationMs: 0,
persistent: false
})
await startOrcad(deps.provider, box, { sandboxId: `smoke-${row.id}` })
} finally {
await deps.provider.deleteSandbox(name).catch(() => undefined)
}
}
async function completeBuild(deps: BuildDeps, row: BuildRow, snapshotId: string): Promise<BuildRow> {
await deps.provider.deleteBuildSandbox(row.provider_name).catch(() => undefined)
// The smoke boot can take minutes: mark progress so no watcher takes this build for interrupted.
row = (await transition(deps.db, row, {}, deps.now())) ?? row
try {
await smokeBoot(deps, row, snapshotId)
} catch (error) {
if (error instanceof ProviderError) {
// The provider hiccuped, not the image: never throw away a finished build for that.
log('environment_build_smoke_skipped', { buildId: row.id, status: error.status })
} else {
log('environment_build_smoke_failed', { buildId: row.id, error: String(error).slice(0, 200) })
const failed = await transition(deps.db, row, { status: 'failed', failed_step: 'snapshot', error: 'smoke_failed', finished_at: deps.now() }, deps.now())
if (failed) {
// Ours to delete only when this pass is the one that failed the build.
await deps.provider.deleteSnapshot(snapshotId).catch(() => undefined)
log('environment_build_failed', { buildId: row.id, number: row.number, step: 'snapshot', error: 'smoke_failed' })
return failed
}
return (await getBuild(deps.db, row.environment_id, row.id)) ?? row
}
}
const now = deps.now()
const done = await transition(deps.db, row, { status: 'succeeded', snapshot_id: snapshotId, finished_at: now }, now)
const alive = await deps.db
@@ -409,8 +469,12 @@ async function completeBuild(deps: BuildDeps, row: BuildRow, snapshotId: string)
.bind(row.environment_id)
.first<{ ok: number }>()
if (!done || !alive) {
// Failed meanwhile (deadline) or the environment was deleted: the snapshot is ours to clean up.
await deps.provider.deleteSnapshot(snapshotId).catch(() => undefined)
// Failed meanwhile (deadline) or the environment was deleted: the snapshot is ours to clean up,
// unless a racing pass already completed the build with this very snapshot.
const current = done ?? (await getBuild(deps.db, row.environment_id, row.id))
if (done || current?.snapshot_id !== snapshotId) {
await deps.provider.deleteSnapshot(snapshotId).catch(() => undefined)
}
if (done) {
await deps.db.prepare('UPDATE environment_builds SET snapshot_deleted_at = ? WHERE id = ?').bind(now, row.id).run()
}
+6 -4
View File
@@ -368,11 +368,13 @@ export async function createSandbox(
const machineSize = source?.machineSize ?? request.machineSize
await timer.time('entitlement', () => requireStart(deps, caller.accountId, caller.userId, machineSize))
const region = request.region ?? deps.config.defaultRegion
// Pooled VMs run the plain golden image: a create that boots an environment build skips the pool.
// The pool keeps warm VMs per image: the golden one, and the active build of recently used environments.
const pooled =
options.pool === false || source
options.pool === false
? null
: await timer.time('pool', () => claimPooledVm(deps, machineSize, region).catch(() => null))
: await timer.time('pool', () =>
claimPooledVm(deps, machineSize, region, source?.snapshotId ?? deps.config.goldenSnapshotId).catch(() => null)
)
if (deps.config.pool) {
// Refill behind the response, on a miss too (empty, or stale after a golden rotation), so the next
// create finds one without waiting for the cron.
@@ -407,7 +409,7 @@ export async function createSandbox(
deps.now()
).catch(async (error: unknown) => {
if (pooled) {
await deletePooledVm(deps, pooled.provider_name).catch(() => undefined)
await deletePooledVm(deps, pooled.provider_name, pooled.snapshot_id).catch(() => undefined)
}
throw error
})
+89 -14
View File
@@ -19,6 +19,15 @@ export const DEFAULT_POOL_MAX_AGE_MS = 20 * 60_000
/** Provider timeout for a pooled VM: outlives max age + one cron period, so the cron deletes it first. */
const POOL_VM_TIMEOUT_MS = DEFAULT_POOL_MAX_AGE_MS + 15 * 60_000
const POOLED_SIZE: MachineSize = 'standard'
/** Ready VMs per hot environment build (its own image: the repo prebuilt, deps installed). */
export const BUILD_POOL_SIZE = 1
/** An environment build is hot while a workspace booted from its environment, or it finished, this recently. */
export const HOT_BUILD_WINDOW_MS = 2 * 60 * 60_000
const MAX_HOT_BUILDS = 20
/** One org with many environments must not take the whole hot-build pool. */
const MAX_HOT_BUILDS_PER_ACCOUNT = 3
/** VMs booted per maintainer pass; the cron finishes the rest (a waitUntil pass has ~30 s). */
const MAX_BOOTS_PER_TICK = 5
const VCPUS: Record<MachineSize, number> = { standard: 4, large: 8 }
export type PoolDeps = {
@@ -71,7 +80,13 @@ function poolId(): string {
* Takes one ready VM for this size/region on the current golden image, or null. One statement, so two
* creates never get the same VM.
*/
export async function claimPooledVm(deps: PoolDeps, machineSize: MachineSize, region: string): Promise<PooledVm | null> {
export async function claimPooledVm(
deps: PoolDeps,
machineSize: MachineSize,
region: string,
/** The image the caller would boot: the golden image, or an environment build's snapshot. */
snapshotId: string = deps.config.goldenSnapshotId
): Promise<PooledVm | null> {
const pool = deps.config.pool
if (!pool || machineSize !== POOLED_SIZE || region !== deps.config.defaultRegion) {
return null
@@ -84,7 +99,7 @@ export async function claimPooledVm(deps: PoolDeps, machineSize: MachineSize, re
ORDER BY created_at LIMIT 1)
RETURNING *`
)
.bind(machineSize, region, deps.config.goldenSnapshotId, deps.now() - pool.maxAgeMs)
.bind(machineSize, region, snapshotId, deps.now() - pool.maxAgeMs)
.first<PooledVm>()
}
@@ -123,20 +138,66 @@ async function takeLease(deps: PoolDeps): Promise<boolean> {
return taken !== null
}
/**
* Images worth a warm VM: the golden image (`size`), plus the active build of every environment in
* use lately (BUILD_POOL_SIZE each), so a create from an org environment skips the provider boot too.
*/
async function poolTargets(deps: PoolDeps, size: number): Promise<Map<string, number>> {
const targets = new Map<string, number>([[deps.config.goldenSnapshotId, size]])
const since = deps.now() - HOT_BUILD_WINDOW_MS
// Hot = a workspace was created from the environment lately (not merely built). Most recent first,
// so the chosen set is stable tick to tick; capped per account and overall.
const hot = await deps.db
.prepare(
`SELECT b.snapshot_id AS snapshot_id, e.account_id AS account_id,
(SELECT MAX(s.created_at) FROM sandboxes s WHERE s.environment_id = e.id) AS used_at
FROM environments e JOIN environment_builds b ON b.id = e.active_build_id
WHERE e.deleted_at IS NULL AND b.status = 'succeeded' AND b.snapshot_id IS NOT NULL
AND b.snapshot_deleted_at IS NULL AND json_extract(b.config, '$.machineSize') = ?
AND used_at > ?
ORDER BY used_at DESC LIMIT ?`
)
.bind(POOLED_SIZE, since, MAX_HOT_BUILDS * 4)
.all<{ snapshot_id: string; account_id: string }>()
.catch(() => ({ results: [] as { snapshot_id: string; account_id: string }[] }))
const perAccount = new Map<string, number>()
let hotCount = 0
for (const row of hot.results) {
const count = perAccount.get(row.account_id) ?? 0
if (count >= MAX_HOT_BUILDS_PER_ACCOUNT || hotCount >= MAX_HOT_BUILDS || targets.has(row.snapshot_id)) {
continue
}
perAccount.set(row.account_id, count + 1)
hotCount++
targets.set(row.snapshot_id, Math.max(targets.get(row.snapshot_id) ?? 0, BUILD_POOL_SIZE))
}
return targets
}
async function maintain(deps: PoolDeps): Promise<PoolTick> {
const now = deps.now()
const pool = deps.config.pool
const draining = !pool || (deps.config.guardrails ? await killSwitchOn(deps.db, deps.config.guardrails) : false)
const all = (await deps.db.prepare(`SELECT * FROM sandbox_pool WHERE status != 'lease'`).all<PooledVm>()).results
const maxAge = pool?.maxAgeMs ?? DEFAULT_POOL_MAX_AGE_MS
const targets = draining || !pool ? new Map<string, number>() : await poolTargets(deps, pool.size)
const expired = (vm: PooledVm) =>
draining ||
vm.snapshot_id !== deps.config.goldenSnapshotId ||
!targets.has(vm.snapshot_id) ||
now - vm.created_at > maxAge ||
(vm.status === 'warming' && now - vm.updated_at > 5 * 60_000)
// Overlapping ticks can overshoot; the oldest extras go first.
// Overlapping ticks can overshoot; the oldest extras go first (per image).
const keep = all.filter((vm) => !expired(vm)).sort((a, b) => b.created_at - a.created_at)
const stale = [...all.filter(expired), ...keep.slice(pool?.size ?? 0)]
const extras: PooledVm[] = []
const kept = new Map<string, number>()
for (const vm of keep) {
const count = (kept.get(vm.snapshot_id) ?? 0) + 1
kept.set(vm.snapshot_id, count)
if (count > (targets.get(vm.snapshot_id) ?? 0)) {
extras.push(vm)
}
}
const stale = [...all.filter(expired), ...extras]
let recycled = 0
for (const vm of stale) {
// Remove the row first: a claim can no longer take it, and a failed delete is retried next tick
@@ -146,7 +207,7 @@ async function maintain(deps: PoolDeps): Promise<PoolTick> {
continue
}
try {
await deletePooledVm(deps, vm.provider_name)
await deletePooledVm(deps, vm.provider_name, vm.snapshot_id)
recycled += 1
} catch (error) {
await insertRow(deps.db, { ...vm, updated_at: now })
@@ -154,11 +215,20 @@ async function maintain(deps: PoolDeps): Promise<PoolTick> {
}
}
const live = all.length - recycled
if (draining || !pool || live >= pool.size) {
if (draining || !pool) {
return { created: 0, recycled, ready: Math.max(0, live) }
}
const wanted = pool.size - live
const results = await Promise.allSettled(Array.from({ length: wanted }, () => bootPooledVm(deps)))
const boots: string[] = []
for (const [snapshotId, want] of targets) {
const have = Math.min(kept.get(snapshotId) ?? 0, want)
for (let i = have; i < want; i++) {
boots.push(snapshotId)
}
}
if (boots.length === 0) {
return { created: 0, recycled, ready: Math.max(0, live) }
}
const results = await Promise.allSettled(boots.slice(0, MAX_BOOTS_PER_TICK).map((snapshotId) => bootPooledVm(deps, snapshotId)))
const created = results.filter((r) => r.status === 'fulfilled').length
for (const failure of results.filter((r) => r.status === 'rejected')) {
console.log(JSON.stringify({ event: 'pool_boot_failed', error: String(failure.reason).slice(0, 200) }))
@@ -166,7 +236,7 @@ async function maintain(deps: PoolDeps): Promise<PoolTick> {
return { created, recycled, ready: live + created }
}
async function bootPooledVm(deps: PoolDeps): Promise<void> {
async function bootPooledVm(deps: PoolDeps, snapshotId: string): Promise<void> {
const id = poolId()
const now = deps.now()
const row: PooledVm = {
@@ -174,7 +244,7 @@ async function bootPooledVm(deps: PoolDeps): Promise<void> {
provider_name: `orca-${deps.config.environment}-${id}`,
machine_size: POOLED_SIZE,
region: deps.config.defaultRegion,
snapshot_id: deps.config.goldenSnapshotId,
snapshot_id: snapshotId,
status: 'warming',
session_id: null,
session_started_at: null,
@@ -207,16 +277,21 @@ async function bootPooledVm(deps: PoolDeps): Promise<void> {
.run()
} catch (error) {
await deps.db.prepare('DELETE FROM sandbox_pool WHERE id = ?').bind(id).run()
await deletePooledVm(deps, row.provider_name).catch(() => undefined)
await deletePooledVm(deps, row.provider_name, row.snapshot_id).catch(() => undefined)
throw error
}
}
/** A pooled VM never ran user code; delete it and any automatic snapshot a provider timeout left. */
export async function deletePooledVm(deps: Pick<PoolDeps, 'provider' | 'config'>, name: string): Promise<void> {
export async function deletePooledVm(
deps: Pick<PoolDeps, 'provider' | 'config'>,
name: string,
/** The image it booted from (golden or an environment build) is shared: never deleted here. */
sourceSnapshotId?: string
): Promise<void> {
await deps.provider.deleteSandbox(name)
for (const snapshot of await deps.provider.listSnapshots(name)) {
if (snapshot.status !== 'deleted' && snapshot.id !== deps.config.goldenSnapshotId) {
if (snapshot.status !== 'deleted' && snapshot.id !== deps.config.goldenSnapshotId && snapshot.id !== sourceSnapshotId) {
await deps.provider.deleteSnapshot(snapshot.id)
}
}
@@ -83,6 +83,16 @@ describe('org environments', () => {
expect(lines.at(-1)).toEqual({ type: 'end' })
})
it('fails a build whose image cannot start orcad, keeping the active one', async () => {
const { h, adminCall, envId, build } = await setup()
const good = await build(0)
h.vercel.failStart = true
const broken = await build(0)
expect(broken).toMatchObject({ status: 'failed', error: 'smoke_failed', failedStep: 'snapshot', activatable: false })
expect((await adminCall('GET', `/v1/environments/${envId}`)).body.environment.activeBuildId).toBe(good.id)
expect([...h.vercel.boxes.keys()].filter((name) => name.includes('envbuild'))).toEqual([])
})
it('refuses a second concurrent build and can cancel one', async () => {
const { adminCall, envId } = await setup()
const started = await adminCall('POST', `/v1/environments/${envId}/builds`)
@@ -20,6 +20,34 @@ async function pooledHarness(size = '2') {
}
describe('warm pool', () => {
it('keeps a warm VM for the active build of an environment in use, and a create from it claims that VM', async () => {
const { h, deps, poolRows } = await pooledHarness('1')
h.vercel.buildResult = JSON.stringify({ repos: [{ url: 'https://github.com/acme/web.git', dir: 'acme/web', branch: 'main', commit: 'a'.repeat(40), lockfiles: {} }] })
const env = await h.call('POST', '/v1/environments', { body: { name: 'Default', repos: [{ url: 'acme/web' }] } })
const started = await h.call('POST', `/v1/environments/${env.body.environment.id}/builds`)
;[...h.vercel.buildCommands.values()].at(-1)!.exitCode = 0
const build = (await h.call('GET', `/v1/environments/${env.body.environment.id}/builds/${started.body.build.id}`)).body.build
expect(build.status).toBe('succeeded')
const snapshot = h.raw.prepare('SELECT snapshot_id FROM environment_builds WHERE id = ?').get(build.id) as { snapshot_id: string }
// Only built, never used: no warm VM for it yet.
await maintainPool(deps())
expect(poolRows().map((r) => r.snapshot_id)).toEqual([GOLDEN])
// The first create from the environment misses (and boots from the build); then it is hot.
const first = await h.call('POST', '/v1/sandboxes', { body: { ...create, workspaceId: 'ws-first', repo: { url: 'https://github.com/acme/web.git' } } })
expect(first.body.sandbox.environmentBuildId).toBe(build.id)
await maintainPool(deps())
const images = poolRows().map((r) => r.snapshot_id).sort()
expect(images).toEqual([GOLDEN, snapshot.snapshot_id].sort())
const pooledFromBuild = poolRows().find((r) => r.snapshot_id === snapshot.snapshot_id)!.id
const res = await h.call('POST', '/v1/sandboxes', { body: { ...create, repo: { url: 'https://github.com/acme/web.git' } } })
expect(res.status).toBe(200)
expect(res.body.sandbox).toMatchObject({ id: pooledFromBuild, environmentBuildId: build.id })
// Two hours without use: the build's warm VM is recycled, the golden pool stays.
h.advance(3 * 60 * MIN)
await maintainPool(deps())
expect(poolRows().map((r) => r.snapshot_id)).toEqual([GOLDEN])
})
it('is off unless SANDBOX_POOL_SIZE is a positive integer, and capped', () => {
expect(poolConfigFromEnv({})).toBeUndefined()
expect(poolConfigFromEnv({ SANDBOX_POOL_SIZE: '0' })).toBeUndefined()