|
| 1 | +// PARKING-RECOVERY (Nathan mandate, convoy incident 2026-07-22) — a supervisor bring-up after a mass |
| 2 | +// outage MUST restore the FULL fleet. The bug: `strategy.status=flapping` + the fast-fail counter persist |
| 3 | +// to a session's tags, so an outage that drives the cap to its limit PARKS the agents, and then a fresh |
| 4 | +// `convoy up`, reading those stale tags, `skip`s them forever (classify: `isFlapping → skip`). The |
| 5 | +// reconstructed incident: a bring-up brought back only part of the fleet; the rest stayed parked from a |
| 6 | +// prior supervisor's give-up and had to be hand-launched. |
| 7 | +// |
| 8 | +// The fix (see up.ts FRESH-SUPERVISOR UN-PARK + flapping-cap.ts clearParkForFreshSupervisor): a foreground |
| 9 | +// `convoy up` is a DELIBERATE bring-up, so at startup it clears the park + zeroes the counter for permanent |
| 10 | +// members (regardless of prior fail count); the cap re-accrues tick-to-tick within THIS supervisor's watch. |
| 11 | +// The `--once` shepherd cron does NOT un-park (it runs every few minutes — un-parking there would relaunch |
| 12 | +// a genuinely broken agent every tick), so parking stays durable for it. |
| 13 | +// |
| 14 | +// This proves it end to end: it stands up a PARKED, gone-but-recorded agent (via convoy's own spawn path |
| 15 | +// plus the same `strategy.*` tags a prior supervisor would have written), then asserts a fresh FOREGROUND |
| 16 | +// up UN-PARKS and RELAUNCHES it, while a fresh `--once` up leaves it parked. Process-level (real daemons + |
| 17 | +// a real `convoy up`), scoped to a throwaway XDG_STATE_HOME. Lives in the vitest gate (test.yml), not the |
| 18 | +// hermetic nix flake check. |
| 19 | + |
| 20 | +import { afterEach, describe, expect, it } from "vitest"; |
| 21 | +import { spawn, spawnSync, type ChildProcess } from "node:child_process"; |
| 22 | +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; |
| 23 | +import { tmpdir } from "node:os"; |
| 24 | +import { dirname, join } from "node:path"; |
| 25 | +import { fileURLToPath } from "node:url"; |
| 26 | +import { updateTags } from "@compoundingtech/pty/client"; |
| 27 | +import { gone, PtyHost, processAlive, spawnFromPtyFile } from "./host.ts"; |
| 28 | +import { FLAPPING_STATUS, TAG } from "./flapping-cap.ts"; |
| 29 | + |
| 30 | +const repoRoot = join(dirname(fileURLToPath(import.meta.url)), ".."); |
| 31 | +const bin = join(repoRoot, "bin", "convoy"); |
| 32 | +const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms)); |
| 33 | + |
| 34 | +let home = ""; |
| 35 | +let net = ""; |
| 36 | +let host: ChildProcess | null = null; |
| 37 | +const savedPtyRoot = process.env["PTY_ROOT"]; |
| 38 | + |
| 39 | +function childEnv(): NodeJS.ProcessEnv { |
| 40 | + return { ...process.env, XDG_STATE_HOME: home, ST_ROOT: "", PTY_ROOT: "" }; |
| 41 | +} |
| 42 | + |
| 43 | +function freshNet(): void { |
| 44 | + home = mkdtempSync(join(tmpdir(), "cvy-park-")); |
| 45 | + net = join(home, "convoy", "default"); |
| 46 | + mkdirSync(join(net, "catalog"), { recursive: true }); |
| 47 | + mkdirSync(join(net, "smalltalk"), { recursive: true }); |
| 48 | +} |
| 49 | + |
| 50 | +/** Stand up one permanent agent whose harness EXITS quickly (`sleep 1`), so it lands in the gone-but- |
| 51 | + * recorded state a real crashed agent occupies — the shape the park tags attach to and a replay relaunches. */ |
| 52 | +async function spawnAgent(id: string): Promise<void> { |
| 53 | + const workspace = join(net, "agents", id); |
| 54 | + mkdirSync(join(workspace, ".convoy"), { recursive: true }); |
| 55 | + writeFileSync( |
| 56 | + join(workspace, ".convoy", "pty.toml"), |
| 57 | + `prefix = "${id}"\n\n[sessions.claude]\nid = "${id}"\ncommand = "sleep 1"\n\n[sessions.claude.tags]\nstrategy = "permanent"\nrole = "agent"\n\n[sessions.claude.env]\nST_AGENT = "${id}"\n`, |
| 58 | + ); |
| 59 | + const { spawned, failed } = await spawnFromPtyFile(workspace, net); |
| 60 | + if (failed.length > 0 || spawned.length === 0) throw new Error(`spawn ${id} failed: ${JSON.stringify({ spawned, failed })}`); |
| 61 | +} |
| 62 | + |
| 63 | +/** Poll until the agent is in the real CRASHED shape: gone-but-recorded with a DEAD pid. The harness |
| 64 | + * exits, and ~0.5s later the pty daemon writes its exit record and shuts down (pid clears) — only then is |
| 65 | + * the pid dead, so `convoy up` treats it as a genuine death to RESPAWN rather than a transient-gone to |
| 66 | + * ADOPT (the adopt-alive guard: reported-gone but pid-alive → adopt, never respawn). */ |
| 67 | +async function waitCrashed(id: string, timeoutMs = 12000): Promise<void> { |
| 68 | + const deadline = Date.now() + timeoutMs; |
| 69 | + while (Date.now() < deadline) { |
| 70 | + const s = (await new PtyHost(net).sessions()).find((x) => x.name === id); |
| 71 | + if (s && gone(s) && !processAlive(s.pid)) return; |
| 72 | + await sleep(150); |
| 73 | + } |
| 74 | + throw new Error(`${id} never reached the crashed (gone + dead-pid) state`); |
| 75 | +} |
| 76 | + |
| 77 | +/** Write the park a prior supervisor would have left: status=flapping at the cap. */ |
| 78 | +function park(id: string): void { |
| 79 | + updateTags(id, { [TAG.status]: FLAPPING_STATUS, [TAG.consecutive]: "3" }); |
| 80 | +} |
| 81 | + |
| 82 | +/** The persisted strategy.status tag for an agent (undefined once cleared). */ |
| 83 | +async function statusTag(id: string): Promise<string | undefined> { |
| 84 | + const s = (await new PtyHost(net).sessions()).find((x) => x.name === id); |
| 85 | + return s?.tags[TAG.status]; |
| 86 | +} |
| 87 | + |
| 88 | +function lockedHostPid(): number | null { |
| 89 | + try { |
| 90 | + const pid = Number.parseInt(readFileSync(join(net, "convoy.pid"), "utf8").trim(), 10); |
| 91 | + return Number.isInteger(pid) && processAlive(pid) ? pid : null; |
| 92 | + } catch { |
| 93 | + return null; |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +/** Start a foreground `convoy up --json`, wait until it is hosting, run for `runMs` (long enough for the |
| 98 | + * startup un-park + the immediate first reconcile), then kill it. Returns the captured JSONL stdout. */ |
| 99 | +async function runForegroundUp(runMs: number): Promise<string> { |
| 100 | + const child = spawn(process.execPath, [bin, "up", net, "--json"], { env: childEnv(), stdio: ["ignore", "pipe", "pipe"] }); |
| 101 | + host = child; |
| 102 | + let stdout = ""; |
| 103 | + child.stdout?.on("data", (d: Buffer) => (stdout += d.toString())); |
| 104 | + const deadline = Date.now() + 15000; |
| 105 | + while (Date.now() < deadline && lockedHostPid() !== child.pid) { |
| 106 | + if (child.exitCode !== null) throw new Error(`convoy up exited early (code ${child.exitCode})`); |
| 107 | + await sleep(50); |
| 108 | + } |
| 109 | + await sleep(runMs); |
| 110 | + const exited = new Promise<void>((r) => child.once("exit", () => r())); |
| 111 | + child.kill("SIGTERM"); |
| 112 | + await exited; |
| 113 | + host = null; |
| 114 | + return stdout; |
| 115 | +} |
| 116 | + |
| 117 | +/** Parse a JSONL stream into records. */ |
| 118 | +function records(stream: string): Array<{ type?: string; session?: string; spawned?: string[] }> { |
| 119 | + const out: Array<{ type?: string; session?: string; spawned?: string[] }> = []; |
| 120 | + for (const line of stream.split("\n")) { |
| 121 | + if (!line.trim()) continue; |
| 122 | + try { |
| 123 | + out.push(JSON.parse(line)); |
| 124 | + } catch { |
| 125 | + /* human line leaked to stdout? ignore */ |
| 126 | + } |
| 127 | + } |
| 128 | + return out; |
| 129 | +} |
| 130 | + |
| 131 | +afterEach(() => { |
| 132 | + if (host) { |
| 133 | + try { |
| 134 | + host.kill("SIGKILL"); |
| 135 | + } catch { |
| 136 | + /* ignore */ |
| 137 | + } |
| 138 | + host = null; |
| 139 | + } |
| 140 | + try { |
| 141 | + spawnSync(process.execPath, [bin, "down", net, "--force"], { env: childEnv() }); |
| 142 | + } catch { |
| 143 | + /* ignore */ |
| 144 | + } |
| 145 | + if (home) rmSync(home, { recursive: true, force: true }); |
| 146 | + if (savedPtyRoot === undefined) delete process.env["PTY_ROOT"]; |
| 147 | + else process.env["PTY_ROOT"] = savedPtyRoot; |
| 148 | +}); |
| 149 | + |
| 150 | +describe("parking recovery — a fresh foreground `convoy up` restores a PARKED agent (Nathan mandate)", () => { |
| 151 | + it("ACCEPTANCE: a fresh FOREGROUND up UN-PARKS and RELAUNCHES a parked gone agent (regardless of fail count)", async () => { |
| 152 | + freshNet(); |
| 153 | + const id = "prk-alpha"; |
| 154 | + await spawnAgent(id); |
| 155 | + await waitCrashed(id); |
| 156 | + park(id); |
| 157 | + expect(await statusTag(id), "the agent must be parked before the bring-up").toBe(FLAPPING_STATUS); |
| 158 | + |
| 159 | + const out = records(await runForegroundUp(2500)); |
| 160 | + |
| 161 | + // It was UN-PARKED (the startup pass cleared the persisted park)... |
| 162 | + expect(out.some((r) => r.type === "unpark" && r.session === id), "a fresh foreground up must emit an unpark for the parked agent").toBe(true); |
| 163 | + // ...and then RELAUNCHED (the reconcile respawned it once un-parking made it eligible — a still-parked |
| 164 | + // agent would have been skipped and never respawned/replayed). |
| 165 | + const relaunched = out.some((r) => (r.type === "respawn" && r.session === id) || (r.type === "replay" && (r.spawned ?? []).includes(id))); |
| 166 | + expect(relaunched, "a fresh foreground up must relaunch the un-parked agent").toBe(true); |
| 167 | + // The persisted park is gone from disk. |
| 168 | + expect(await statusTag(id), "the flapping status tag must be cleared on disk after the bring-up").not.toBe(FLAPPING_STATUS); |
| 169 | + }, 45000); |
| 170 | + |
| 171 | + it("CONTROL: a `--once` bring-up does NOT un-park — parking stays durable for the shepherd cron", async () => { |
| 172 | + freshNet(); |
| 173 | + const id = "prk-beta"; |
| 174 | + await spawnAgent(id); |
| 175 | + await waitCrashed(id); |
| 176 | + park(id); |
| 177 | + |
| 178 | + const r = spawnSync(process.execPath, [bin, "up", net, "--once", "--json"], { env: childEnv(), encoding: "utf8" }); |
| 179 | + expect(r.status, `--once should exit 0\nstderr:\n${r.stderr}`).toBe(0); |
| 180 | + |
| 181 | + // No un-park was emitted, and the park is still on disk — `--once` must respect it (else it would |
| 182 | + // relaunch a genuinely broken agent every few minutes). |
| 183 | + expect(records(r.stdout).some((rec) => rec.type === "unpark"), "--once must NOT un-park anything").toBe(false); |
| 184 | + expect(await statusTag(id), "--once must leave the park intact").toBe(FLAPPING_STATUS); |
| 185 | + }, 45000); |
| 186 | +}); |
0 commit comments