An open-source, faster Devin alternative
TypeScript
computer: legacy drain signals the node host under tsx and checks the flip (work 103, follow-up to #1084) (#1085)
opencomputer-app[bot]3680bf5fc53e
diff --git a/computer/deploy/vm/legacy-drain.sh b/computer/deploy/vm/legacy-drain.shnew file mode 100755index 00000000..17565a1a--- /dev/null+++ b/computer/deploy/vm/legacy-drain.sh@@ -0,0 +1,176 @@+#!/usr/bin/env bash+# ONE-TIME systemd->podman migration (work 103). Delete together with the systemd launch path in step 11+# (with provision.sh's marked block and src/dev/sandbox-check-legacy.ts).+#+# Drain-then-flip of slack-presence-host, for provision.sh, which sources this+# and calls `legacy_drain_restart || systemctl restart slack-presence-host`.+# When the restart turns the host's SP_LAUNCH from systemd to podman, the+# running host is told to drain (SIGUSR2, src/host/legacy-migration/drain.ts):+# every runner exits after its turn, and the host exits once none is left;+# Restart= brings it back as a `podman` host.+#+# legacy-drain.sh host-pid <pid> the process running src/host/main.ts at or below <pid> (sandbox-check-legacy.ts)+#+# Invariants:+# - SIGUSR2 goes to the process running src/host/main.ts, never to MainPID as+# such: the unit's ExecStart is tsx's CLI, which starts main.ts as a child+# and forwards only SIGINT and SIGTERM, so SIGUSR2 on MainPID kills the+# wrapper and the host is stopped, not drained (exit 140, #1084's review).+# - Returns 1, for a plain restart, only before anything was signalled: no+# change systemd -> podman, a host it cannot find, or a release without the+# drain. Once signalled it succeeds or exits the script non-zero.+# - Success is checked, not assumed: the old invocation logged+# `legacy drain: exiting` and the new host process has SP_LAUNCH=podman.+# - Only the runner units there before the drain are stopped afterwards; the+# `podman` host's runners are units of the same name pattern.+#+# Seams for tests (src/host/legacy-migration/legacy-drain-sh.test.ts): LEGACY_PROC (/proc), PATH+# (systemctl, journalctl, runuser), LEGACY_WAIT_S, LEGACY_STEP_S.++LEGACY_UNIT=slack-presence-host.service+LEGACY_PROC=${LEGACY_PROC:-/proc}+LEGACY_WAIT_S=${LEGACY_WAIT_S:-660} # the drain's 10 min deadline, its grace, the host's stop and Restart=+LEGACY_STEP_S=${LEGACY_STEP_S:-5}++declare -F log >/dev/null || log() { printf '\n==> %s\n' "$*"; }+declare -F warn >/dev/null || warn() { printf 'WARNING: %s\n' "$*" >&2; }+declare -F die >/dev/null || die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }++legacy_is_host() { # <pid>: its command line runs src/host/main.ts+ local c+ c=$(tr '\0' ' ' < "$LEGACY_PROC/$1/cmdline" 2>/dev/null) || return 1+ [[ $c == *src/host/main.ts* ]]+}++legacy_children() { # <pid>: its children's pids, from each process's stat (no CONFIG_PROC_CHILDREN needed)+ local f s ppid+ for f in "$LEGACY_PROC"/[0-9]*/stat; do+ s=$(cat "$f" 2>/dev/null) || continue+ s=${s##*) } # past the command name, which may hold spaces and parentheses+ read -r _ ppid _ <<< "$s"+ if [[ $ppid == "$1" ]]; then f=${f%/stat}; printf '%s\n' "${f##*/}"; fi+ done+}++legacy_host_pid() { # <pid>: the deepest process running src/host/main.ts from <pid> down; 1 when <pid> runs none+ local pid=$1 c next+ legacy_is_host "$pid" || return 1+ while :; do+ next=''+ for c in $(legacy_children "$pid"); do+ if legacy_is_host "$c"; then next=$c; break; fi+ done+ [[ -n $next ]] || break+ pid=$next+ done+ printf '%s\n' "$pid"+}++legacy_env_of() { # <pid> <name>: the variable in that process's environment (empty when unset)+ tr '\0' '\n' < "$LEGACY_PROC/$1/environ" 2>/dev/null | sed -n "s/^$2=//p" | tail -n1+}++legacy_launch_of_files() { # <env files...>: the last SP_LAUNCH= in them, unquoted+ local f v=''+ for f in "$@"; do+ [[ -r $f ]] || continue+ v=$(sed -n 's/^[[:space:]]*\(export[[:space:]]\+\)\?SP_LAUNCH=//p' "$f" | tail -n1 | sed "s/^[\"']//; s/[\"']\$//")+ [[ -n $v ]] && printf '%s\n' "$v"+ done | tail -n1+}++legacy_new_launch() { # what the restarted unit will have: its Environment=, then its EnvironmentFile=s in order (they win)+ local new files fromfiles+ new=$(systemctl show -p Environment --value "$LEGACY_UNIT" | tr ' ' '\n' | sed -n 's/^SP_LAUNCH=//p' | tail -n1)+ mapfile -t files < <(systemctl show -p EnvironmentFiles --value "$LEGACY_UNIT" | tr ' ' '\n' | grep '^/' || true)+ fromfiles=$(legacy_launch_of_files "${files[@]}")+ printf '%s\n' "${fromfiles:-$new}"+}++legacy_user_systemctl() { runuser -u "$AGENT_USER" -- env XDG_RUNTIME_DIR=/run/user/"$AGENT_UID" systemctl --user "$@"; }++legacy_runner_units() { # the runners' units running now, one a line+ legacy_user_systemctl list-units --plain --no-legend --state=active,activating,deactivating 'sp-runner-*' 2>/dev/null | awk '{print $1}' | grep '^sp-runner-' || true+}++legacy_stop_leftovers() { # <units before the drain, newline-separated>: stop those still running+ local before=$1 u left=()+ [[ -n $before ]] || return 0+ while read -r u; do+ [[ -n $u ]] && grep -qxF -- "$u" <<< "$before" && left+=("$u")+ done < <(legacy_runner_units)+ ((${#left[@]})) || { log "legacy drain: no runner of the systemd host is left"; return 0; }+ warn "legacy drain: stopping ${#left[@]} runner(s) of the systemd host still running: ${left[*]}"+ legacy_user_systemctl stop -- "${left[@]}" || warn "legacy drain: could not stop all of ${left[*]}"+}++legacy_drained() { # <old invocation id> <old MainPID>: the old host logged that the drain ended it (journald may lag: a few tries)+ local i out+ for ((i = 0; i < 5; i++)); do+ if [[ -n $1 ]]; then out=$(journalctl --no-pager -o cat "_SYSTEMD_INVOCATION_ID=$1" 2>/dev/null | grep 'legacy drain: exiting' || true)+ else out=$(journalctl --no-pager -o cat "_SYSTEMD_UNIT=$LEGACY_UNIT" "_PID=$2" 2>/dev/null | grep 'legacy drain: exiting' || true)+ fi+ if [[ -n $out ]]; then printf '%s\n' "$out" | tail -n1; return 0; fi+ sleep 1+ done+ return 1+}++legacy_wait_main() { # <old MainPID>: the new MainPID, once there is one, or 1 at LEGACY_WAIT_S+ local i now+ for ((i = 0; i < LEGACY_WAIT_S; i += LEGACY_STEP_S)); do+ sleep "$LEGACY_STEP_S"+ now=$(systemctl show -p MainPID --value "$LEGACY_UNIT" 2>/dev/null || echo 0)+ if [[ -n $now && $now != 0 && $now != "$1" ]]; then printf '%s\n' "$now"; return 0; fi+ done+ return 1+}++legacy_new_host() { # <MainPID>: the process running main.ts under it, once tsx has started it (30 s at most)+ local i pid+ for ((i = 0; i < 30; i++)); do+ if pid=$(legacy_host_pid "$1") && [[ $pid != "$1" || $(tr '\0' ' ' < "$LEGACY_PROC/$1/cmdline" 2>/dev/null) != *tsx* ]]; then+ printf '%s\n' "$pid"; return 0+ fi+ sleep 1+ done+ return 1+}++legacy_drain_restart() {+ local main pid old new inv before now host launch line+ main=$(systemctl show -p MainPID --value "$LEGACY_UNIT" 2>/dev/null || echo 0)+ [[ -n $main && $main != 0 ]] || return 1+ pid=$(legacy_host_pid "$main") || return 1+ old=$(legacy_env_of "$pid" SP_LAUNCH)+ new=$(legacy_new_launch)+ [[ ${old:-systemd} == systemd && ${new:-systemd} == podman ]] || return 1+ if [[ ! -f $LEGACY_PROC/$main/cwd/src/host/legacy-migration/drain.ts ]]; then+ warn "SP_LAUNCH turns to podman but the running host has no drain: plain restart (deploy this release on systemd first)"+ return 1+ fi+ inv=$(systemctl show -p InvocationID --value "$LEGACY_UNIT" 2>/dev/null || true)+ before=$(legacy_runner_units)+ log "SP_LAUNCH systemd -> podman: draining host $pid (unit MainPID $main; runners finish their turns; at most ~10 min)"+ kill -USR2 "$pid" || die "legacy drain: could not signal host $pid; the host is unchanged. Retry provision, or restart it by hand"+ if ! now=$(legacy_wait_main "$main"); then+ warn "legacy drain: host $pid did not leave in ${LEGACY_WAIT_S} s: restarting it"+ systemctl restart "$LEGACY_UNIT"+ now=$(systemctl show -p MainPID --value "$LEGACY_UNIT" 2>/dev/null || echo 0)+ fi+ host=$(legacy_new_host "$now") || die "legacy drain: the host did not come back (MainPID $now runs no src/host/main.ts): journalctl -u $LEGACY_UNIT"+ launch=$(legacy_env_of "$host" SP_LAUNCH)+ [[ $launch == podman ]] || die "legacy drain: the host came back as pid $host with SP_LAUNCH=${launch:-unset}, not podman: journalctl -u $LEGACY_UNIT"+ legacy_stop_leftovers "$before"+ line=$(legacy_drained "$inv" "$main") || die "legacy drain: host $pid (invocation ${inv:-?}) never logged 'legacy drain: exiting': it was stopped, not drained, and turns may have been cut. The new host is podman (pid $host): journalctl _SYSTEMD_INVOCATION_ID=$inv"+ [[ $line == *'still connected'* ]] && warn "legacy drain: the deadline was reached: $line"+ log "host drained and back as podman (pid $host, MainPID $now)"+}++if [[ ${BASH_SOURCE[0]} == "$0" ]]; then+ set -euo pipefail+ case ${1:-} in+ host-pid) legacy_host_pid "${2:?usage: legacy-drain.sh host-pid <pid>}" ;;+ *) echo "usage: legacy-drain.sh host-pid <pid>" >&2; exit 2 ;;+ esac+fidiff --git a/computer/deploy/vm/provision.sh b/computer/deploy/vm/provision.shindex 53235c89..96c5cdcb 100755--- a/computer/deploy/vm/provision.sh+++ b/computer/deploy/vm/provision.sh@@ -872,47 +872,14 @@ fi# ---- ONE-TIME systemd->podman migration (work 103). Delete together with the systemd launch path in step 11.# When this run turns the host's SP_LAUNCH from systemd to podman, a plain-# restart would leave the `systemd` runners running beside a `podman` host.-# Instead the running host is drained (src/host/legacy-migration/drain.ts):-# SIGUSR2, it tells every runner to exit after its turn, holds new deliveries-# and exits when none is left (10 min at most); Restart= brings it back as a-# `podman` host, which migrates each thread at its next delivery. Returns 1,-# for a plain restart, when SP_LAUNCH does not change that way, when the-# running release has no drain, or when the host did not come back in time.-sp_launch_of_files() { # <env files...>: the last SP_LAUNCH= in them, unquoted- local f v=''- for f in "$@"; do- [[ -r $f ]] || continue- v=$(sed -n 's/^[[:space:]]*\(export[[:space:]]\+\)\?SP_LAUNCH=//p' "$f" | tail -n1 | sed "s/^[\"']//; s/[\"']\$//")- [[ -n $v ]] && printf '%s\n' "$v"- done | tail -n1-}-legacy_drain_restart() {- local pid old new files- pid=$(systemctl show -p MainPID --value slack-presence-host.service 2>/dev/null || echo 0)- [[ -n $pid && $pid != 0 && -r /proc/$pid/environ ]] || return 1- old=$(tr '\0' '\n' < "/proc/$pid/environ" | sed -n 's/^SP_LAUNCH=//p' | tail -n1)- # What the restarted unit will have: its Environment=, then its EnvironmentFile=s in order (they win).- new=$(systemctl show -p Environment --value slack-presence-host.service | tr ' ' '\n' | sed -n 's/^SP_LAUNCH=//p' | tail -n1)- mapfile -t files < <(systemctl show -p EnvironmentFiles --value slack-presence-host.service | tr ' ' '\n' | grep '^/' || true)- local fromfiles; fromfiles=$(sp_launch_of_files "${files[@]}")- new=${fromfiles:-$new}- [[ ${old:-systemd} == systemd && ${new:-systemd} == podman ]] || return 1- if [[ ! -f /proc/$pid/cwd/src/host/legacy-migration/drain.ts ]]; then- warn "SP_LAUNCH turns to podman but the running host has no drain: plain restart (deploy this release on systemd first)"- return 1- fi- log "SP_LAUNCH systemd -> podman: draining host $pid (runners finish their turns; at most ~10 min)"- systemctl kill -s SIGUSR2 --kill-whom=main slack-presence-host.service || return 1- local i now- for ((i = 0; i < 660; i += 5)); do- sleep 5- now=$(systemctl show -p MainPID --value slack-presence-host.service 2>/dev/null || echo 0)- if [[ -n $now && $now != 0 && $now != "$pid" ]]; then log "host drained and back as podman (pid $now)"; return 0; fi- done- warn "host $pid did not drain in time: restarting it"- return 1-}+# restart would leave the `systemd` runners running beside a `podman` host:+# legacy_drain_restart drains the running host instead, checks that it came+# back as `podman`, and stops the old runners still left (deploy/vm/legacy-drain.sh,+# delete it with this block). Returns 1, for a plain restart, when SP_LAUNCH does+# not change that way or the running release has no drain; exits non-zero when a+# drain it started did not end as one.+# shellcheck source=legacy-drain.sh+source "$SP_CURRENT/deploy/vm/legacy-drain.sh"# ---- end ONE-TIME systemd->podman migrationif [[ -f $HOST_ENV ]]; thendiff --git a/computer/src/dev/sandbox-check-legacy.ts b/computer/src/dev/sandbox-check-legacy.tsindex 1db3839e..98ddea97 100644--- a/computer/src/dev/sandbox-check-legacy.ts+++ b/computer/src/dev/sandbox-check-legacy.ts@@ -6,7 +6,10 @@// oc-modelproxy, sandbox-check-model.ts); one goes idle and its runner exits// (a cold thread), the other is live with an uncommitted file in its// worktree. SIGUSR2 drains the host (legacy-migration/drain.ts): a delivery-// sent then gets no reply from it, its runner exits and so does the host. A+// sent then gets no reply from it, its runner exits and so does the host.+// The host runs as its unit runs it, under tsx's CLI, and gets the signal the+// way provision.sh sends it, at the process deploy/vm/legacy-drain.sh finds+// (tsx forwards no SIGUSR2: the wrapper itself would die of it). A// host with SP_LAUNCH=podman comes up, the fake gateway sends the held// delivery again (as the gateway does when a host's socket closes), then// delivers to the cold thread with the session id and fork path of its last@@ -148,7 +151,8 @@ const COLD = thread(2);let host: ChildProcess | undefined;function startHost(launch: 'systemd' | 'podman'): ChildProcess {const { SP_DEFINITION, WORKDIR, SLACK_BOT_TOKEN, ...rest } = process.env;- const h = spawn(process.execPath, ['--import', 'tsx', 'src/host/main.ts'], {+ // As provision.sh's unit runs it (ExecStart): through tsx's CLI, which starts main.ts as its child.+ const h = spawn(path.join(ROOT, 'node_modules/.bin/tsx'), ['src/host/main.ts'], {cwd: ROOT,env: { ...rest, SP_GATEWAY_URL: `ws://127.0.0.1:${(wss.address() as net.AddressInfo).port}/host`, SP_HOST_TOKEN: 'check-token', SP_HOST_ID: 'sandbox-check-legacy',SP_RUN: RUN, SP_DATA: DATA, SP_IDLE_MS: String(IDLE_MS), SP_LAUNCH: launch, SP_POOL_SIZE: '0', SP_FAKE_SLACK: '1', SP_MODEL_PROXY: model.control, SP_MODEL_SOCKET: model.api },@@ -206,7 +210,10 @@ async function onSystemd() {async function drain() {const h = host!;- h.kill('SIGUSR2');+ // As provision.sh signals it (deploy/vm/legacy-drain.sh): the process running main.ts, not the wrapper.+ const pid = Number(execFileSync('bash', [path.join(ROOT, 'deploy/vm/legacy-drain.sh'), 'host-pid', String(h.pid)], { encoding: 'utf8' }).trim());+ check(pid !== h.pid, `drain: the host runs under tsx's CLI as the unit runs it (pid ${pid} under ${h.pid})`);+ process.kill(pid, 'SIGUSR2');await sleep(500);const held = LIVE.send('during the drain marker-live-3');const out = await exited(h, 120_000);diff --git a/computer/src/host/legacy-migration/legacy-drain-sh.test.ts b/computer/src/host/legacy-migration/legacy-drain-sh.test.tsnew file mode 100644index 00000000..e309c45d--- /dev/null+++ b/computer/src/host/legacy-migration/legacy-drain-sh.test.ts@@ -0,0 +1,201 @@+// ONE-TIME systemd->podman migration (work 103). Delete together with the systemd launch path in step 11.+//+// deploy/vm/legacy-drain.sh (provision.sh's drain-then-flip), against a fake+// /proc and stub systemctl, journalctl and runuser: which process gets+// SIGUSR2, and when a drain counts as done.+import { execFileSync, spawnSync } from 'node:child_process';+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++const SCRIPT = path.resolve(import.meta.dirname, '../../../deploy/vm/legacy-drain.sh');++let dir: string;+const proc = () => path.join(dir, 'proc');+const state = (f: string) => path.join(dir, 'state', f);+const read = (f: string) => {+ try {+ return readFileSync(state(f), 'utf8');+ } catch {+ return '';+ }+};++/** A process in the fake /proc. */+function ps(pid: number, ppid: number, argv: string[], env: Record<string, string> = {}, cwd?: string) {+ const d = path.join(proc(), String(pid));+ mkdirSync(d, { recursive: true });+ writeFileSync(path.join(d, 'cmdline'), `${argv.join('\0')}\0`);+ writeFileSync(path.join(d, 'stat'), `${pid} (${path.basename(argv[0])} x) S ${ppid} ${pid} ${pid} 0 -1`);+ writeFileSync(path.join(d, 'environ'), `${Object.entries(env).map(([k, v]) => `${k}=${v}`).join('\0')}\0`);+ if (cwd) {+ mkdirSync(path.join(d, 'cwd', 'src/host/legacy-migration'), { recursive: true });+ writeFileSync(path.join(d, 'cwd', 'src/host/legacy-migration/drain.ts'), '');+ }+}++/** The unit's ExecStart: tsx's CLI, which starts main.ts as its child. */+function tsxHost(main: number, env: Record<string, string>, opts: { drain?: boolean } = {}) {+ ps(main, 1, ['node', '/opt/slack-presence/current/node_modules/.bin/tsx', 'src/host/main.ts'], env, opts.drain === false ? undefined : 'cwd');+ ps(main + 1, main, ['/usr/bin/node', '--require', '/opt/x/node_modules/tsx/dist/preflight.cjs', '--import', 'file:///opt/x/node_modules/tsx/dist/loader.mjs', 'src/host/main.ts'], env);+ ps(main + 2, main + 1, ['git', 'fetch', '--quiet']); // a housekeeping child of the host+}++function stub(name: string, body: string) {+ const f = path.join(dir, 'bin', name);+ writeFileSync(f, `#!/usr/bin/env bash\nS=${JSON.stringify(path.join(dir, 'state'))}\n${body}\n`);+ chmodSync(f, 0o755);+}++beforeEach(() => {+ dir = mkdtempSync(path.join(os.tmpdir(), 'legacy-drain-'));+ for (const d of ['proc', 'state', 'bin']) mkdirSync(path.join(dir, d));+ stub('systemctl', `+if [[ $1 == --user ]]; then+ shift+ case $1 in+ list-units) cat "$S/units" 2>/dev/null | sed 's/$/ loaded active running x/' ;;+ stop) shift; [[ $1 == -- ]] && shift; echo "$*" >> "$S/stopped" ;;+ esac+ exit 0+fi+case "$1 $2 $3" in+ "show -p MainPID") cat "$S/mainpid" ;;+ "show -p Environment") cat "$S/environment" 2>/dev/null; echo ;;+ "show -p EnvironmentFiles") echo ;;+ "show -p InvocationID") echo inv-old ;;+ restart*) echo restarted >> "$S/restarted"; cat "$S/after-restart" > "$S/mainpid" ;;+esac`);+ stub('journalctl', '[[ " $* " == *" _SYSTEMD_INVOCATION_ID=inv-old "* ]] && cat "$S/journal" 2>/dev/null; exit 0');+ stub('runuser', 'while [[ $1 != -- ]]; do shift; done; shift; exec "$@"');+});+afterEach(() => rmSync(dir, { recursive: true, force: true }));++/** provision.sh's call, under its shell options; `onKill` runs as the signal "arrives". */+function provision(onKill = '') {+ writeFileSync(state('on-kill'), onKill);+ const driver = `+set -euo pipefail+source ${JSON.stringify(SCRIPT)}+sleep() { :; }+kill() { echo "$*" >> ${JSON.stringify(state('killed'))}; bash ${JSON.stringify(state('on-kill'))}; }+legacy_drain_restart || echo PLAIN-RESTART`;+ const r = spawnSync('bash', ['-c', driver], {+ env: { ...process.env, PATH: `${path.join(dir, 'bin')}:${process.env.PATH}`, LEGACY_PROC: proc(), LEGACY_WAIT_S: '3', LEGACY_STEP_S: '1', AGENT_USER: 'agent', AGENT_UID: '1500' },+ encoding: 'utf8',+ });+ return { code: r.status, out: r.stdout, err: r.stderr, killed: read('killed').trim(), stopped: read('stopped').trim(), restarted: !!read('restarted') };+}++/** The flip as the drain does it: the old host leaves, logging so, and the unit comes back as `podman` under MainPID 300. */+const flip = (opts: { launch?: string; log?: string } = {}) => {+ tsxHost(300, { SP_LAUNCH: opts.launch ?? 'podman' });+ return [+ `echo 300 > ${JSON.stringify(state('mainpid'))}`,+ `printf '%s\\n' ${JSON.stringify(opts.log ?? 'legacy drain: exiting after 42 s (no runner left)')} > ${JSON.stringify(state('journal'))}`,+ `printf 'sp-runner-stuck\\nsp-runner-newpod\\n' > ${JSON.stringify(state('units'))}`,+ ].join('\n');+};++function systemdHost() {+ tsxHost(100, {});+ writeFileSync(state('mainpid'), '100\n');+ writeFileSync(state('environment'), 'HOME=/home/agent SP_LAUNCH=podman');+ writeFileSync(state('units'), 'sp-runner-done\nsp-runner-stuck\n');+}++describe('legacy-drain.sh host-pid', () => {+ const hostPid = (pid: number) => spawnSync('bash', [SCRIPT, 'host-pid', String(pid)], { env: { ...process.env, LEGACY_PROC: proc() }, encoding: 'utf8' });++ it("finds main.ts in tsx's child, not the wrapper systemd sees as MainPID", () => {+ tsxHost(100, {});+ expect(hostPid(100).stdout.trim()).toBe('101');+ });++ it('is MainPID itself under `node --import tsx`', () => {+ ps(200, 1, ['node', '--import', 'tsx', 'src/host/main.ts']);+ ps(201, 200, ['git', 'fetch']);+ expect(hostPid(200).stdout.trim()).toBe('200');+ });++ it('fails for a process that runs no host', () => {+ ps(400, 1, ['sleep', '100']);+ expect(hostPid(400).status).toBe(1);+ expect(hostPid(999).status).toBe(1);+ });++ it('reads a command name with spaces and parentheses', () => {+ tsxHost(100, {});+ writeFileSync(path.join(proc(), '101', 'stat'), '101 (node (x) y) S 100 101 101 0 -1');+ expect(execFileSync('bash', [SCRIPT, 'host-pid', '100'], { env: { ...process.env, LEGACY_PROC: proc() }, encoding: 'utf8' }).trim()).toBe('101');+ });+});++describe('legacy_drain_restart', () => {+ it('is a plain restart when SP_LAUNCH stays systemd, with nothing signalled', () => {+ systemdHost();+ writeFileSync(state('environment'), 'HOME=/home/agent');+ const r = provision();+ expect(r.out).toContain('PLAIN-RESTART');+ expect(r.killed).toBe('');+ });++ it('is a plain restart when the running host is already podman', () => {+ systemdHost();+ tsxHost(100, { SP_LAUNCH: 'podman' });+ expect(provision().out).toContain('PLAIN-RESTART');+ });++ it('is a plain restart, with a warning, when the running release has no drain', () => {+ systemdHost();+ rmSync(path.join(proc(), '100', 'cwd'), { recursive: true });+ const r = provision();+ expect(r.out).toContain('PLAIN-RESTART');+ expect(r.err).toContain('has no drain');+ expect(r.killed).toBe('');+ });++ it('signals the node child, checks the flip, and stops only the old runners still running', () => {+ systemdHost();+ const r = provision(flip());+ expect(r.code).toBe(0);+ expect(r.killed).toBe('-USR2 101');+ expect(r.out).not.toContain('PLAIN-RESTART');+ expect(r.stopped).toBe('sp-runner-stuck'); // not sp-runner-newpod: the podman host's+ expect(r.out).toContain('host drained and back as podman (pid 301, MainPID 300)');+ });++ it('warns when the drain ended at its deadline', () => {+ systemdHost();+ const r = provision(flip({ log: 'legacy drain: exiting after 610 s (1 runner(s) still connected)' }));+ expect(r.code).toBe(0);+ expect(r.err).toContain('the deadline was reached');+ });++ it('fails when the old host never logged its drain (stopped, not drained)', () => {+ systemdHost();+ const r = provision(flip({ log: 'host stopping' }));+ expect(r.code).toBe(1);+ expect(r.err).toContain("never logged 'legacy drain: exiting'");+ expect(r.out).not.toContain('PLAIN-RESTART');+ });++ it('fails when the host came back without SP_LAUNCH=podman, and stops no runner', () => {+ systemdHost();+ const r = provision(flip({ launch: 'systemd' }));+ expect(r.code).toBe(1);+ expect(r.err).toContain('SP_LAUNCH=systemd, not podman');+ expect(r.stopped).toBe('');+ });++ it('restarts the host and fails when it did not leave in time', () => {+ systemdHost();+ tsxHost(300, { SP_LAUNCH: 'podman' });+ writeFileSync(state('after-restart'), '300\n');+ const r = provision(''); // the signal changes nothing+ expect(r.restarted).toBe(true);+ expect(r.err).toContain('did not leave in 3 s');+ expect(r.code).toBe(1);+ });+});