diff --git a/changelog.d/gst-1220-ubi-recovery.md b/changelog.d/gst-1220-ubi-recovery.md new file mode 100644 index 0000000000..57dfcee011 --- /dev/null +++ b/changelog.d/gst-1220-ubi-recovery.md @@ -0,0 +1,13 @@ +**A Ubicloud run survives a dead controller (GST-1220).** When the machine that ran `ubi-runner.sh up` died, its VM kept running but its ssh key and state lived only on that machine, so no other machine could pull the results or destroy the VM before its TTL. Paid runs were lost with the controller. + +### Added +- **Encrypted recovery bundles and `recover`.** With `UBI_RECOVERY_DIR` set, `up` writes each VM's key, state and tags to `
###` sentinel in its log; a log without
the sentinel after the VM is gone is an interrupted run, not a pass.
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 793bff5ffb..8f5bb1f670 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -6673,6 +6673,50 @@ These codes come from `bin/gstack-modules` and `gen-skill-docs --loadout/--modul
**Meaning.** `--out-dir` is a non-empty directory that an earlier `gstack-modules render` did not write, so replacing it could delete someone's files. **Fix.** Pass a new or empty directory, or the directory of an earlier render.
+## ubi-runner recovery and results sink
+
+These codes come from `scripts/ubicloud/ubi-runner.sh` (GST-1220). `RECOVERED`, `RECOVER_GONE` and `RECOVER_FAILED` lines go to stdout, one per bundle. Every `RECOVER_FAILED` keeps its bundle, so rerunning `recover` after the fix is always safe.
+
+
+### `UBI_RECOVERY_REQUIRED`
+
+**Meaning.** A counted run (`--counted` or `UBI_COUNTED=1`) or `recover` needs a recovery directory, and neither `UBI_RECOVERY_DIR` nor `GSTACK_CAPY_RECOVERY_DIR` (nor `recover --dir`) names one. Nothing was created. A counted rerun also refuses with this code when it would reattach to a live VM whose bundle under the recovery directory is missing or doesn't open under this secret. **Fix.** Set `UBI_RECOVERY_DIR` to a directory another controller can read (on Capy, a drive folder), then rerun. For a VM without a bundle that opens, destroy it with the printed `down` command, then rerun.
+
+
+### `UBI_RECOVERY_UNAVAILABLE`
+
+**Meaning.** The bundle can't be written or opened: `openssl` is missing, there is no secret (`UBI_RECOVERY_KEY` or `UBICLOUD_API_KEY`), or the directory isn't writable. A counted run stops: before any create when the check runs up front, or through `up`'s teardown, which destroys the VM, when a later write fails. An uncounted run prints a warning and goes on without a bundle. **Fix.** Install openssl and make the directory writable, then rerun.
+
+
+### `RECOVER_FAILED: vm= code=RECOVER_DECRYPT_FAILED`
+
+**Meaning.** The bundle didn't authenticate under this machine's secret, or it was sealed for a different VM name or owner than its file name and folder say, so no state was written. Either the secret differs from the creating controller's (another `UBI_RECOVERY_KEY`, or a different Ubicloud token), or the file was changed, renamed or moved. **Fix.** Set `UBI_RECOVERY_KEY` (or `UBICLOUD_API_KEY`) to the value the creating controller used and rerun `recover`. If the secret is right, treat the bundle as tampered and destroy the VM from the Ubicloud console instead.
+
+
+### `RECOVER_FAILED: vm= code=RECOVER_API_UNAVAILABLE`
+
+**Meaning.** The Ubicloud API answered something other than 200 or 404 for the VM, or the VM's create was sent less than `UBI_CREATE_GRACE` seconds ago and may still be in flight. No state was written. **Fix.** Rerun `recover` once the API answers, or after the grace period.
+
+
+### `RECOVER_FAILED: vm= code=RECOVER_EXISTS`
+
+**Meaning.** This machine already has state for the VM, and `recover` never overwrites it. **Fix.** Use that state (`pull`, `ssh`, `down `). Remove the state directory only if you know it's stale.
+
+
+### `RECOVER_GONE: vm=`
+
+**Meaning.** The VM is confirmed gone, so its bundle was deleted. **Fix.** None. Its results are wherever its sink put them, if it had one.
+
+
+### `UBI_SINK_INVALID`
+
+**Meaning.** `--sink` or `UBI_SINK` names something other than `https-put:`. `file:` works only with `UBI_SINK_ALLOW_FILE=1`, which is meant for tests, and there is no `git:` sink because it would put a repository credential on the VM. Nothing was created, and the line never prints the URL. **Fix.** Pass a presigned PUT URL for one object.
+
+
+### `SINK_FLUSH_FAILED: vm= seq= last_push= [sink_skipped=size|tar_failed]`
+
+**Meaning.** `down` stopped the VM's pusher and ran one last push, and that push failed, took longer than 150 seconds, or was skipped because the results were over `UBI_SINK_MAX_MB` (`size`) or couldn't be read (`tar_failed`). A skipped snapshot is never uploaded, so the sink keeps the last good one. The VM was destroyed anyway, so the sink holds results only up to the push made at `last_push`. A `run` or `verify` of that VM exits 1 instead of 0. **Fix.** Treat the run's results as incomplete. Check that the presigned URL hasn't expired and still allows a PUT, then rerun. For a tiered `verify`, rerun with `--no-resume`: a plain rerun reuses the tiers that already passed under the same key, creates no VM and pushes nothing, so the sink would still hold the incomplete snapshot.
+
## Per-repo cleanup (gstack-clean)
These codes come from `bin/gstack-clean`, which reclaims old codex scratch in `/.gstack/tmp/`, browse logs over 1 MB and, with `--audit-days N`, old browse audit entries. It changes nothing unless you pass `--apply`, and `gstack-clean --help` lists what it touches.
diff --git a/scripts/ubicloud/ubi-runner.sh b/scripts/ubicloud/ubi-runner.sh
index 03a698e4bb..81468387dc 100755
--- a/scripts/ubicloud/ubi-runner.sh
+++ b/scripts/ubicloud/ubi-runner.sh
@@ -102,7 +102,34 @@
# reads .gstack/ubicloud.json (setup, command, size, location, env, pass, pull)
# and runs it through `run`, so lanes share one committed definition instead of
# per-lane wrappers.
+#
+# Surviving a dead controller (GST-1220). With UBI_RECOVERY_DIR set (on Capy,
+# GSTACK_CAPY_RECOVERY_DIR names a drive folder), `up` writes an encrypted
+# recovery bundle of each VM's local state (ssh key, env, tags) to
+# //.bundle, and `recover [--owner OLD]` on another machine
+# rebuilds that state so pull, ssh and down work there. The bundle is AES-256
+# (openssl enc, pbkdf2) under a key derived from UBI_RECOVERY_KEY or else
+# UBICLOUD_API_KEY, with an HMAC-SHA256 checked before anything is decrypted;
+# the secret travels only on a pipe, never in argv, a child's environment or a
+# file. A counted run (--counted or UBI_COUNTED=1) refuses before any create
+# without a bundle (UBI_RECOVERY_REQUIRED, UBI_RECOVERY_UNAVAILABLE). Run
+# recover only once the creating machine is dead: a paused one is not detected.
+# `up --sink https-put: --sink-path PATH` starts a pusher on the
+# VM that uploads heartbeat.json and the PATH entries as results.tgz every
+# UBI_SINK_INTERVAL seconds, so results land even when every controller dies;
+# the URL reaches the VM only in a 600 curl config file. The sink is off unless
+# --sink or UBI_SINK names one, and `down` makes one last push first
+# (SINK_FLUSH_FAILED turns a passing run into exit 1).
set -euo pipefail
+# The caller's exported names and values, captured before the runner sets any
+# variable of its own: --pass forwards from here, never from a live variable.
+INHERITED_NAMES=() INHERITED_VALUES=()
+for _ubi_n in $(compgen -e); do
+ [ -n "${!_ubi_n+x}" ] || continue
+ INHERITED_NAMES+=("$_ubi_n") INHERITED_VALUES+=("${!_ubi_n}")
+done
+unset _ubi_n
+INHERITED_ENV=" ${INHERITED_NAMES[*]-} "
# Keep heredoc bodies on temp files, not the pipe window (test/heredoc-pipe-deadlock.test.ts).
BASH_COMPAT=50
@@ -142,6 +169,15 @@ for bin in curl python3 ssh ssh-keygen tar; do
command -v "$bin" >/dev/null || die "$bin is required"
done
UBICLOUD_API_KEY="${UBICLOUD_API_KEY:-${UBICLOUD_API_TOKEN:-}}"
+RECOVERY_DIR="${UBI_RECOVERY_DIR:-${GSTACK_CAPY_RECOVERY_DIR:-}}"
+RECOVERY_SECRET="${UBI_RECOVERY_KEY:-$UBICLOUD_API_KEY}"
+unset UBI_RECOVERY_KEY
+COUNTED="${UBI_COUNTED:-0}"
+SINK_INTERVAL="${UBI_SINK_INTERVAL:-300}"
+SINK_MAX_MB="${UBI_SINK_MAX_MB:-512}"
+SINK_FLUSH_FAILED=""
+[[ "$SINK_INTERVAL" =~ ^[1-9][0-9]*$ ]] || die "UBI_SINK_INTERVAL must be a whole number of seconds, at least 1"
+[[ "$SINK_MAX_MB" =~ ^[1-9][0-9]*$ ]] || die "UBI_SINK_MAX_MB must be a whole number of megabytes, at least 1"
[[ "$GC_HOURS" =~ ^[0-9]+$ ]] || die "UBI_GC_HOURS must be a whole number of hours (unset or 0 disables the sweep)"
for v in IDLE_TIMEOUT RUN_TIMEOUT HEARTBEAT QUOTA_WAIT CHECKPOINT_MAX_AGE REATTACH_MARGIN; do
[[ "${!v}" =~ ^[0-9]+$ ]] || die "UBI_$v must be a whole number of seconds (0 disables it)"
@@ -854,10 +890,10 @@ write_state() {
"$1" "$2" "$3" "$4" "$5" "$6" "$$" >"$(state_dir "$1")/env"
}
-# record_vm NAME LOCATION: append to the scratch VM-id file (record-before-create).
+# record_vm NAME LOCATION [OWNER]: append to the scratch VM-id file (record-before-create).
record_vm() {
mkdir -p "$(dirname "$VM_RECORD")" 2>/dev/null || return 0
- printf '%s\t%s\t%s\t%s\t%s\n' "$1" "$2" "$OWNER" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$$" >>"$VM_RECORD"
+ printf '%s\t%s\t%s\t%s\t%s\n' "$1" "$2" "${3:-$OWNER}" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$$" >>"$VM_RECORD"
}
# forget_vm NAME: drop the VM from the scratch file once it is confirmed gone.
@@ -875,6 +911,285 @@ cmd_records() {
awk -F'\t' '{ printf "%-40s %-14s %-12s %-20s %s\n", $1, $2, $3, $4, $5 }' "$VM_RECORD"
}
+# vm_gone_final SEEN CREATED CREATE_AT CREATE_PID: a "not found" for the VM is
+# final: it was seen, its create was answered, or the create was sent more than
+# UBI_CREATE_GRACE seconds ago by a process that is gone (or is this one).
+vm_gone_final() {
+ [ "$1" = 1 ] || [ "$2" != unknown ] || { [ $(( $(date +%s) - $3 )) -ge "$CREATE_GRACE" ] \
+ && { [ "$4" = "$$" ] || ! kill -0 "$4" 2>/dev/null; }; }
+}
+
+# Recovery bundles. RB_PY reads the secret on stdin and stretches it with
+# PBKDF2-SHA256 (200000 rounds, a random salt per bundle) into an encryption key
+# and a MAC key; the encryption key reaches openssl on a pipe fd (-pass fd:N).
+# A bundle is UBIRB1, the salt, the ciphertext of a JSON map of the state files
+# with the VM name and owner, and an HMAC over all of it, checked with
+# compare_digest before anything is decrypted. open NAME OWNER exits 3 on any
+# failure, a sealed name or owner other than NAME and OWNER included.
+RB_PY='
+import base64, hashlib, hmac, json, os, subprocess, sys
+MAGIC = b"UBIRB1\n"
+FILES = ("key", "key.pub", "env", "tags", "sink")
+secret = sys.stdin.buffer.read()
+if not secret:
+ sys.exit(2)
+def keys(salt):
+ k = hashlib.pbkdf2_hmac("sha256", secret, b"ubi-runner recovery bundle v1" + salt, 200000, 64)
+ return k[:32].hex().encode(), k[32:]
+def ossl(mode, data, enc_key):
+ r, w = os.pipe()
+ os.write(w, enc_key + b"\n")
+ os.close(w)
+ try:
+ p = subprocess.run(["openssl", "enc", mode, "-aes-256-cbc", "-pbkdf2", "-iter", "1000", "-salt", "-pass", "fd:%d" % r],
+ input=data, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, pass_fds=(r,))
+ finally:
+ os.close(r)
+ return p.returncode, p.stdout
+if sys.argv[1] == "seal":
+ src, out, name, owner = sys.argv[2:6]
+ salt = os.urandom(16)
+ enc_key, mac_key = keys(salt)
+ files = {}
+ for n in FILES:
+ if os.path.isfile(os.path.join(src, n)):
+ with open(os.path.join(src, n), "rb") as f:
+ files[n] = base64.b64encode(f.read()).decode()
+ rc, ct = ossl("-e", json.dumps({"v": 1, "name": name, "owner": owner, "files": files}).encode(), enc_key)
+ if rc != 0 or not ct:
+ sys.exit(1)
+ body = MAGIC + salt + ct
+ os.makedirs(os.path.dirname(out), mode=0o700, exist_ok=True)
+ tmp = "%s.tmp.%d" % (out, os.getpid())
+ with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as f:
+ f.write(body + hmac.new(mac_key, body, hashlib.sha256).digest())
+ os.rename(tmp, out)
+else:
+ bundle, dest, name, owner = sys.argv[2:6]
+ with open(bundle, "rb") as f:
+ data = f.read()
+ body, mac = data[:-32], data[-32:]
+ if len(data) < len(MAGIC) + 16 + 33 or not body.startswith(MAGIC):
+ sys.exit(3)
+ enc_key, mac_key = keys(body[len(MAGIC):len(MAGIC) + 16])
+ if not hmac.compare_digest(mac, hmac.new(mac_key, body, hashlib.sha256).digest()):
+ sys.exit(3)
+ rc, plain = ossl("-d", body[len(MAGIC) + 16:], enc_key)
+ try:
+ sealed = json.loads(plain) if rc == 0 else {}
+ except ValueError:
+ sealed = {}
+ files = sealed.get("files") if isinstance(sealed, dict) else None
+ if sealed.get("name") != name or sealed.get("owner") != owner or not isinstance(files, dict) \
+ or "env" not in files or "key" not in files or any(n not in FILES for n in files):
+ sys.exit(3)
+ for n, b in files.items():
+ with os.fdopen(os.open(os.path.join(dest, n), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as f:
+ f.write(base64.b64decode(b))
+'
+
+# bundle_save NAME: (re)write NAME's recovery bundle when UBI_RECOVERY_DIR is
+# set. A counted run stops on a failed write; any other run warns and goes on.
+bundle_save() {
+ [ -n "$RECOVERY_DIR" ] || return 0
+ printf %s "$RECOVERY_SECRET" | python3 -c "$RB_PY" seal "$(state_dir "$1")" "$RECOVERY_DIR/$OWNER/$1.bundle" "$1" "$OWNER" && return 0
+ [ "$COUNTED" != 1 ] || die "UBI_RECOVERY_UNAVAILABLE: could not write the recovery bundle for $1 under $RECOVERY_DIR (needs openssl and a writable directory); a counted run needs it"
+ log "WARNING: could not write the recovery bundle for $1 under $RECOVERY_DIR (UBI_RECOVERY_UNAVAILABLE); continuing without one"
+}
+
+# recovery_preflight: a counted run needs a bundle another controller can open.
+recovery_preflight() {
+ [ -n "$RECOVERY_DIR" ] || die "UBI_RECOVERY_REQUIRED: a counted run (--counted or UBI_COUNTED=1) needs a recovery bundle; set UBI_RECOVERY_DIR to a directory another controller can read (on Capy, a drive folder), then rerun"
+ command -v openssl >/dev/null && [ -n "$RECOVERY_SECRET" ] \
+ || die "UBI_RECOVERY_UNAVAILABLE: a counted run needs openssl and a secret (UBI_RECOVERY_KEY or UBICLOUD_API_KEY) to write its recovery bundle"
+}
+
+# recover_failed NAME CODE FIX: one RECOVER_FAILED line; the bundle is kept.
+recover_failed() { echo "RECOVER_FAILED: vm=$1 code=$2 fix=$3"; RECOVER_FAILS=$(( RECOVER_FAILS + 1 )); }
+
+# recover [--owner OLD] [--dir DIR]: rebuild local state for every VM with a
+# bundle under DIR/OLD (default UBI_RECOVERY_DIR and this owner). A live VM
+# prints RECOVERED, a VM confirmed gone drops its bundle (RECOVER_GONE), and
+# anything else prints RECOVER_FAILED and keeps the bundle. State already on
+# this machine is never overwritten.
+RECOVER_FAILS=0
+cmd_recover() {
+ local from=$OWNER dir=$RECOVERY_DIR b name dest tmp code out ip tags
+ while [ $# -gt 0 ]; do
+ case $1 in
+ --owner) from=$2; shift 2 ;;
+ --dir) dir=$2; shift 2 ;;
+ *) die "recover: unknown option $1" ;;
+ esac
+ done
+ [[ "$from" =~ ^[a-z][a-z0-9]{0,11}$ ]] || die "recover: --owner must be an owner tag as the owner command prints it"
+ [ -n "$dir" ] || die "UBI_RECOVERY_REQUIRED: recover reads bundles from UBI_RECOVERY_DIR (or --dir DIR), and neither is set"
+ command -v openssl >/dev/null || die "UBI_RECOVERY_UNAVAILABLE: openssl is required to open recovery bundles"
+ mkdir -p "$STATE_ROOT"
+ out=$(mktemp)
+ for b in "$dir/$from"/*.bundle; do
+ [ -f "$b" ] || { log "recover: no bundles under $dir/$from"; continue; }
+ name=$(basename "$b" .bundle)
+ valid_name "$name" || continue
+ dest=$(state_dir "$name")
+ if [ -e "$dest" ]; then
+ recover_failed "$name" RECOVER_EXISTS "this machine already has state for $name; use it, or run down $name"
+ continue
+ fi
+ tmp=$(mktemp -d "$STATE_ROOT/.recover.XXXXXX")
+ local NAME="" LOCATION="" SIZE="" IP="" CREATED="" CREATE_AT=0 CREATE_PID="" line
+ if printf %s "$RECOVERY_SECRET" | python3 -c "$RB_PY" open "$b" "$tmp" "$name" "$from"; then
+ while IFS= read -r line; do
+ [[ "$line" =~ ^(NAME|LOCATION|SIZE|IP|CREATED|CREATE_AT|CREATE_PID)=([A-Za-z0-9._:/-]*)$ ]] || continue
+ printf -v "${BASH_REMATCH[1]}" %s "${BASH_REMATCH[2]}"
+ done <"$tmp/env"
+ fi
+ if [ "$NAME" != "$name" ] || ! [[ "$CREATE_AT" =~ ^[0-9]+$ && "$LOCATION" =~ ^[a-z0-9-]+$ ]]; then
+ rm -rf "$tmp"
+ recover_failed "$name" RECOVER_DECRYPT_FAILED "the bundle does not authenticate under this secret, or it was sealed for another VM or owner; set UBI_RECOVERY_KEY (or UBICLOUD_API_KEY) to the creating controller's"
+ continue
+ fi
+ code=$(api "$out" vm "$LOCATION/$name" show)
+ case $code in
+ 200)
+ ip=$(sed -n 's/^ip4: //p' "$out")
+ printf 'NAME=%q\nLOCATION=%q\nSIZE=%q\nIP=%q\nCREATED=yes\nCREATE_AT=%q\nCREATE_PID=\nADOPTED_BY=%q\n' \
+ "$name" "$LOCATION" "$SIZE" "${ip:-$IP}" "$CREATE_AT" "$OWNER" >"$tmp/env"
+ if [ -e "$dest" ]; then
+ rm -rf "$tmp"
+ recover_failed "$name" RECOVER_EXISTS "state for $name appeared on this machine while recovering; use it"
+ continue
+ fi
+ mv "$tmp" "$dest"
+ record_vm "$name" "$LOCATION" "$from"
+ tags=$(grep -E '^[A-Za-z0-9_.-]+=[A-Za-z0-9_.:/@+-]*$' "$dest/tags" 2>/dev/null | paste -s -d, - || true)
+ echo "RECOVERED: vm=$name ip=${ip:-$IP} owner=$from tags=$tags" ;;
+ 404)
+ rm -rf "$tmp"
+ if vm_gone_final 0 "$CREATED" "$CREATE_AT" ""; then
+ rm -f "$b"
+ echo "RECOVER_GONE: vm=$name"
+ else
+ recover_failed "$name" RECOVER_API_UNAVAILABLE "its create may still be in flight; rerun recover after UBI_CREATE_GRACE (${CREATE_GRACE}s)"
+ fi ;;
+ *)
+ rm -rf "$tmp"
+ recover_failed "$name" RECOVER_API_UNAVAILABLE "the Ubicloud API answered HTTP $code; nothing changed, rerun recover" ;;
+ esac
+ done
+ rm -f "$out"
+ [ "$RECOVER_FAILS" -eq 0 ]
+}
+
+# sink_check SPEC: https-put: is the only network sink; file:
+# only under UBI_SINK_ALLOW_FILE=1 (tests). The URL is never printed.
+sink_check() {
+ case $1 in
+ https-put:https://*) [[ "${1#https-put:}" =~ ^https://[^[:space:]]+$ ]] && return 0 ;;
+ file:/*) [ "${UBI_SINK_ALLOW_FILE:-}" = 1 ] && return 0 ;;
+ esac
+ die "UBI_SINK_INVALID: a sink is https-put: (file: only with UBI_SINK_ALLOW_FILE=1); got a '${1%%:*}:' spec. Nothing was created"
+}
+
+# SINK_SH: the VM-side pusher. Every SINK_INTERVAL seconds it packs
+# heartbeat.json and the SINK_PATHS entries under ~ (never ~/.ubirun-*, which
+# hold --pass values and the URL) into results.tgz and pushes it when they
+# changed, or every fifth interval regardless. A snapshot tar cannot read, or
+# one over UBI_SINK_MAX_MB, is skipped, so the last good one stays in the sink.
+# A failed or skipped push backs off and retries; it never ends the loop.
+# --once pushes one time and exits 1 with "seq= last_push= [sink_skipped=]".
+SINK_SH='#!/usr/bin/env bash
+. ~/.ubirun-sink.conf || exit 1
+once=0
+[ "${1:-}" != --once ] || once=1
+[ "$once" = 1 ] || echo $$ > ~/.ubirun-sink.pid
+seq=$(cat ~/.ubirun-sink.seq 2>/dev/null || echo 0)
+last=$(cat ~/.ubirun-sink.last 2>/dev/null || echo never)
+present() { P=(); local p; for p in ${SINK_PATHS[@]+"${SINK_PATHS[@]}"}; do [ ! -e "$HOME/$p" ] || P+=("$p"); done; }
+digest() { present; [ ${#P[@]} -gt 0 ] || { echo none; return 0; }; tar -cf - --exclude=".ubirun-*" -C "$HOME" "${P[@]}" 2>/dev/null | cksum; }
+beat() { printf "{\"vm\": \"%s\", \"owner\": \"%s\", \"seq\": %d, \"time\": \"%s\", \"last_push\": \"%s\", \"sink_skipped\": \"%s\"}\n" \
+ "$SINK_VM" "$SINK_OWNER" "$seq" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$last" "$2" > "$1/heartbeat.json"; }
+push() {
+ local d rc=0
+ skipped=""
+ d=$(mktemp -d "$HOME/.ubirun-sink.XXXXXX") || return 1
+ seq=$((seq + 1)); echo "$seq" > ~/.ubirun-sink.seq
+ present
+ beat "$d" ""
+ if [ ${#P[@]} -gt 0 ]; then
+ tar -czf "$d/results.tgz" --exclude=".ubirun-*" -C "$d" heartbeat.json -C "$HOME" "${P[@]}" 2>/dev/null || rc=$?
+ [ "$rc" -le 1 ] || skipped=tar_failed
+ [ -n "$skipped" ] || [ "$(wc -c < "$d/results.tgz")" -le $((SINK_MAX_MB * 1048576)) ] || skipped=size
+ else
+ tar -czf "$d/results.tgz" -C "$d" heartbeat.json
+ fi
+ if [ -n "$skipped" ]; then rm -rf "$d"; return 2; fi
+ rc=0
+ case $SINK_KIND in
+ file) { mkdir -p "$SINK_DIR/$SINK_VM" && cp "$d/results.tgz" "$SINK_DIR/$SINK_VM/.results.tgz.$$" \
+ && mv -f "$SINK_DIR/$SINK_VM/.results.tgz.$$" "$SINK_DIR/$SINK_VM/results.tgz"; } 2>/dev/null || rc=1 ;;
+ https-put) curl -sS --fail --max-time 120 -K "$HOME/.ubirun-sink.curl" -T "$d/results.tgz" >/dev/null 2>&1 || rc=1 ;;
+ *) rc=1 ;;
+ esac
+ rm -rf "$d"
+ [ "$rc" -ne 0 ] || { last=$(date +%s); echo "$last" > ~/.ubirun-sink.last; }
+ return "$rc"
+}
+if [ "$once" = 1 ]; then push && exit 0; echo "seq=$seq last_push=$last${skipped:+ sink_skipped=$skipped}"; exit 1; fi
+h="" beats=0 backoff=0
+while :; do
+ n=$(digest)
+ if [ "$n" != "$h" ] || [ "$beats" -ge 5 ]; then
+ if push; then h=$n; beats=0; backoff=0
+ else backoff=$(( backoff ? backoff * 2 : SINK_INTERVAL )); [ "$backoff" -le 900 ] || backoff=900; fi
+ else
+ beats=$((beats + 1))
+ fi
+ sleep $(( SINK_INTERVAL + backoff ))
+done
+'
+
+# SINK_STOP: end the running pusher (its process group, so an upload in
+# flight dies with it) and wait for it, so no older snapshot lands later.
+SINK_STOP='p=$(cat ~/.ubirun-sink.pid 2>/dev/null); if [ -n "$p" ]; then kill -TERM -- "-$p" 2>/dev/null || kill -TERM "$p" 2>/dev/null; for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20; do kill -0 "$p" 2>/dev/null || break; sleep 0.5; done; kill -KILL -- "-$p" 2>/dev/null; rm -f ~/.ubirun-sink.pid; fi;'
+
+# sink_start NAME SPEC PATH...: write the pusher's config (600; the URL only in
+# ~/.ubirun-sink.curl, over ssh stdin), upload it and start it outside any ssh
+# session, and mark the state dir so down flushes it.
+sink_start() {
+ local name=$1 spec=$2 kind interval=$SINK_INTERVAL url sdir=""
+ shift 2
+ kind=${spec%%:*}
+ [ "$kind" != file ] || sdir=${spec#file:}
+ [ "$kind" = file ] || [ "$interval" -ge 60 ] || interval=60
+ { printf 'SINK_KIND=%q\nSINK_DIR=%q\nSINK_VM=%q\nSINK_OWNER=%q\nSINK_INTERVAL=%q\nSINK_MAX_MB=%q\n' \
+ "$kind" "$sdir" "$name" "$OWNER" "$interval" "$SINK_MAX_MB"
+ printf 'SINK_PATHS=(%s)\n' "$(qwords "$@")"; } | remote "$name" 'umask 077 && cat > ~/.ubirun-sink.conf && chmod 600 ~/.ubirun-sink.conf'
+ if [ "$kind" = https-put ]; then
+ url=${spec#https-put:}; url=${url//\\/\\\\}; url=${url//\"/\\\"}
+ printf 'url = "%s"\n' "$url" | remote "$name" 'umask 077 && cat > ~/.ubirun-sink.curl && chmod 600 ~/.ubirun-sink.curl'
+ fi
+ printf %s "$SINK_SH" | remote "$name" 'umask 077 && cat > ~/.ubirun-sink.sh'
+ remote "$name" "$SINK_STOP"' if command -v setsid >/dev/null 2>&1; then setsid -f bash ~/.ubirun-sink.sh >~/.ubirun-sink.log 2>&1; else nohup bash ~/.ubirun-sink.sh >~/.ubirun-sink.log 2>&1 & fi' /dev/null
+ : >"$(state_dir "$name")/sink"
+ log "sink: pushing $# path(s) to a $kind sink every ${interval}s (pid in ~/.ubirun-sink.pid on $name)"
+}
+
+# sink_flush NAME: stop the pusher, then one last push before down destroys
+# NAME (150 s cap, above curl's 120). A failure prints SINK_FLUSH_FAILED and
+# adds NAME to SINK_FLUSH_FAILED, which turns a passing run or verify of that
+# VM into exit 1; the VM is destroyed either way.
+sink_flush() {
+ local out
+ if out=$(remote "$1" "$SINK_STOP"' timeout 150 bash ~/.ubirun-sink.sh --once' /dev/null); then
+ log "sink: final push done for $1"
+ return 0
+ fi
+ SINK_FLUSH_FAILED="$SINK_FLUSH_FAILED $1 "
+ out=$(tail -n 1 <<<"$out")
+ echo "SINK_FLUSH_FAILED: vm=$1 ${out:-seq=unknown last_push=unknown} (results in the sink may be incomplete)" >&2
+}
+
new_name() {
echo "$PREFIX-$OWNER-$(date +%s)-$(head -c4 /dev/urandom | od -An -tx1 | tr -d ' \n')-t$TTL_HOURS"
}
@@ -943,7 +1258,7 @@ UP_NAME=""
UP_READY=""
cmd_up() {
require_owner
- local size=$DEFAULT_SIZE location=$DEFAULT_LOCATION name="" storage="" image=ubuntu-noble
+ local size=$DEFAULT_SIZE location=$DEFAULT_LOCATION name="" storage="" image=ubuntu-noble sink=${UBI_SINK:-} tags=() sink_paths=()
while [ $# -gt 0 ]; do
case $1 in
-s|--size) size=$2; shift 2 ;;
@@ -951,11 +1266,17 @@ cmd_up() {
-n|--name) name=$2; shift 2 ;;
-S|--storage) check_storage "$2"; storage=$2; shift 2 ;;
-b|--image) image=$2; shift 2 ;;
+ --tag) [[ "$2" =~ ^[A-Za-z0-9_.-]+=[A-Za-z0-9_.:/@+-]*$ ]] || die "up: --tag $2: expected key=value (letters, digits and _.:/@+- only)"; tags+=("$2"); shift 2 ;;
+ --sink) sink=$2; shift 2 ;;
+ --sink-path) [[ "$2" != /* && "/$2/" != */../* && -n "$2" ]] || die "up: --sink-path $2: must be a path under ~ on the VM"; sink_paths+=("$2"); shift 2 ;;
+ --counted) COUNTED=1; shift ;;
*) die "up: unknown option $1" ;;
esac
done
[ -n "$name" ] || name=$(new_name)
valid_name "$name" || die "invalid VM name '$name' (Ubicloud allows 1-63 of a-z, 0-9 and '-', starting and ending with a letter or digit)"
+ [ "$COUNTED" != 1 ] || recovery_preflight
+ [ -z "$sink" ] || sink_check "$sink"
if [ "$REAP" != 0 ]; then
cmd_reap || log "reap failed; continuing"
fi
@@ -969,12 +1290,14 @@ cmd_up() {
mkdir -p "$dir"
chmod 700 "$dir"
ssh-keygen -q -t ed25519 -N '' -C "$name" -f "$dir/key"
+ [ ${#tags[@]} -eq 0 ] || printf '%s\n' "${tags[@]}" >"$dir/tags"
local args=(vm "$location/$name" create -s "$size" -b "$image")
[ -z "$storage" ] || args+=(-S "$storage")
args+=("$(cat "$dir/key.pub")")
create_at=$(date +%s)
write_state "$name" "$location" "$size" "" unknown "$create_at"
+ bundle_save "$name"
record_vm "$name" "$location"
UP_NAME=$name
log "creating $location/$name ($size)"
@@ -984,6 +1307,7 @@ cmd_up() {
trap 'interrupted=1' INT TERM HUP QUIT
cli "${args[@]}" >/dev/null 2>"$dir/create.err" || created=no
write_state "$name" "$location" "$size" "" "$created" "$create_at"
+ [ "$created" = no ] || bundle_save "$name"
trap 'exit 130' INT TERM HUP QUIT
[ -z "$interrupted" ] || exit 130
if [ "$created" = no ]; then
@@ -1010,6 +1334,7 @@ cmd_up() {
sleep "$POLL"
done
write_state "$name" "$location" "$size" "$ip" yes "$create_at"
+ bundle_save "$name"
load "$name"
deadline=$(( $(date +%s) + 300 ))
@@ -1019,6 +1344,10 @@ cmd_up() {
sleep "$POLL"
done
remote "$name" 'cloud-init status --wait >/dev/null 2>&1 || true'
+ if [ -n "$sink" ]; then
+ sink_start "$name" "$sink" ${sink_paths[@]+"${sink_paths[@]}"}
+ bundle_save "$name"
+ fi
UP_READY=1
log "ready: $name ($IP)"
echo "$name"
@@ -1044,6 +1373,7 @@ cmd_down() {
if [ -f "$dir/env" ]; then
load "$name"
loc=$LOCATION
+ [ ! -f "$dir/sink" ] || [ -z "$IP" ] || sink_flush "$name"
if [ -S "$dir/ctl" ] && [ -n "$IP" ]; then
# shellcheck disable=SC2046
ssh $(ssh_opts) -O exit "ubi@$IP" >/dev/null 2>&1 || true
@@ -1075,11 +1405,11 @@ cmd_down() {
log "destroy requested: $loc/$name"
fi
elif [ "$code" = 404 ]; then
- if [ "$seen" = 1 ] || [ "$CREATED" != unknown ] || { [ $(( now - CREATE_AT )) -ge "$CREATE_GRACE" ] \
- && { [ "$CREATE_PID" = "$$" ] || ! kill -0 "$CREATE_PID" 2>/dev/null; }; }; then
+ if vm_gone_final "$seen" "$CREATED" "$CREATE_AT" "$CREATE_PID"; then
rm -f "$out"
rm -rf "$dir"
forget_vm "$name"
+ [ -z "$RECOVERY_DIR" ] || rm -f "$RECOVERY_DIR"/*/"$name.bundle"
if [ "$seen" = 1 ]; then log "destroyed ${loc:-?}/$name"; else log "gone: ${loc:-?}/$name (never existed or already destroyed)"; fi
return 0
fi
@@ -1201,11 +1531,27 @@ cmd_pull() {
remote "$name" "cd $dir && tar -czf - $(basename "$from")" | tar -xzf - -C "$to"
}
-# pass_name NAME: a variable this runner may forward to a VM. Its own
-# credentials (UBICLOUD_*) never leave this machine, whoever asks.
+# pass_name NAME: a variable this runner may forward to a VM: one the caller's
+# environment held when the runner started. Its own credentials (UBICLOUD_*),
+# its recovery secret and sink URL, and every variable it sets itself
+# (RECOVERY_SECRET holds the Ubicloud key by default) never leave this machine.
pass_name() {
[[ "$1" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || die "--pass $1: not a variable name"
case $1 in UBICLOUD_*) die "--pass $1: the runner never forwards its own Ubicloud credentials to a VM" ;; esac
+ case $1 in RECOVERY_SECRET|UBI_RECOVERY_KEY|UBI_SINK) die "--pass $1: the runner never forwards its recovery secret or sink URL to a VM" ;; esac
+ case $1 in INHERITED_NAMES|INHERITED_VALUES|INHERITED_ENV|PASS_VALUE|_ubi_n) die "--pass $1: the runner never forwards its own variables" ;; esac
+ [[ "$INHERITED_ENV" == *" $1 "* ]] || die "--pass $1: not in this shell's environment; the runner forwards only variables you exported, never its own"
+}
+
+# inherited NAME: PASS_VALUE becomes NAME's value as the caller exported it.
+inherited() {
+ local i
+ for i in "${!INHERITED_NAMES[@]}"; do
+ [ "${INHERITED_NAMES[i]}" = "$1" ] || continue
+ PASS_VALUE=${INHERITED_VALUES[i]}
+ return 0
+ done
+ die "--pass $1: not in this shell's environment"
}
# inside_dir DIR ROOT: DIR resolves, symlinks followed, to ROOT or below it.
@@ -1244,7 +1590,10 @@ run_teardown() {
left=unknown others=unknown
fi
leftover "left=$left owner=$OWNER vm=$RUN_VM others=$others"
- [ "$left" = 0 ] && return 0
+ if [ "$left" = 0 ]; then
+ [[ "$SINK_FLUSH_FAILED" != *" $RUN_VM "* ]] || [ "$rc" -ne 0 ] || exit 1
+ return 0
+ fi
log "VM cleanup not confirmed for $RUN_VM (left=$left); destroy it with: $0 down $RUN_VM"
[ "$rc" -ne 0 ] || exit 1
}
@@ -1253,16 +1602,21 @@ TIER_NAMES=() TIER_CMDS=() RESUME=1 RERUN_FAILED=0 FORCE_ATTACH="" RUN_ARGS=()
cmd_run() {
require_owner
local up_args=() src=. dest="" setup="" keep=0 pulls=() envs=() passes=() key_inputs=() probe=0
- RUN_ARGS=("$@")
+ # The run record replays RUN_ARGS on attach. Each option's words are copied as
+ # it is parsed, so a --sink URL stays out of it (pass it as UBI_SINK).
+ local all=("$@") pos=0 opt left
+ RUN_ARGS=()
while [ $# -gt 0 ]; do
+ opt=$1 left=$#
case $1 in
-S|--storage) check_storage "$2"; up_args+=("$1" "$2"); shift 2 ;;
- -s|--size|-l|--location|-n|--name|-b|--image) up_args+=("$1" "$2"); shift 2 ;;
+ -s|--size|-l|--location|-n|--name|-b|--image|--tag|--sink|--sink-path) up_args+=("$1" "$2"); shift 2 ;;
+ --counted) COUNTED=1; shift ;;
--src) src=$2; shift 2 ;;
--dest) dest=$2; shift 2 ;;
--setup) setup=$2; shift 2 ;;
--env) envs+=("$2"); shift 2 ;;
- --pass) pass_name "$2"; [ -n "${!2+x}" ] || die "--pass $2: not set locally"; passes+=("$2"); shift 2 ;;
+ --pass) pass_name "$2"; passes+=("$2"); shift 2 ;;
--pull) pulls+=("$2"); shift 2 ;;
--keep) keep=1; shift ;;
--key-input) key_inputs+=("$2"); shift 2 ;;
@@ -1273,16 +1627,21 @@ cmd_run() {
--) shift; break ;;
*) die "run: unknown option $1" ;;
esac
+ [ "$opt" = --sink ] || RUN_ARGS+=("${all[@]:pos:left-$#}")
+ pos=$(( pos + left - $# ))
done
+ [ "$pos" -ge ${#all[@]} ] || RUN_ARGS+=("${all[@]:pos}")
[ $# -gt 0 ] || [ ${#TIER_NAMES[@]} -gt 0 ] || die "run: missing command after --"
[ -z "$setup" ] || [ -f "$setup" ] || die "setup script not found: $setup"
command -v git >/dev/null || die "git is required: the run key fingerprints the checkout with it"
src=$(cd "$src" && pwd)
[ -n "$dest" ] || dest="work/$(basename "$src")"
- local i name="" size=$DEFAULT_SIZE location=$DEFAULT_LOCATION image=ubuntu-noble storage="" e n
+ local i name="" size=$DEFAULT_SIZE location=$DEFAULT_LOCATION image=ubuntu-noble storage="" e n sink=${UBI_SINK:-} sink_paths=()
for (( i = 0; i < ${#up_args[@]}; i += 2 )); do
case ${up_args[i]} in
+ --sink) sink=${up_args[i+1]} ;;
+ --sink-path) sink_paths+=("${up_args[i+1]}") ;;
-n|--name) name=${up_args[i+1]} ;;
-s|--size) size=${up_args[i+1]} ;;
-l|--location) location=${up_args[i+1]} ;;
@@ -1300,7 +1659,7 @@ cmd_run() {
printf 'command %q\n' "$*"
if [ -n "$setup" ]; then echo "setup $(sha256 <"$setup")"; else echo "setup none"; fi
for e in ${envs[@]+"${envs[@]}"}; do printf 'env %q\n' "$e"; done
- for n in ${passes[@]+"${passes[@]}"}; do printf 'pass %s %s\n' "$n" "$(printf %s "${!n}" | sha256)"; done
+ for n in ${passes[@]+"${passes[@]}"}; do inherited "$n"; printf 'pass %s %s\n' "$n" "$(printf %s "$PASS_VALUE" | sha256)"; done
printf 'vm %q %q %q %q\n' "$size" "$location" "$image" "$storage"
echo "base $(base_sha "$src")"
echo "runner $(sha256 <"${BASH_SOURCE[0]}")"
@@ -1352,6 +1711,16 @@ cmd_run() {
cmd_down "$attach" >/dev/null || log "WARNING: failed to destroy $attach; run: $0 down $attach"
attach=""
fi
+ if [ -n "$attach" ] && [ "$COUNTED" = 1 ]; then
+ recovery_preflight
+ local opened rbt
+ rbt=$(mktemp -d)
+ opened=0
+ printf %s "$RECOVERY_SECRET" | python3 -c "$RB_PY" open "$RECOVERY_DIR/$OWNER/$attach.bundle" "$rbt" "$attach" "$OWNER" 2>/dev/null && opened=1
+ rm -rf "$rbt"
+ [ "$opened" = 1 ] \
+ || die "UBI_RECOVERY_REQUIRED: a counted run would reattach to $attach, which has no recovery bundle under $RECOVERY_DIR/$OWNER that opens under this secret; destroy it ($0 down $attach) and rerun"
+ fi
[ -z "$attach" ] || name=$attach
[ -n "$name" ] || { name=$(new_name); up_args+=(-n "$name"); }
RUN_VM=$name
@@ -1363,6 +1732,11 @@ cmd_run() {
if [ -n "$attach" ]; then
load "$name"
log "reattached to $name created_at=$CREATE_AT key=${RUN_KEY:0:12}"
+ if [ -n "$sink" ]; then
+ sink_check "$sink"
+ sink_start "$name" "$sink" ${sink_paths[@]+"${sink_paths[@]}"}
+ bundle_save "$name"
+ fi
else
cmd_up "${up_args[@]}" >/dev/null
trap 'exit 130' INT TERM QUIT
@@ -1390,7 +1764,7 @@ cmd_run() {
qdest=$(printf %q "$dest")
if [ ! -f "$dir/synced" ]; then
{ for e in ${envs[@]+"${envs[@]}"}; do printf 'export %s=%q\n' "${e%%=*}" "${e#*=}"; done
- for n in ${passes[@]+"${passes[@]}"}; do printf 'export %s=%q\n' "$n" "${!n}"; done; } \
+ for n in ${passes[@]+"${passes[@]}"}; do inherited "$n"; printf 'export %s=%q\n' "$n" "$PASS_VALUE"; done; } \
| remote "$name" 'umask 077 && cat > ~/.ubirun-env'
cmd_sync "$name" "$src" "$dest"
# A subdirectory of a checkout uploads the whole .git with only its own
@@ -1526,8 +1900,8 @@ print("cfg_cmd=" + q(c.get("command", "")))
case $1 in
--) shift; user_cmd=("$@"); break ;;
--trust-config) trust=1; shift ;;
- --keep|--resume|--no-resume|--rerun-failed|--probe) user_pre+=("$1"); shift ;;
- --pass|-S|--storage|-s|--size|-l|--location|-n|--name|-b|--image|--src|--dest|--setup|--env|--pull)
+ --keep|--resume|--no-resume|--rerun-failed|--probe|--counted) user_pre+=("$1"); shift ;;
+ --pass|-S|--storage|-s|--size|-l|--location|-n|--name|-b|--image|--src|--dest|--setup|--env|--pull|--tag|--sink|--sink-path)
[ $# -ge 2 ] || die "verify: $1 needs a value"
[ "$1" != --pass ] || granted+=("$2")
user_pre+=("$1" "$2"); shift 2 ;;
@@ -1569,9 +1943,19 @@ usage: ubi-runner.sh [args]
here (--pass NAME, or all: --trust-config). With tiers, a pass checkpoint
under the same run key is reused (resume is the default)
attach NAME resume the run recorded for NAME on this machine, as a rerun would
- up [-s SIZE] [-l LOCATION] [-n NAME] [-S STORAGE_GIB] [-b IMAGE]
+ up [-s SIZE] [-l LOCATION] [-n NAME] [-S STORAGE_GIB] [-b IMAGE] [--tag K=V]...
+ [--sink https-put:URL] [--sink-path PATH]... [--counted]
create a VM and wait for SSH; prints its name
- (STORAGE_GIB: one of $ALLOWED_STORAGE)
+ (STORAGE_GIB: one of $ALLOWED_STORAGE). --tag is kept in the VM's
+ state and recovery bundle; --sink starts a pusher on the VM that
+ uploads heartbeat.json and the PATH entries under ~ as results.tgz;
+ --counted (or UBI_COUNTED=1) refuses without a recovery bundle
+ (UBI_RECOVERY_REQUIRED, UBI_RECOVERY_UNAVAILABLE). run and verify
+ take the same four options
+ recover [--owner OLD] [--dir DIR]
+ rebuild this machine's state for the VMs with a bundle under
+ DIR/OLD (UBI_RECOVERY_DIR, this owner); prints RECOVERED, RECOVER_GONE
+ or RECOVER_FAILED per VM. Run it only once the creating machine is dead
ssh NAME [COMMAND] shell or login-shell command on the VM (user ubi, passwordless sudo)
sync NAME [SRC] [DEST] stream a checkout (tracked + untracked-unignored + .git)
pack [SRC] write that checkout tarball to stdout
@@ -1605,7 +1989,10 @@ env: UBI_TTL_HOURS (${TTL_HOURS}h in the name, 1-999), UBI_REAP (0: up skips the
UBI_GC_HOURS (unset/0: no sweep on up), UBI_CREATE_GRACE (${CREATE_GRACE}s),
UBI_DOWN_TIMEOUT (${DOWN_TIMEOUT}s), UBI_API_TIMEOUT (${API_TIMEOUT}s), UBI_VM_RECORD (scratch VM-id file),
UBI_ALLOWED_STORAGE (the -S sizes Ubicloud accepts; default "320 640"),
- UBI_CHECKPOINT_DIR (tier checkpoints; $CHECKPOINT_DIR), UBI_CHECKPOINT_MAX_AGE (${CHECKPOINT_MAX_AGE}s a pass is reused)
+ UBI_CHECKPOINT_DIR (tier checkpoints; $CHECKPOINT_DIR), UBI_CHECKPOINT_MAX_AGE (${CHECKPOINT_MAX_AGE}s a pass is reused),
+ UBI_RECOVERY_DIR (recovery bundles; GSTACK_CAPY_RECOVERY_DIR on Capy), UBI_RECOVERY_KEY (bundle secret;
+ else UBICLOUD_API_KEY), UBI_COUNTED, UBI_SINK (a sink spec), UBI_SINK_INTERVAL (${SINK_INTERVAL}s, at least 60
+ for https-put), UBI_SINK_MAX_MB (${SINK_MAX_MB}: a bigger results.tgz is skipped, sink_skipped=size)
EOF
}
@@ -1630,6 +2017,7 @@ case $cmd in
unpack) cmd_unpack "$@" ;;
pull) cmd_pull "$@" ;;
down) cmd_down "$@" ;;
+ recover) cmd_recover "$@" ;;
list) cmd_list "$@" ;;
usage) cmd_usage ;;
owner) echo "$OWNER" ;;
diff --git a/test/fixtures/context-budget.json b/test/fixtures/context-budget.json
index 48a84e7023..37a9ab1dc0 100644
--- a/test/fixtures/context-budget.json
+++ b/test/fixtures/context-budget.json
@@ -67,7 +67,7 @@
"spec": 9136,
"sync-gbrain": 9749,
"test-audit": 4622,
- "ubicloud": 3594,
+ "ubicloud": 3971,
"unfreeze": 409,
"verify": 2896,
"write-skill": 2264
diff --git a/test/test-of-test-ratchet.test.ts b/test/test-of-test-ratchet.test.ts
index 119b7b7757..f5e0622590 100644
--- a/test/test-of-test-ratchet.test.ts
+++ b/test/test-of-test-ratchet.test.ts
@@ -241,6 +241,7 @@ const BASELINE = [
'test/test-free-shards-capture.test.ts',
'test/timeline.test.ts',
'test/ubicloud-runner-reattach.test.ts', // GSTA-151: split from test/ubicloud-runner.test.ts for shard time; runs scripts/ubicloud/ubi-runner.sh through test/helpers/ubi-runner-fake-vm.ts
+ 'test/ubicloud-runner-recovery.test.ts', // GST-1220: recovery bundle and results sink; runs scripts/ubicloud/ubi-runner.sh through test/helpers/ubi-runner-fake-vm.ts
'test/ubicloud-runner-tiers.test.ts', // GSTA-151: split from test/ubicloud-runner.test.ts for shard time; runs scripts/ubicloud/ubi-runner.sh through test/helpers/ubi-runner-fake-vm.ts
'test/workflow-judge-cache.test.ts', // slices test/skill-llm-eval.test.ts source (recorded 2026-10 when the ratchet learned paid-source slicing)
'test/workflow-judge-input.test.ts', // slices test/skill-llm-eval.test.ts source (recorded 2026-10 when the ratchet learned paid-source slicing)
diff --git a/test/ubicloud-runner-recovery.test.ts b/test/ubicloud-runner-recovery.test.ts
new file mode 100644
index 0000000000..a6c21d174f
--- /dev/null
+++ b/test/ubicloud-runner-recovery.test.ts
@@ -0,0 +1,316 @@
+/**
+ * GST-1220: a dead controller strands nothing. The VM pushes its own results to the
+ * caller's sink, and `recover` rebuilds a VM's local state on another controller
+ * from the encrypted bundle `up` wrote. Offline: the fake API and fake VM only.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { creates, fakeVm, gitSrc, run, until, vmDirs, type FakeVm } from './helpers/ubi-runner-fake-vm';
+
+const fixtures: FakeVm[] = [];
+const make = () => { const f = fakeVm(); fixtures.push(f); return f; };
+const stopSink = (f: FakeVm) => {
+ const pidFile = join(f.vm, '.ubirun-sink.pid');
+ if (!existsSync(pidFile)) return;
+ const pid = Number(readFileSync(pidFile, 'utf8').trim());
+ if (!pid) return;
+ try { process.kill(-pid, 'SIGKILL'); } catch { /* not a group leader or gone */ }
+ try { process.kill(pid, 'SIGKILL'); } catch { /* gone */ }
+};
+afterEach(() => {
+ for (const f of fixtures.splice(0)) { stopSink(f); rmSync(f.root, { recursive: true, force: true }); }
+});
+const out = (r: { stdout: Buffer; stderr: Buffer }) => r.stdout.toString() + r.stderr.toString();
+const tarList = (tgz: string) => Bun.spawnSync(['tar', '-tzf', tgz], { timeout: 10_000 }).stdout.toString();
+const heartbeat = (tgz: string) => {
+ const r = Bun.spawnSync(['tar', '-xzOf', tgz, 'heartbeat.json'], { timeout: 10_000 });
+ try { return JSON.parse(r.stdout.toString()) as { vm: string; seq: number }; } catch { return { vm: '', seq: 0 }; }
+};
+const fileSink = (f: FakeVm, dir = join(f.root, 'sink')) => ({ UBI_SINK: 'file:' + dir, UBI_SINK_ALLOW_FILE: '1', UBI_SINK_INTERVAL: '1', UBI_REAP: '0' });
+const keyBody = (key: string) => key.split('\n').filter(l => l && !l.startsWith('-----'));
+
+describe('ubi-runner results sink (GST-1220 a)', () => {
+ test('the controller dies after up, and the VM still pushes its results to the sink', async () => {
+ const f = make();
+ const up = run(f, ['up', '--sink-path', 'results'], fileSink(f));
+ expect(out(up)).toContain('sink: pushing');
+ expect(up.exitCode).toBe(0);
+ const name = up.stdout.toString().trim();
+ rmSync(f.state, { recursive: true, force: true });
+ mkdirSync(join(f.vm, 'results'), { recursive: true });
+ writeFileSync(join(f.vm, 'results', 'r.json'), '{"score": 7}\n');
+ const tgz = join(f.root, 'sink', name, 'results.tgz');
+ await until(() => existsSync(tgz) && tarList(tgz).includes('results/r.json'), 30_000);
+ const first = heartbeat(tgz);
+ expect(first.vm).toBe(name);
+ writeFileSync(join(f.vm, 'results', 'r2.json'), '{"score": 8}\n');
+ await until(() => heartbeat(tgz).seq > first.seq && tarList(tgz).includes('results/r2.json'), 30_000);
+ }, 90_000);
+
+ test('a sink must be a presigned https-put URL; file: only under the test switch; nothing is created otherwise', () => {
+ const f = make();
+ for (const spec of ['http://plain.example/x', 'git:https://github.com/a/b', 'file:/tmp/x']) {
+ const r = run(f, ['up'], { UBI_SINK: spec, UBI_REAP: '0' });
+ expect(r.exitCode).not.toBe(0);
+ expect(out(r)).toContain('UBI_SINK_INVALID');
+ }
+ expect(creates(f)).toBe(0);
+ });
+
+ test('the presigned URL reaches the VM only through a 600 file, never a command line or a log', async () => {
+ const f = make();
+ const url = 'https://bucket.example/o?X-Amz-Signature=sekritsig123';
+ const up = run(f, ['up'], { UBI_SINK: 'https-put:' + url, UBI_REAP: '0' });
+ expect(up.exitCode).toBe(0);
+ await until(() => existsSync(join(f.vm, '.ubirun-sink.curl')) && existsSync(join(f.vm, '.ubirun-sink.pid')), 30_000);
+ expect(readFileSync(join(f.vm, '.ubirun-sink.curl'), 'utf8')).toContain('sekritsig123');
+ expect(statSync(join(f.vm, '.ubirun-sink.curl')).mode & 0o777).toBe(0o600);
+ expect(statSync(join(f.vm, '.ubirun-sink.conf')).mode & 0o777).toBe(0o600);
+ expect(f.ssh()).not.toContain('sekritsig123');
+ expect(out(up)).not.toContain('sekritsig123');
+ }, 60_000);
+
+ test('run keeps the presigned URL out of its run record, and a command word --sink stays in it', async () => {
+ const f = make();
+ writeFileSync(join(f.root, 'make-test.sh'), 'echo begin; sleep 3\n');
+ const a = f.spawn(['run', '--sink', 'https-put:https://b.example/o?X-Amz-Signature=sekritsig456', '--src', gitSrc(f), '--', 'make', 'test', '--sink', 'kept'], { UBI_REAP: '0' });
+ await until(() => vmDirs(f).some(d => existsSync(join(f.state, d, 'command.out')) && readFileSync(join(f.state, d, 'command.out'), 'utf8').includes('begin')), 30_000);
+ const name = vmDirs(f)[0]!;
+ const record = readFileSync(join(f.state, name, 'run'), 'utf8');
+ expect(record).not.toContain('sekritsig456');
+ expect(record).toContain(' -- make test --sink kept');
+ expect(await a.exited).toBe(0);
+ expect(f.listed().trim()).toBe('');
+ }, 90_000);
+
+ test('a failed final push prints SINK_FLUSH_FAILED, the VM is destroyed anyway, and run exits 1', () => {
+ const f = make();
+ const blocker = join(f.root, 'blocker');
+ writeFileSync(blocker, 'a file where the sink directory should be\n');
+ const r = run(f, ['run', '--src', gitSrc(f), '--', 'echo hi'], { ...fileSink(f, blocker), UBI_SINK_INTERVAL: '3600' });
+ expect(out(r)).toContain('SINK_FLUSH_FAILED: vm=');
+ expect(r.exitCode).toBe(1);
+ expect(f.listed().trim()).toBe('');
+ }, 90_000);
+
+ test('a snapshot over UBI_SINK_MAX_MB keeps the last good one, and the final flush stops the pusher and fails', async () => {
+ const f = make();
+ const env = { ...fileSink(f), UBI_SINK_MAX_MB: '1' };
+ const up = run(f, ['up', '--sink-path', 'results', '--sink-path', '.'], env);
+ expect(up.exitCode).toBe(0);
+ const name = up.stdout.toString().trim();
+ mkdirSync(join(f.vm, 'results'), { recursive: true });
+ writeFileSync(join(f.vm, 'results', 'r.json'), '{"score": 7}\n');
+ const tgz = join(f.root, 'sink', name, 'results.tgz');
+ await until(() => existsSync(tgz) && tarList(tgz).includes('results/r.json'), 30_000);
+ expect(tarList(tgz)).not.toContain('.ubirun-');
+ const pid = Number(readFileSync(join(f.vm, '.ubirun-sink.pid'), 'utf8').trim());
+ writeFileSync(join(f.vm, 'results', 'big.bin'), Buffer.from(Array.from({ length: 3 << 20 }, () => Math.floor(Math.random() * 256))));
+ const down = run(f, ['down', name], env);
+ expect(down.exitCode).toBe(0);
+ expect(out(down)).toMatch(new RegExp('SINK_FLUSH_FAILED: vm=' + name + ' seq=\\d+ last_push=\\d+ sink_skipped=size'));
+ expect(tarList(tgz)).toContain('results/r.json');
+ expect(tarList(tgz)).not.toContain('big.bin');
+ expect(() => process.kill(pid, 0)).toThrow();
+ }, 90_000);
+
+ test('a reaped VM whose final push fails does not fail a run that passed on its own VM', () => {
+ const f = make();
+ const blocker = join(f.root, 'blocker');
+ writeFileSync(blocker, 'a file where the sink directory should be\n');
+ const old = 'ubirun-thrd1-1000000000-abcd1234-t1';
+ expect(run(f, ['up', '-n', old], { ...fileSink(f, blocker), UBI_SINK_INTERVAL: '3600' }).exitCode).toBe(0);
+ const r = run(f, ['run', '--src', gitSrc(f), '--', 'echo hi']);
+ expect(out(r)).toContain('SINK_FLUSH_FAILED: vm=' + old);
+ expect(r.exitCode).toBe(0);
+ expect(f.listed().trim()).toBe('');
+ }, 90_000);
+});
+
+describe('ubi-runner recovery bundle (GST-1220 b)', () => {
+ const setup = () => {
+ const f = make();
+ const rec = join(f.root, 'recovery');
+ const up = run(f, ['up', '--tag', 'shard=3'], { UBI_RECOVERY_DIR: rec, UBI_REAP: '0' });
+ expect(up.exitCode).toBe(0);
+ const name = up.stdout.toString().trim();
+ const key = readFileSync(join(f.state, name, 'key'), 'utf8');
+ const bundle = join(rec, 'thrd1', name + '.bundle');
+ return { f, rec, up, name, key, bundle, state2: join(f.root, 'state2') };
+ };
+
+ test('recover rebuilds a VM on a new controller, and pull and down work from there', () => {
+ const { f, rec, up, name, key, bundle, state2 } = setup();
+ expect(existsSync(bundle)).toBe(true);
+ expect(statSync(bundle).mode & 0o777).toBe(0o600);
+ expect(readFileSync(bundle, 'latin1')).not.toContain('PRIVATE KEY');
+ const env2 = { UBI_RECOVERY_DIR: rec, UBI_RUNNER_STATE: state2, UBI_OWNER: 'thrd2', UBI_REAP: '0' };
+ const r = run(f, ['recover', '--owner', 'thrd1'], env2);
+ expect(r.exitCode).toBe(0);
+ expect(r.stdout.toString()).toContain(`RECOVERED: vm=${name} ip=192.0.2.1 owner=thrd1 tags=shard=3`);
+ expect(readFileSync(join(state2, name, 'key'), 'utf8')).toBe(key);
+ expect(statSync(join(state2, name)).mode & 0o777).toBe(0o700);
+ expect(readFileSync(join(state2, name, 'env'), 'utf8')).toMatch(/^CREATE_PID=$/m);
+ const again = run(f, ['recover', '--owner', 'thrd1'], env2);
+ expect(again.stdout.toString()).toContain(`RECOVER_FAILED: vm=${name} code=RECOVER_EXISTS`);
+ mkdirSync(join(f.root, 'remote-fs', 'results'), { recursive: true });
+ writeFileSync(join(f.root, 'remote-fs', 'results', 'r.json'), '{}\n');
+ expect(run(f, ['pull', name, 'results', join(f.root, 'pulled')], env2).exitCode).toBe(0);
+ expect(existsSync(join(f.root, 'pulled', 'results', 'r.json'))).toBe(true);
+ const down = run(f, ['down', name], env2);
+ expect(down.exitCode).toBe(0);
+ expect(existsSync(bundle)).toBe(false);
+ expect(f.listed().trim()).toBe('');
+ for (const line of keyBody(key)) for (const text of [out(up), out(r), out(down), f.ssh()]) expect(text).not.toContain(line);
+ }, 90_000);
+
+ test('a wrong secret or a tampered bundle never decrypts, writes no state and keeps the bundle', () => {
+ const { f, rec, name, bundle, state2 } = setup();
+ const env2 = { UBI_RECOVERY_DIR: rec, UBI_RUNNER_STATE: state2, UBI_REAP: '0' };
+ const wrong = run(f, ['recover'], { ...env2, UBI_RECOVERY_KEY: 'not-the-secret' });
+ expect(wrong.stdout.toString()).toContain(`RECOVER_FAILED: vm=${name} code=RECOVER_DECRYPT_FAILED`);
+ const bytes = readFileSync(bundle);
+ bytes[bytes.length - 40] ^= 1;
+ writeFileSync(bundle, bytes);
+ chmodSync(bundle, 0o600);
+ const tampered = run(f, ['recover'], env2);
+ expect(tampered.stdout.toString()).toContain(`RECOVER_FAILED: vm=${name} code=RECOVER_DECRYPT_FAILED`);
+ expect(existsSync(join(state2, name))).toBe(false);
+ expect(existsSync(bundle)).toBe(true);
+ }, 60_000);
+
+ test('a valid bundle under another VM or owner name is refused before the API is asked', () => {
+ const { f, rec, name, bundle, state2 } = setup();
+ const other = 'ubirun-other-1700000000-dead1234-t3';
+ writeFileSync(join(rec, 'thrd1', other + '.bundle'), readFileSync(bundle));
+ mkdirSync(join(rec, 'thrd9'), { recursive: true });
+ writeFileSync(join(rec, 'thrd9', name + '.bundle'), readFileSync(bundle));
+ writeFileSync(join(f.root, 'listed'), f.listed() + 'us-east-a2 ' + other + '\n');
+ const env2 = { UBI_RECOVERY_DIR: rec, UBI_RUNNER_STATE: state2, UBI_REAP: '0' };
+ const r = run(f, ['recover'], env2);
+ expect(r.stdout.toString()).toContain(`RECOVER_FAILED: vm=${other} code=RECOVER_DECRYPT_FAILED`);
+ expect(r.stdout.toString()).toContain(`RECOVERED: vm=${name}`);
+ expect(existsSync(join(state2, other))).toBe(false);
+ const adopted = run(f, ['recover', '--owner', 'thrd9'], { ...env2, UBI_RUNNER_STATE: join(f.root, 'state3') });
+ expect(adopted.stdout.toString()).toContain(`RECOVER_FAILED: vm=${name} code=RECOVER_DECRYPT_FAILED`);
+ }, 60_000);
+
+ test('an API outage keeps the bundle; a VM that is gone drops it', () => {
+ const { f, rec, name, bundle, state2 } = setup();
+ const env2 = { UBI_RECOVERY_DIR: rec, UBI_RUNNER_STATE: state2, UBI_REAP: '0' };
+ writeFileSync(join(f.root, 'listed.show-fails'), '');
+ const down = run(f, ['recover'], env2);
+ expect(down.stdout.toString()).toContain(`RECOVER_FAILED: vm=${name} code=RECOVER_API_UNAVAILABLE`);
+ expect(existsSync(bundle)).toBe(true);
+ rmSync(join(f.root, 'listed.show-fails'));
+ writeFileSync(join(f.root, 'listed'), '');
+ const gone = run(f, ['recover'], env2);
+ expect(gone.stdout.toString()).toContain(`RECOVER_GONE: vm=${name}`);
+ expect(existsSync(bundle)).toBe(false);
+ }, 60_000);
+
+ test('a counted run refuses before any create without a recovery directory', () => {
+ const f = make();
+ for (const [args, extra] of [[['up'], { UBI_COUNTED: '1' }], [['up', '--counted'], {}]] as [string[], Record][]) {
+ const r = run(f, args, { ...extra, UBI_REAP: '0' });
+ expect(r.exitCode).not.toBe(0);
+ expect(out(r)).toContain('UBI_RECOVERY_REQUIRED');
+ }
+ expect(creates(f)).toBe(0);
+ writeFileSync(join(f.root, 'blocker'), 'a file where the recovery directory should be\n');
+ const unwritable = run(f, ['up', '--counted'], { UBI_RECOVERY_DIR: join(f.root, 'blocker', 'rec'), UBI_REAP: '0' });
+ expect(unwritable.exitCode).not.toBe(0);
+ expect(out(unwritable)).toContain('UBI_RECOVERY_UNAVAILABLE');
+ expect(creates(f)).toBe(0);
+ for (const bad of [['--sink-path', '/etc'], ['--sink-path', 'a/../..'], ['--tag', 'no-equals']]) {
+ const r = run(f, ['up', ...bad], { UBI_REAP: '0' });
+ expect(r.exitCode).not.toBe(0);
+ }
+ expect(creates(f)).toBe(0);
+ const rec = join(f.root, 'recovery');
+ const ok = run(f, ['up', '--counted'], { UBI_RECOVERY_DIR: rec, UBI_REAP: '0' });
+ expect(ok.exitCode).toBe(0);
+ expect(existsSync(join(rec, 'thrd1', ok.stdout.toString().trim() + '.bundle'))).toBe(true);
+ });
+
+ test('a counted rerun refuses to reattach to a VM that has no bundle', async () => {
+ const f = make();
+ const repo = gitSrc(f);
+ writeFileSync(join(f.root, 'make-test.sh'), 'echo begin; sleep 4; echo end\n');
+ const a = f.spawn(['run', '--src', repo, '--', 'make test'], { UBI_REAP: '0' });
+ await until(() => vmDirs(f).some(d => existsSync(join(f.state, d, 'command.out')) && readFileSync(join(f.state, d, 'command.out'), 'utf8').includes('begin')), 30_000);
+ process.kill(a.pid, 'SIGKILL');
+ await a.exited;
+ const name = vmDirs(f)[0]!;
+ const r = run(f, ['run', '--counted', '--src', repo, '--', 'make test'], { UBI_RECOVERY_DIR: join(f.root, 'rec'), UBI_REAP: '0' });
+ expect(out(r)).toContain('UBI_RECOVERY_REQUIRED: a counted run would reattach to ' + name);
+ expect(r.exitCode).not.toBe(0);
+ expect(creates(f)).toBe(1);
+ expect(run(f, ['down', name]).exitCode).toBe(0);
+ }, 90_000);
+
+ test('a counted rerun refuses a bundle that does not open, and reattaches once the bundle is good again', async () => {
+ const f = make();
+ const repo = gitSrc(f);
+ const rec = join(f.root, 'rec');
+ writeFileSync(join(f.root, 'make-test.sh'), 'echo begin; sleep 4; echo end\n');
+ const a = f.spawn(['run', '--src', repo, '--', 'make test'], { UBI_RECOVERY_DIR: rec, UBI_REAP: '0' });
+ await until(() => vmDirs(f).some(d => existsSync(join(f.state, d, 'command.out')) && readFileSync(join(f.state, d, 'command.out'), 'utf8').includes('begin')), 30_000);
+ process.kill(a.pid, 'SIGKILL');
+ await a.exited;
+ const name = vmDirs(f)[0]!;
+ const bundle = join(rec, 'thrd1', name + '.bundle');
+ const good = readFileSync(bundle);
+ writeFileSync(bundle, 'not a bundle\n');
+ const corrupt = run(f, ['run', '--counted', '--src', repo, '--', 'make test'], { UBI_RECOVERY_DIR: rec, UBI_REAP: '0' });
+ expect(out(corrupt)).toContain('UBI_RECOVERY_REQUIRED: a counted run would reattach to ' + name);
+ expect(corrupt.exitCode).not.toBe(0);
+ expect(creates(f)).toBe(1);
+ writeFileSync(bundle, good);
+ const ok = run(f, ['run', '--counted', '--src', repo, '--', 'make test'], { UBI_RECOVERY_DIR: rec, UBI_REAP: '0' });
+ expect(out(ok)).toContain('reattached to ' + name);
+ expect(ok.exitCode).toBe(0);
+ expect(creates(f)).toBe(1);
+ }, 90_000);
+
+ test('the runner never forwards its own variables: --pass and --trust-config both refuse them', () => {
+ const f = make();
+ const dir = gitSrc(f, { command: 'make verify', pass: ['RECOVERY_SECRET'] });
+ const env = { UBI_RECOVERY_KEY: 'recovery-key-value', UBI_SINK: 'https-put:https://b.example/o?X-Amz-Signature=sekritsig321', UBI_REAP: '0' };
+ const trusted = run(f, ['verify', '--src', dir, '--trust-config'], env);
+ expect(trusted.exitCode).toBe(1);
+ expect(out(trusted)).toContain('--pass RECOVERY_SECRET');
+ for (const name of ['RECOVERY_SECRET', 'RECOVERY_DIR', 'OWNER', 'SINK_INTERVAL', 'UBI_RECOVERY_KEY', 'UBI_SINK']) {
+ const r = run(f, ['run', '--pass', name, '--src', dir, '--', 'true'], env);
+ expect(r.exitCode).toBe(1);
+ expect(out(r)).toContain('--pass ' + name);
+ }
+ expect(creates(f)).toBe(0);
+ expect(existsSync(join(f.root, 'ubirun-env'))).toBe(false);
+ });
+
+ test('--pass forwards the value the caller exported, never a runner variable of the same name', () => {
+ const f = make();
+ const sinkDir = join(f.root, 'sink');
+ const repo = gitSrc(f);
+ for (const name of ['opt', 'src', 'sink']) {
+ const r = run(f, ['run', '--pass', name, '--src', repo, '--', 'test "$' + name + '" = caller-' + name], { ...fileSink(f, sinkDir), [name]: 'caller-' + name });
+ expect(out(r)).not.toContain('not in this shell');
+ expect(r.exitCode).toBe(0);
+ }
+ expect(f.ssh()).not.toContain(sinkDir);
+ }, 120_000);
+
+ test('an option value spelled --sink does not carry the presigned URL into the run record', async () => {
+ const f = make();
+ writeFileSync(join(f.root, 'make-test.sh'), 'echo begin; sleep 3\n');
+ const a = f.spawn(['run', '--key-input', '--sink', '--sink', 'https-put:https://b.example/o?X-Amz-Signature=sekritsig789', '--src', gitSrc(f), '--', 'make', 'test'], { UBI_REAP: '0' });
+ await until(() => vmDirs(f).some(d => existsSync(join(f.state, d, 'command.out')) && readFileSync(join(f.state, d, 'command.out'), 'utf8').includes('begin')), 30_000);
+ const name = vmDirs(f)[0]!;
+ const record = readFileSync(join(f.state, name, 'run'), 'utf8');
+ expect(record).not.toContain('sekritsig789');
+ expect(record).toContain('--key-input --sink --src');
+ expect(await a.exited).toBe(0);
+ }, 90_000);
+});
diff --git a/ubicloud/SKILL.md b/ubicloud/SKILL.md
index b7a2774258..00e06d5773 100644
--- a/ubicloud/SKILL.md
+++ b/ubicloud/SKILL.md
@@ -189,9 +189,10 @@ are not ignored, and `.git`, so uncommitted edits are tested), runs the
bootstrap once, runs the command in a login shell with `umask 022`, copies
`--pull REMOTE_GLOB:LOCAL_DIR` artifacts back and destroys the VM. It exits
with the command's status. `--env K=V` passes a literal; `--pass NAME` forwards
-a local variable's value without printing it (never `UBICLOUD_*`: the runner's
-own credentials stay on this machine); `--keep` skips teardown for debugging,
-and then `$U down ` is yours to run.
+a variable you exported, as it was when the runner started, without printing it
+(never `UBICLOUD_*`, `UBI_RECOVERY_KEY` or `UBI_SINK`: the runner's own
+credentials, recovery secret and sink URL stay on this machine); `--keep`
+skips teardown for debugging, and then `$U down ` is yours to run.
---
@@ -277,7 +278,8 @@ is visible: a `standard-16` run is billed from create to confirmed teardown.
2. `$U records` and `$U list --mine`, then `$U down` anything of yours that no
rerun will reattach to.
3. After a machine swap nothing reattaches; tier checkpoints on a Drive
- (`UBI_CHECKPOINT_DIR`) still count.
+ (`UBI_CHECKPOINT_DIR`) still count; with `UBI_RECOVERY_DIR`, `$U recover`
+ rebuilds VM state here once the old machine is dead.
4. A background log with no exit sentinel and no VM is an interrupted run, not
a pass; rerun it.
5. Measure before/after pairs on the same size and location, never one side
diff --git a/ubicloud/SKILL.md.tmpl b/ubicloud/SKILL.md.tmpl
index 1c339af9f1..601d650c2a 100644
--- a/ubicloud/SKILL.md.tmpl
+++ b/ubicloud/SKILL.md.tmpl
@@ -115,9 +115,10 @@ are not ignored, and `.git`, so uncommitted edits are tested), runs the
bootstrap once, runs the command in a login shell with `umask 022`, copies
`--pull REMOTE_GLOB:LOCAL_DIR` artifacts back and destroys the VM. It exits
with the command's status. `--env K=V` passes a literal; `--pass NAME` forwards
-a local variable's value without printing it (never `UBICLOUD_*`: the runner's
-own credentials stay on this machine); `--keep` skips teardown for debugging,
-and then `$U down ` is yours to run.
+a variable you exported, as it was when the runner started, without printing it
+(never `UBICLOUD_*`, `UBI_RECOVERY_KEY` or `UBI_SINK`: the runner's own
+credentials, recovery secret and sink URL stay on this machine); `--keep`
+skips teardown for debugging, and then `$U down ` is yours to run.
---
@@ -203,7 +204,8 @@ is visible: a `standard-16` run is billed from create to confirmed teardown.
2. `$U records` and `$U list --mine`, then `$U down` anything of yours that no
rerun will reattach to.
3. After a machine swap nothing reattaches; tier checkpoints on a Drive
- (`UBI_CHECKPOINT_DIR`) still count.
+ (`UBI_CHECKPOINT_DIR`) still count; with `UBI_RECOVERY_DIR`, `$U recover`
+ rebuilds VM state here once the old machine is dead.
4. A background log with no exit sentinel and no VM is an interrupted run, not
a pass; rerun it.
5. Measure before/after pairs on the same size and location, never one side