diff --git a/cloud/apps/sandbox-control/image/env/workspace-prelude.sh b/cloud/apps/sandbox-control/image/env/workspace-prelude.sh index 676f2d42fed..694ee3e485d 100644 --- a/cloud/apps/sandbox-control/image/env/workspace-prelude.sh +++ b/cloud/apps/sandbox-control/image/env/workspace-prelude.sh @@ -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" -- || diff --git a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts index e9a70ef116c..999f1e2b4b5 100644 --- a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts +++ b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts @@ -6,4 +6,4 @@ export const PROVISION_SCRIPT: string = "#!/usr/bin/env bash\n# Runs once inside export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents). Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"}\\n' \"$STATE/ready.json\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/runtime/orcad/orcad-server.js\" \\\n --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\nfor _ in $(seq 1 1200); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.05\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\ndir=\"/dev/shm/orca-env-$(id -u)\"\nif [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex provider block (no secret values: env_key names the variable) ----\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop both managed blocks\n awk '/^# >>> orca-cloud managed/{skip=1} !skip{print} /^# <<< orca-cloud managed/{skip=0}' \"$1\"\n}\nif [ -n \"$openai_base_url\" ] || grep -q '^# >>> orca-cloud managed' \"$codex_config\" 2>/dev/null; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then\n # Top-level keys must precede every table; skip ours if the user already chose a provider/model.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n {\n printf '# >>> orca-cloud managed (Orca Cloud provider; edit in Orca settings)\\n'\n if ! grep -Eq '^[[:space:]]*model_provider[[:space:]]*=' <<<\"$head_keys\"; then\n printf 'model_provider = \"orca_cloud\"\\n'\n fi\n if [ -n \"$openai_model\" ] && ! grep -Eq '^[[:space:]]*model[[:space:]]*=' <<<\"$head_keys\"; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n } >\"$next\"\n else\n cat \"$user_part\" >\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n"} export const ENVIRONMENT_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Environment build (\"Cloud Computer\"), run by the control plane in a VM booted from the golden image.\n# Clones every repo, runs the org's install script once with `set -euo pipefail`, then records what it\n# built from (commit + lockfile blob ids per repo) so the control plane can tell when a rebuild is due.\n# Everything printed here streams live to the desktop build log.\n#\n# Env from the control plane (validated there): ORCA_BUILD_REPOS (`|||\n# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER, plus\n# the org secrets the environment names. `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result.\nset -uo pipefail\numask 022\n# One stream: the provider replays stdout and stderr separately after the fact, so a failed build's\n# log would read out of order. `::orca-error::` lines carry Orca's own failure explanations.\nexec 2>&1\nOUT=/tmp/orca-build\nROOT=/vercel/sandbox/repos\nmkdir -p \"$OUT\" \"$ROOT\"\nstep() { printf '\\n::orca-step:: %s\\n' \"$1\"; }\nstarted=$(date +%s)\nexport PATH=\"/opt/orca/tools/bin:/opt/orca/bin:$PATH\"\nexport ORCA_REPOS_ROOT=\"$ROOT\" ORCA_ENVIRONMENT_BUILD=1 CI=1 GIT_TERMINAL_PROMPT=0\nrepos() { printf '%s\\n' \"$ORCA_BUILD_REPOS\"; }\n\n# Tell the script author (often an agent) what they are installing onto.\npm=$(for c in apt-get dnf yum apk; do command -v \"$c\" >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\necho \"Base image: $(. /etc/os-release 2>/dev/null && echo \"$PRETTY_NAME\"), $(nproc) vCPU, package manager: ${pm:-none} (with sudo)\"\n\nstep clone\nfirst=\"\"\nwhile IFS='|' read -r url branch dir header; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n [ -n \"$first\" ] || first=\"$dest\"\n # The egress layer swaps the placeholder for a short-lived repo token; nothing real is on disk,\n # and the header is never written to the repo's config.\n git_auth=()\n [ -z \"${header:-}\" ] || git_auth=(-c \"http.https://github.com/.extraheader=$header\")\n echo \"Cloning $url${branch:+ ($branch)}\"\n rm -rf -- \"$dest\"\n # The clone's own error shows only when it really failed (an empty repo is recovered below).\n if ! git \"${git_auth[@]}\" clone --quiet ${branch:+--branch \"$branch\"} -- \"$url\" \"$dest\" 2>\"$OUT/clone.err\"; then\n refs=0\n git \"${git_auth[@]}\" ls-remote --exit-code -- \"$url\" >/dev/null 2>&1 || refs=$?\n if [ -n \"$branch\" ] && [ \"$refs\" -eq 2 ]; then\n # Reachable but no refs at all (ls-remote exits 2): a repo with no commits yet.\n echo \"$url has no commits yet; starting it empty on $branch.\"\n rm -rf -- \"$dest\"\n { git \"${git_auth[@]}\" clone --quiet -- \"$url\" \"$dest\" 2>/dev/null && git -C \"$dest\" checkout --quiet -b \"$branch\"; } || exit 10\n else\n cat \"$OUT/clone.err\"\n echo \"::orca-error:: Could not clone $url${branch:+ at $branch}. Check that the branch exists and Orca Cloud can reach the repository.\" \n exit 10\n fi\n fi\n git -C \"$dest\" log -1 --format=' at %h %s' 2>/dev/null || echo ' (no commits yet)'\ndone < <(repos)\n\nstep install\nprintf '%s' \"${ORCA_INSTALL_SCRIPT_B64:-}\" | base64 -d >\"$OUT/install.sh\"\nif [ -s \"$OUT/install.sh\" ]; then\n echo \"Running the install script in ${first:-$ROOT}\"\n (cd \"${first:-$ROOT}\" && exec bash -euo pipefail \"$OUT/install.sh\") /dev/null)\" || continue\n git -C \"$dest\" ls-files --others --ignored --exclude-standard --directory 2>/dev/null \\\n | sed 's#/$##' | grep -E \"$deps_re\" | head -n 500 >\"$common/orca-env-deps\" || true\n if [ -n \"${ORCA_DEPS_HOOK_B64:-}\" ]; then\n # A relative core.hooksPath (husky: .husky/_) names a gitignored folder a new worktree lacks; pin\n # it to the primary checkout so every worktree runs the same hooks, ours included.\n rel=\"$(git -C \"$dest\" config --get core.hooksPath 2>/dev/null || true)\"\n case \"$rel\" in '' | /*) ;; *) git -C \"$dest\" config core.hooksPath \"$dest/$rel\" ;; esac\n hooks=\"$(git -C \"$dest\" rev-parse --path-format=absolute --git-path hooks)\"\n mkdir -p \"$hooks\"\n if [ -e \"$hooks/post-checkout\" ] && ! grep -q 'orca-env-deps' \"$hooks/post-checkout\"; then\n mv -- \"$hooks/post-checkout\" \"$hooks/post-checkout.orca-chained\"\n fi\n printf '%s' \"$ORCA_DEPS_HOOK_B64\" | base64 -d >\"$hooks/post-checkout\" && chmod 0755 \"$hooks/post-checkout\"\n fi\n n=$(wc -l <\"$common/orca-env-deps\" | tr -d ' ')\n [ \"$n\" -gt 0 ] && echo \"$dir: $n installed folder(s) carried into new workspaces.\"\ndone < <(repos)\n{\n printf '{\"durationSec\":%d,\"repos\":[' \"$(( $(date +%s) - started ))\"\n sep=\"\"\n while IFS='|' read -r url branch dir _; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n commit=$(git -C \"$dest\" rev-parse --verify --quiet HEAD 2>/dev/null || true)\n head=$(git -C \"$dest\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\n printf '%s{\"url\":\"%s\",\"dir\":\"%s\",\"branch\":\"%s\",\"commit\":\"%s\",\"lockfiles\":{' \"$sep\" \"$url\" \"$dir\" \"$head\" \"$commit\"\n lsep=\"\"\n if [ -n \"$commit\" ]; then\n for f in ${ORCA_LOCKFILES:-}; do\n blob=$(git -C \"$dest\" rev-parse --verify --quiet \"HEAD:$f\" 2>/dev/null || true)\n if [ -n \"$blob\" ]; then printf '%s\"%s\":\"%s\"' \"$lsep\" \"$f\" \"$blob\"; lsep=\",\"; fi\n done\n fi\n printf '}}'\n sep=\",\"\n done < <(repos)\n printf '],\"diskUsedBytes\":%s,\"diskTotalBytes\":%s}\\n' \\\n \"$(df -B1 --output=used / | tail -n 1 | tr -d ' ')\" \"$(df -B1 --output=size / | tail -n 1 | tr -d ' ')\"\n} >\"$OUT/result.json\" || exit 30\n# Nothing from this VM's own session belongs in the image, only what the script installed.\nrm -rf -- \"$OUT/install.sh\" \"$HOME/.bash_history\" \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\"\necho \"Disk used: $(df -h --output=used / | tail -n 1 | tr -d ' ') of $(df -h --output=size / | tail -n 1 | tr -d ' ')\"\n" export const ENVIRONMENT_DEPS_HOOK: string = "#!/usr/bin/env bash\n# Installed by Orca environment builds as the repo's post-checkout hook. When git creates a new linked\n# worktree (`git worktree add` passes the null commit as the previous HEAD), give it the dependency\n# folders the build installed in the primary checkout, as hard links: near-instant, real paths (not\n# symlinks, so bundlers and native modules behave). Hard links share file contents: tools that rewrite\n# a file in place inside these folders change it for every worktree on this VM (one workspace per VM).\n# Any post-checkout hook the repo already had runs afterwards, unchanged.\nprev=\"${1:-}\"\nhere=\"$(dirname \"$0\")\"\nif [ \"$prev\" = \"0000000000000000000000000000000000000000\" ] && [ \"${ORCA_SKIP_DEPS_LINK:-}\" != 1 ]; then\n common=\"$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || true)\"\n top=\"$(git rev-parse --show-toplevel 2>/dev/null || true)\"\n primary=\"$(dirname \"$common\")\"\n list=\"$common/orca-env-deps\"\n if [ -n \"$top\" ] && [ \"$top\" != \"$primary\" ] && [ -f \"$list\" ]; then\n started=$(date +%s%N)\n linked=0\n while IFS= read -r rel; do\n case \"$rel\" in '' | /* | *..*) continue ;; esac\n [ -e \"$primary/$rel\" ] && [ ! -e \"$top/$rel\" ] || continue\n mkdir -p \"$(dirname \"$top/$rel\")\"\n if [ -d \"$primary/$rel\" ]; then\n if ! cp -al -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null; then\n # A partial hard-link copy would make the fallback nest inside it: start clean.\n rm -rf -- \"$top/$rel\"\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || { rm -rf -- \"$top/$rel\"; continue; }\n fi\n else\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || continue\n fi\n linked=$((linked + 1))\n done <\"$list\"\n if [ \"$linked\" -gt 0 ]; then\n echo \"Orca: reused $linked installed dependency folder(s) from the environment build ($(( ($(date +%s%N) - started) / 1000000 )) ms).\" >&2\n fi\n fi\nfi\nif [ -x \"$here/post-checkout.orca-chained\" ]; then\n if head -n 1 \"$here/post-checkout.orca-chained\" | grep -Eq '^#!.*(ba|da|z)?sh'; then\n # Sourced, so $0 still names `post-checkout` (husky v9 finds the user's hook by basename \"$0\").\n ( . \"$here/post-checkout.orca-chained\" \"$@\" )\n exit $?\n fi\n exec \"$here/post-checkout.orca-chained\" \"$@\"\nfi\nexit 0\n" -export const WORKSPACE_PRELUDE_SCRIPT: string = "#!/usr/bin/env bash\n# Runs right before orca-sandbox-start on a workspace's first boot. Prints only to stderr: the start\n# script's last stdout line is the orcad recipe line the control plane parses.\n#\n# - Booted from an environment build (ORCA_ENV_REPO_DIR set): the repo is already cloned with its\n# dependencies installed under /vercel/sandbox/repos. Link it as the project (a link, not a move,\n# so absolute paths baked into installed dependencies keep working) and bring the requested\n# branch up to date. A failed fetch keeps the build's commit: the workspace still opens.\n# - Otherwise clone ORCA_REPO_URL here so a repo with no commits yet also opens: it gets an empty\n# first commit on the requested branch, which Orca needs to create the workspace's worktree.\nset -uo pipefail\nP=/vercel/sandbox/project\nROOT=/vercel/sandbox/repos\nexport GIT_TERMINAL_PROMPT=0\nauth=()\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n auth=(-c \"http.https://github.com/.extraheader=$ORCA_GIT_EXTRAHEADER\")\nfi\nref=\"${ORCA_REPO_REF:-}\"\n\nfirst_commit() {\n if ! git -C \"$P\" rev-parse --verify --quiet HEAD >/dev/null; then\n git -C \"$P\" checkout --quiet -B \"${ref:-main}\" 2>/dev/null || true\n git -C \"$P\" -c user.name='Orca' -c user.email='cloud@onorca.dev' \\\n commit --quiet --allow-empty -m 'Initial commit' && echo 'Empty repository: created a first commit.'\n fi\n}\n\nif [ ! -e \"$P\" ] && [ -n \"${ORCA_ENV_REPO_DIR:-}\" ] && [ -d \"$ROOT/$ORCA_ENV_REPO_DIR/.git\" ]; then\n ln -s \"$ROOT/$ORCA_ENV_REPO_DIR\" \"$P\"\n if [ -n \"$ref\" ]; then\n if timeout 60 git \"${auth[@]}\" -C \"$P\" fetch --quiet origin \"+refs/heads/$ref:refs/remotes/origin/$ref\"; then\n # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.\n git -C \"$P\" checkout --quiet -f -B \"$ref\" \"origin/$ref\" -- ||\n echo \"Could not switch to $ref; the workspace starts at the build's commit.\"\n else\n echo \"Could not fetch $ref; the workspace starts at the build's commit.\"\n fi\n fi\n first_commit\nelif [ ! -e \"$P\" ] && [ -n \"${ORCA_REPO_URL:-}\" ]; then\n if ! git \"${auth[@]}\" clone --quiet ${ref:+--branch \"$ref\"} -- \"$ORCA_REPO_URL\" \"$P\" 2>/dev/null; then\n rm -rf -- \"$P\"\n # Branch missing (or a repo with no commits): clone the default branch, then switch.\n git \"${auth[@]}\" clone --quiet -- \"$ORCA_REPO_URL\" \"$P\" || exit 1\n if [ -n \"$ref\" ] && ! git -C \"$P\" checkout --quiet \"$ref\" -- 2>/dev/null; then\n git -C \"$P\" checkout --quiet -b \"$ref\" -- || true\n fi\n fi\n first_commit\nfi\nexit 0\n" +export const WORKSPACE_PRELUDE_SCRIPT: string = "#!/usr/bin/env bash\n# Runs right before orca-sandbox-start on a workspace's first boot. Prints only to stderr: the start\n# script's last stdout line is the orcad recipe line the control plane parses.\n#\n# - Booted from an environment build (ORCA_ENV_REPO_DIR set): the repo is already cloned with its\n# dependencies installed under /vercel/sandbox/repos. Link it as the project (a link, not a move,\n# so absolute paths baked into installed dependencies keep working). No fetch when the build is\n# already on the requested branch: Orca fetches the base right before it adds the workspace's\n# worktree, so a fetch here would only delay orcad (measured ~0.5-1 s). Another branch is fetched\n# and checked out; if that fails the workspace still opens at the build's commit.\n# - Otherwise clone ORCA_REPO_URL here so a repo with no commits yet also opens: it gets an empty\n# first commit on the requested branch, which Orca needs to create the workspace's worktree.\nset -uo pipefail\nP=/vercel/sandbox/project\nROOT=/vercel/sandbox/repos\nexport GIT_TERMINAL_PROMPT=0\nauth=()\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n auth=(-c \"http.https://github.com/.extraheader=$ORCA_GIT_EXTRAHEADER\")\nfi\nref=\"${ORCA_REPO_REF:-}\"\n\nfirst_commit() {\n if ! git -C \"$P\" rev-parse --verify --quiet HEAD >/dev/null; then\n git -C \"$P\" checkout --quiet -B \"${ref:-main}\" 2>/dev/null || true\n git -C \"$P\" -c user.name='Orca' -c user.email='cloud@onorca.dev' \\\n commit --quiet --allow-empty -m 'Initial commit' && echo 'Empty repository: created a first commit.'\n fi\n}\n\nif [ ! -e \"$P\" ] && [ -n \"${ORCA_ENV_REPO_DIR:-}\" ] && [ -d \"$ROOT/$ORCA_ENV_REPO_DIR/.git\" ]; then\n ln -s \"$ROOT/$ORCA_ENV_REPO_DIR\" \"$P\"\n if [ -n \"$ref\" ] && [ \"$(git -C \"$P\" symbolic-ref --quiet --short HEAD 2>/dev/null)\" != \"$ref\" ]; then\n if timeout 60 git \"${auth[@]}\" -C \"$P\" fetch --quiet origin \"+refs/heads/$ref:refs/remotes/origin/$ref\"; then\n # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.\n git -C \"$P\" checkout --quiet -f -B \"$ref\" \"origin/$ref\" -- ||\n echo \"Could not switch to $ref; the workspace starts at the build's commit.\"\n else\n echo \"Could not fetch $ref; the workspace starts at the build's commit.\"\n fi\n fi\n first_commit\nelif [ ! -e \"$P\" ] && [ -n \"${ORCA_REPO_URL:-}\" ]; then\n if ! git \"${auth[@]}\" clone --quiet ${ref:+--branch \"$ref\"} -- \"$ORCA_REPO_URL\" \"$P\" 2>/dev/null; then\n rm -rf -- \"$P\"\n # Branch missing (or a repo with no commits): clone the default branch, then switch.\n git \"${auth[@]}\" clone --quiet -- \"$ORCA_REPO_URL\" \"$P\" || exit 1\n if [ -n \"$ref\" ] && ! git -C \"$P\" checkout --quiet \"$ref\" -- 2>/dev/null; then\n git -C \"$P\" checkout --quiet -b \"$ref\" -- || true\n fi\n fi\n first_commit\nfi\nexit 0\n" diff --git a/cloud/apps/sandbox-control/migrations/0030_sandboxes_environment_index.sql b/cloud/apps/sandbox-control/migrations/0030_sandboxes_environment_index.sql new file mode 100644 index 00000000000..c1a3f247656 --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0030_sandboxes_environment_index.sql @@ -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); diff --git a/cloud/apps/sandbox-control/src/environment-builds.ts b/cloud/apps/sandbox-control/src/environment-builds.ts index 49f9207d57d..a1279699d8a 100644 --- a/cloud/apps/sandbox-control/src/environment-builds.ts +++ b/cloud/apps/sandbox-control/src/environment-builds.ts @@ -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 { + // 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 { 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() } diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index 1c3c20d52b4..02ae808da45 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -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 }) diff --git a/cloud/apps/sandbox-control/src/pool.ts b/cloud/apps/sandbox-control/src/pool.ts index fc7c87b0349..991a1a27555 100644 --- a/cloud/apps/sandbox-control/src/pool.ts +++ b/cloud/apps/sandbox-control/src/pool.ts @@ -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 = { 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 { +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 { 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() } @@ -123,20 +138,66 @@ async function takeLease(deps: PoolDeps): Promise { 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> { + const targets = new Map([[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() + 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 { 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()).results const maxAge = pool?.maxAgeMs ?? DEFAULT_POOL_MAX_AGE_MS + const targets = draining || !pool ? new Map() : 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() + 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 { 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 { } } 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 { return { created, recycled, ready: live + created } } -async function bootPooledVm(deps: PoolDeps): Promise { +async function bootPooledVm(deps: PoolDeps, snapshotId: string): Promise { const id = poolId() const now = deps.now() const row: PooledVm = { @@ -174,7 +244,7 @@ async function bootPooledVm(deps: PoolDeps): Promise { 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 { .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, name: string): Promise { +export async function deletePooledVm( + deps: Pick, + name: string, + /** The image it booted from (golden or an environment build) is shared: never deleted here. */ + sourceSnapshotId?: string +): Promise { 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) } } diff --git a/cloud/apps/sandbox-control/test/environments.test.ts b/cloud/apps/sandbox-control/test/environments.test.ts index f98f938afd9..e202f382adf 100644 --- a/cloud/apps/sandbox-control/test/environments.test.ts +++ b/cloud/apps/sandbox-control/test/environments.test.ts @@ -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`) diff --git a/cloud/apps/sandbox-control/test/pool.test.ts b/cloud/apps/sandbox-control/test/pool.test.ts index 2f0524ca2d6..779b9208039 100644 --- a/cloud/apps/sandbox-control/test/pool.test.ts +++ b/cloud/apps/sandbox-control/test/pool.test.ts @@ -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()