From 3701b4218c7ad4e22c433b9da8cd136b98d01646 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 06:03:38 +0000 Subject: [PATCH 01/10] task: selfhost legacy compose adoption --- ...-11-20-selfhost-legacy-compose-adoption.md | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 tasks/active/2026-11-20-selfhost-legacy-compose-adoption.md diff --git a/tasks/active/2026-11-20-selfhost-legacy-compose-adoption.md b/tasks/active/2026-11-20-selfhost-legacy-compose-adoption.md new file mode 100644 index 0000000000..36f809f457 --- /dev/null +++ b/tasks/active/2026-11-20-selfhost-legacy-compose-adoption.md @@ -0,0 +1,63 @@ +# Self-host: adopt pre-L24 legacy compose installs so they can upgrade + +Idea: 01M7VRD7FTD50WANT5FKWQS678. Coordinator: task 01M7JMXS2JRW6QQMB1356ENPM3. + +## Problem + +The post-merge combined L23+L24 smoke on sam-box (2026-11-20, checkout 7f086c72b) found that +every install created before L24 (#2918) cannot upgrade to main: + +- main's `pnpm selfhost:upgrade` refuses it before any mutation: without `COMPOSE_PROJECT_NAME`, + "missing installation compose creation receipt"; with `sam-selfhost`, "legacy shared compose + project cannot safely roll back" (`scripts/selfhost/upgrade-preflight.ts:assertRollbackReady`). +- The pre-L24 tool on the box would check out main, whose `docker-compose.yml` requires + `COMPOSE_PROJECT_NAME`, and it takes no backup. +- The README asks for an "operator-controlled migration" but gives no procedure. + +## Research findings + +- `recordInstall` (install-record.ts) already writes the compose-project receipt when + `COMPOSE_PROJECT_NAME` equals the canonical name (`expectedComposeProjectFor`). +- The canonical name hashes the domain, state dir and `SAM_INSTALLATION_ID` (platform-keys.json). +- L24 treats `celld-data` as a disposable cache (backup-recovery.ts removes it on recovery). +- `runRollback` requires receipts and refuses legacy installs, so legacy rollback needs its own + path. Adoption changes no code and deploys nothing, so legacy rollback never restores the bucket. +- The first hop from a pre-L24 checkout must run the new tool: the operator checks out the new + ref, and the tool checks out the deployed `--from` ref while it adopts (the running stack's bind + mounts and compose config must match), then chains into the normal L24 `runUpgrade` from it. +- The box (.tmp/legacy-layout.txt): 4 volumes `sam-selfhost_{caddy-config,caddy-data,celld-data, + egress-fence-attestation}`, 8 containers (including the one-shot `celld-data-owner` and + `caddy-volumes`), all labelled working_dir/config_files/environment_file in /home/sam/sam. +- upgrade-lib.ts is at 493 lines (rule 18), so adoption lives in new modules. + +## Checklist + +- [ ] `--adopt-legacy --from ` on `selfhost:upgrade` (upgrade.ts), operator-only +- [ ] Ownership proof: every container in the legacy project is labelled with this checkout's + working dir, compose files and env file; bind mounts sit inside the checkout or state dir; + each legacy volume is mounted only by proven containers; the running config hash equals + `--from`'s compose config; there is exactly one running celld; the canonical project is empty + (or exactly what this journal created). Anything else refuses. +- [ ] Backup first (runBackup against the explicit legacy project) before any change +- [ ] Durable private journal (`.state/legacy-adoption.json`) plus a private copy of the original + .env; resume after a kill at every phase; a killed copy helper is removed before re-copy +- [ ] Copy each volume into a labelled canonical volume; verify by a content, mode and owner digest +- [ ] Set `COMPOSE_PROJECT_NAME`, start the canonical project, verify health, write receipts via + `recordInstall`, remove the stopped legacy containers, keep the legacy volumes (print rm command) +- [ ] Failure or failed verify rolls back to the legacy project: canonical containers and owned + volumes removed, .env restored byte for byte, legacy cache emptied if canonical celld ran, + legacy stack started and health-checked +- [ ] Chain into `runUpgrade` from `--from`; keep the journal until the upgrade succeeds +- [ ] README: legacy adoption procedure, resume and rollback behaviour +- [ ] Live real-Docker tests: adopt-then-upgrade (the L24 preflight passes afterwards), kill + mid-copy then resume, ambiguous-ownership refusal (another checkout on the same project), + failed verify rolls back to legacy; plus unit tests for argument and journal validation +- [ ] Security review; box adoption plus smoke steps 1, 2 and 4 after merge + +## Acceptance criteria + +- On a legacy fixture, adoption succeeds and `assertRollbackReady` then passes; data survives. +- A kill during a volume copy resumes to a verified complete copy. +- A legacy project also used by another checkout is refused with no change. +- A failed health verification leaves the legacy project running, its data and .env unchanged. +- sam-box is adopted and upgraded to main; smoke steps 1, 2 and 4 pass. From 5a1e199bbfad715b8e6e56d9839075bf808c2c2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 06:15:00 +0000 Subject: [PATCH 02/10] feat(selfhost): adopt pre-L24 legacy compose installs before upgrading Installs created before L24 run under the shared `sam-selfhost` Compose project with no compose creation receipt, so `pnpm selfhost:upgrade` refused them and their own checkout still held the pre-snapshot tool. `selfhost:upgrade --adopt-legacy --from ` proves the legacy project belongs to this checkout, takes the encrypted backup, copies the volumes into the canonical project, writes COMPOSE_PROJECT_NAME and the receipts, verifies health and then runs the normal upgrade. It is journaled and resumable, and rolls back to the legacy project on failure. Found by the post-merge L23+L24 smoke on the self-host box (idea 01M7VRD7FTD50WANT5FKWQS678). Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 54 ++- scripts/selfhost/legacy-adoption-inventory.ts | 225 ++++++++++ scripts/selfhost/legacy-adoption-journal.ts | 155 +++++++ scripts/selfhost/legacy-adoption-volumes.ts | 242 ++++++++++ scripts/selfhost/legacy-adoption.test.ts | 194 ++++++++ scripts/selfhost/legacy-adoption.ts | 422 ++++++++++++++++++ .../selfhost/live/legacy-adoption-child.ts | 45 ++ .../selfhost/live/legacy-adoption-fixture.ts | 219 +++++++++ .../live/legacy-adoption.live.test.ts | 289 ++++++++++++ scripts/selfhost/upgrade.ts | 25 +- 10 files changed, 1866 insertions(+), 4 deletions(-) create mode 100644 scripts/selfhost/legacy-adoption-inventory.ts create mode 100644 scripts/selfhost/legacy-adoption-journal.ts create mode 100644 scripts/selfhost/legacy-adoption-volumes.ts create mode 100644 scripts/selfhost/legacy-adoption.test.ts create mode 100644 scripts/selfhost/legacy-adoption.ts create mode 100644 scripts/selfhost/live/legacy-adoption-child.ts create mode 100644 scripts/selfhost/live/legacy-adoption-fixture.ts create mode 100644 scripts/selfhost/live/legacy-adoption.live.test.ts diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 73c3d7fb1c..e26a21bfc1 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -287,9 +287,57 @@ and Compose operation uses that installation's environment and overlays. Set `SAM_SELFHOST_STATE_DIR` to an absolute path when running Compose manually. Older installs using the shared `sam-selfhost` project may set `COMPOSE_PROJECT_NAME=sam-selfhost` -explicitly for backup. Upgrades and destructive teardown refuse that shared identity. Move to a -separate, installation-specific Compose project through an operator-controlled migration first; -these commands do not adopt or automatically migrate the old project. +explicitly for backup. Upgrades and destructive teardown refuse that shared identity. Move such an +install to its installation-specific project with legacy adoption (below) first. + +### Upgrade an install created before the shared project was retired + +Installs created before `pnpm selfhost:upgrade` gained snapshots run under the fixed Compose +project `sam-selfhost` and have no compose creation receipt, so a plain upgrade refuses them. Their +own checkout also still holds the old upgrade tool. Check out the new SAM ref, then let its tool +adopt the install and upgrade it in one command; `--from` is the full commit the stack runs now: + +```sh +git fetch origin && git checkout --detach && pnpm install --frozen-lockfile +pnpm selfhost:upgrade --adopt-legacy --from --to \ + --encryption-key-file "$HOME/.config/sam/backup.key" +``` + +The running stack is not touched by the checkout. Adoption changes no SAM code and deploys +nothing (`scripts/selfhost/legacy-adoption.ts:runLegacyAdoption`): + +1. It checks out `--from` again, so the compose files and bind mounts match the running stack. +2. It proves ownership (`legacy-adoption-inventory.ts:proveLegacyOwnership`): every container of + the `sam-selfhost` project carries this checkout's compose directory, compose files and `.env`; + bind mounts stay inside this checkout or its state directory; each project volume is used only + by those containers; each container's config hash equals `--from`'s compose configuration; and + the canonical project is empty. Another checkout on the same host using `sam-selfhost`, or a + wrong `--from`, refuses before any change. A shell `COMPOSE_PROJECT_NAME` also refuses. +3. It takes the encrypted backup (`--adoption-backup-to`, default + `backups/pre-adoption-`) from the live legacy stack. +4. It stops the legacy stack and copies each volume into `_` with the locally + built egress-fence image (no network, labelled with a random adoption id), verified by a digest of + every path's type, owner and mode and every file's content. +5. It writes `COMPOSE_PROJECT_NAME=` into `.env` (every other byte kept), starts the + same version under that project and checks health. It then writes the installation and + compose-project creation receipts and removes the stopped legacy containers. +6. It runs the normal upgrade from `--from` to the target, with its own fresh snapshot + (`--backup-to`), automatic rollback and printed rollback command. + +Each step is journaled in `.state/legacy-adoption.json`, beside a private copy of the original +`.env`. If the process is killed, check out the target ref again and rerun the identical command: +it resumes at the recorded step, removes any copy helper the killed run left and recopies an +unfinished volume from scratch. If adoption fails or the new project is unhealthy, it rolls back +to `sam-selfhost`: it removes the canonical containers and the volumes it created, restores `.env` +byte for byte and restarts the legacy stack. The legacy volumes are only read, except that the +disposable celld cache is emptied when the new celld already ran, because the fleet bucket may then +be newer than that cache. Adoption never restores the bucket: the same deployed version kept +writing it. After a rollback the checkout stays at `--from`, which matches the running stack. + +If the upgrade step fails, its automatic rollback restores `--from` under the adopted project; the +adoption stands and its journal remains. Check out the target and rerun the same command to retry +the upgrade. After a successful run the legacy volumes remain until you remove them with the +`docker volume rm` command it prints. ## Teardown diff --git a/scripts/selfhost/legacy-adoption-inventory.ts b/scripts/selfhost/legacy-adoption-inventory.ts new file mode 100644 index 0000000000..bb4b9bd197 --- /dev/null +++ b/scripts/selfhost/legacy-adoption-inventory.ts @@ -0,0 +1,225 @@ +/** + * Ownership proof for a pre-L24 install that still runs under the shared `sam-selfhost` Compose + * project (legacy-adoption.ts). Every container and volume of that project must provably belong + * to this checkout, .env and state directory; anything ambiguous refuses before a change. + */ +import { realpathSync } from 'node:fs'; +import { dirname, relative, resolve } from 'node:path'; + +import { type BoxContext, check } from './backup-lib'; + +/** The fixed project name every pre-L24 docker-compose.yml declared (`name: sam-selfhost`). */ +export const LEGACY_COMPOSE_PROJECT = 'sam-selfhost'; + +const PROJECT_LABEL = 'com.docker.compose.project'; +const SERVICE_LABEL = 'com.docker.compose.service'; +const VOLUME_LABEL = 'com.docker.compose.volume'; +const HASH_LABEL = 'com.docker.compose.config-hash'; +const CONTAINER_ID = /^[a-f0-9]{64}$/; +const VOLUME_SUFFIX = /^[a-z0-9][a-z0-9_.-]*$/; + +export interface LegacyContainer { + id: string; + service: string; + running: boolean; +} +export interface LegacyVolume { + /** The compose volume key (`celld-data`); the Docker name is `_`. */ + suffix: string; + name: string; +} +export interface LegacyInventory { + containers: LegacyContainer[]; + volumes: LegacyVolume[]; +} + +interface Inspected { + Id?: unknown; + State?: { Running?: unknown }; + Config?: { Labels?: Record | null }; + Mounts?: { Type?: unknown; Name?: unknown; Source?: unknown }[] | null; +} + +const refuse = (why: string): never => { + throw new Error(`Legacy adoption refused: ${why}`); +}; + +function lines(text: string): string[] { + return text + .split('\n') + .map((line) => line.trim()) + .filter(Boolean); +} + +function json(text: string, what: string): unknown { + try { + return JSON.parse(text); + } catch { + return refuse(`cannot parse ${what}`); + } +} + +function real(path: string): string { + try { + return realpathSync(path); + } catch { + return resolve(path); + } +} + +function inside(root: string, path: string): boolean { + const rel = relative(root, path); + return rel === '' || (!rel.startsWith('..') && !rel.startsWith('/')); +} + +/** Container IDs carrying `label`, all states. */ +export function containersLabelled(ctx: Pick, label: string): string[] { + const ids = lines( + check( + ctx.run('docker', ['ps', '--all', '--quiet', '--no-trunc', '--filter', `label=${label}`]), + 'list compose containers' + ).stdout + ); + if (ids.some((id) => !CONTAINER_ID.test(id))) refuse('unexpected container identifier'); + return ids; +} + +/** Volume names carrying `label`. */ +export function volumesLabelled(ctx: Pick, label: string): string[] { + return lines( + check( + ctx.run('docker', ['volume', 'ls', '--quiet', '--filter', `label=${label}`]), + 'list compose volumes' + ).stdout + ); +} + +/** `service hash` pairs for the active services of `--from`'s compose configuration. */ +function configHashes(output: string): Map { + const hashes = new Map(); + for (const line of lines(output)) { + const [service, hash, extra] = line.split(/\s+/); + if (!service || !hash || extra !== undefined || !/^[a-f0-9]{64}$/.test(hash)) + refuse('cannot read the compose configuration hashes'); + hashes.set(service as string, hash as string); + } + return hashes; +} + +export interface ProveOptions { + legacyProject: string; + /** Root of this checkout: bind mounts may come only from here or from the state directory. */ + checkoutRoot: string; + /** `docker compose ... config --hash '*'` for the legacy project at `--from`. */ + configHashOutput: string; + /** Before the stop: the legacy stack must be live, with exactly one running celld. */ + requireRunningCelld: boolean; +} + +/** + * Proves the legacy project is this checkout's install: container labels name this compose + * project directory, these compose files and this .env; bind mounts stay inside the checkout or + * the state directory; the config hashes equal `--from`'s configuration; and each project volume + * is used only by those containers. Returns the inventory adoption will move. + */ +export function proveLegacyOwnership( + ctx: Pick, + opts: ProveOptions +): LegacyInventory { + const projectLabel = `${PROJECT_LABEL}=${opts.legacyProject}`; + const ids = containersLabelled(ctx, projectLabel); + if (ids.length === 0) refuse(`no containers belong to compose project ${opts.legacyProject}`); + const inspected = json( + check(ctx.run('docker', ['inspect', ...ids]), 'inspect legacy containers').stdout, + 'container inspection' + ); + if (!Array.isArray(inspected) || inspected.length !== ids.length) + refuse('container inspection does not match the project inventory'); + + const workingDir = real(dirname(ctx.composeFiles[0] ?? '')); + const configFiles = ctx.composeFiles.map(real).join(','); + const envFile = real(ctx.envFile); + const stateDir = real(ctx.stateDir); + const checkoutRoot = real(opts.checkoutRoot); + const hashes = configHashes(opts.configHashOutput); + const mountedBy = new Map>(); + const containers: LegacyContainer[] = []; + + for (const item of inspected as Inspected[]) { + const id = typeof item.Id === 'string' ? item.Id : ''; + if (!ids.includes(id)) refuse('container inspection returned an unlisted container'); + const labels = item.Config?.Labels ?? {}; + const label = (name: string) => (typeof labels[name] === 'string' ? labels[name] : ''); + if (label(PROJECT_LABEL) !== opts.legacyProject) refuse(`container ${id} changed project`); + const files = label('com.docker.compose.project.config_files') + .split(',') + .filter(Boolean) + .map(real) + .join(','); + if ( + real(label('com.docker.compose.project.working_dir')) !== workingDir || + files !== configFiles || + real(label('com.docker.compose.project.environment_file')) !== envFile + ) + refuse( + `container ${id.slice(0, 12)} of project ${opts.legacyProject} belongs to another checkout, compose file set or .env` + ); + const service = label(SERVICE_LABEL); + const expectedHash = hashes.get(service); + if (!expectedHash) + refuse(`service ${service || '(none)'} is not in the --from compose configuration`); + if (label(HASH_LABEL) !== expectedHash) + refuse( + `service ${service} does not match the --from compose configuration; pass the deployed commit` + ); + for (const mount of item.Mounts ?? []) { + if (mount.Type === 'bind') { + const source = typeof mount.Source === 'string' ? real(mount.Source) : ''; + if (!inside(checkoutRoot, source) && !inside(stateDir, source)) + refuse(`service ${service} mounts a path outside this checkout and state directory`); + } else if (mount.Type === 'volume') { + const name = typeof mount.Name === 'string' ? mount.Name : ''; + if (!name.startsWith(`${opts.legacyProject}_`)) + refuse(`service ${service} mounts a volume of another project`); + mountedBy.set(name, (mountedBy.get(name) ?? new Set()).add(id)); + } else if (mount.Type !== 'tmpfs') { + refuse(`service ${service} has an unsupported mount type`); + } + } + containers.push({ id, service, running: item.State?.Running === true }); + } + const runningCelld = containers.filter((c) => c.service === 'celld' && c.running); + if (opts.requireRunningCelld && runningCelld.length !== 1) + refuse('the legacy project must have exactly one running celld'); + if (containers.filter((c) => c.service === 'celld').length !== 1) + refuse('the legacy project must have exactly one celld container'); + + const volumes: LegacyVolume[] = []; + for (const name of volumesLabelled(ctx, projectLabel)) { + const detail = json( + check(ctx.run('docker', ['volume', 'inspect', name]), 'inspect legacy volume').stdout, + 'volume inspection' + ); + const labels = (Array.isArray(detail) ? detail[0] : null)?.Labels ?? {}; + const suffix = typeof labels[VOLUME_LABEL] === 'string' ? labels[VOLUME_LABEL] : ''; + if ( + labels[PROJECT_LABEL] !== opts.legacyProject || + !VOLUME_SUFFIX.test(suffix) || + name !== `${opts.legacyProject}_${suffix}` + ) + refuse(`volume ${name} has inconsistent compose labels`); + if (!mountedBy.has(name)) refuse(`volume ${name} is not used by any proven container`); + // Any container that mounts the volume, of any project, must be one of the proven ones. + const users = lines( + check( + ctx.run('docker', ['ps', '--all', '--quiet', '--no-trunc', '--filter', `volume=${name}`]), + 'list volume users' + ).stdout + ); + if (users.some((id) => !ids.includes(id))) refuse(`volume ${name} is also used elsewhere`); + volumes.push({ suffix, name }); + } + for (const name of mountedBy.keys()) + if (!volumes.some((v) => v.name === name)) refuse(`volume ${name} has no compose labels`); + return { containers, volumes }; +} diff --git a/scripts/selfhost/legacy-adoption-journal.ts b/scripts/selfhost/legacy-adoption-journal.ts new file mode 100644 index 0000000000..613e3c1ba3 --- /dev/null +++ b/scripts/selfhost/legacy-adoption-journal.ts @@ -0,0 +1,155 @@ +/** + * The durable record of one legacy adoption (legacy-adoption.ts): private, fsynced and atomically + * replaced after every step, so a killed run resumes exactly where it stopped. The original .env + * bytes are kept beside it until the adoption either completes or is rolled back. + */ +import { existsSync, lstatSync, readFileSync, rmSync } from 'node:fs'; +import { isAbsolute, join } from 'node:path'; + +import { assertPrivateFile, replacePrivateFile } from './secret-files'; + +export const ADOPTION_JOURNAL_FILE = 'legacy-adoption.json'; +/** A private copy of the operator's .env from before COMPOSE_PROJECT_NAME was written. */ +export const ADOPTION_ENV_FILE = 'legacy-adoption.env'; + +/** + * proving: ownership proved, backup not yet recorded complete. backed-up: encrypted snapshot + * taken. stopped: legacy stack stopped. switched: canonical volumes copied and .env names the + * canonical project. adopted: canonical stack healthy and receipts written; only the upgrade + * remains. Each phase implies all earlier ones. + */ +export const ADOPTION_PHASES = ['proving', 'backed-up', 'stopped', 'switched', 'adopted'] as const; +export type AdoptionPhase = (typeof ADOPTION_PHASES)[number]; + +export interface AdoptionVolume { + suffix: string; + legacy: string; + canonical: string; + /** CreatedAt of the canonical volume this adoption made; set before any copy into it. */ + createdAt?: string; + /** Verified digest once the copy is complete. */ + digest?: string; +} + +export interface AdoptionJournal { + version: 1; + /** Random; labels every canonical volume this adoption creates. */ + adoptionId: string; + from: string; + to: string; + legacyProject: string; + canonicalProject: string; + installationId: string; + phase: AdoptionPhase; + backupDir?: string; + /** The legacy containers proved before the stop; removed only after verified adoption. */ + legacyContainers: string[]; + volumes: AdoptionVolume[]; + /** Set before the canonical stack is first started: its celld may have written the bucket. */ + canonicalStarted: boolean; +} + +const SHA = /^[a-f0-9]{40}$/; +const CONTAINER = /^[a-f0-9]{64}$/; + +const invalid = (path: string): never => { + throw new Error( + `${path} is not a legacy adoption record this tool wrote; preserve it and the stack for inspection` + ); +}; + +export function phaseAtLeast(journal: AdoptionJournal, phase: AdoptionPhase): boolean { + return ADOPTION_PHASES.indexOf(journal.phase) >= ADOPTION_PHASES.indexOf(phase); +} + +function validVolume(value: unknown, legacyProject: string, canonicalProject: string): boolean { + if (!value || typeof value !== 'object') return false; + const v = value as Record; + return ( + typeof v.suffix === 'string' && + v.legacy === `${legacyProject}_${v.suffix}` && + v.canonical === `${canonicalProject}_${v.suffix}` && + (v.createdAt === undefined || typeof v.createdAt === 'string') && + (v.digest === undefined || (typeof v.digest === 'string' && /^[a-f0-9]{64}$/.test(v.digest))) + ); +} + +export function readAdoptionJournal(stateDir: string): AdoptionJournal | null { + const path = join(stateDir, ADOPTION_JOURNAL_FILE); + if (!existsSync(path)) return null; + const stat = lstatSync(path); + if (!stat.isFile() || stat.isSymbolicLink()) return invalid(path); + assertPrivateFile(path); + let raw: unknown; + try { + raw = JSON.parse(readFileSync(path, 'utf8')); + } catch { + return invalid(path); + } + const j = raw as Record; + if ( + !raw || + typeof raw !== 'object' || + j.version !== 1 || + typeof j.adoptionId !== 'string' || + !/^[a-f0-9]{32}$/.test(j.adoptionId) || + typeof j.from !== 'string' || + !SHA.test(j.from) || + typeof j.to !== 'string' || + !SHA.test(j.to) || + typeof j.legacyProject !== 'string' || + typeof j.canonicalProject !== 'string' || + j.legacyProject === j.canonicalProject || + typeof j.installationId !== 'string' || + !/^[a-f0-9]{32}$/.test(j.installationId) || + !ADOPTION_PHASES.includes(j.phase as AdoptionPhase) || + (j.backupDir !== undefined && (typeof j.backupDir !== 'string' || !isAbsolute(j.backupDir))) || + !Array.isArray(j.legacyContainers) || + !j.legacyContainers.every((id) => typeof id === 'string' && CONTAINER.test(id)) || + !Array.isArray(j.volumes) || + !j.volumes.every((v) => + validVolume(v, j.legacyProject as string, j.canonicalProject as string) + ) || + typeof j.canonicalStarted !== 'boolean' + ) + return invalid(path); + return raw as AdoptionJournal; +} + +export function writeAdoptionJournal(stateDir: string, journal: AdoptionJournal): void { + replacePrivateFile( + join(stateDir, ADOPTION_JOURNAL_FILE), + `${JSON.stringify(journal, null, 2)}\n` + ); +} + +/** Keeps the operator's original .env once; a resumed run never overwrites the first copy. */ +export function saveOriginalEnv(stateDir: string, envFile: string): void { + const path = join(stateDir, ADOPTION_ENV_FILE); + if (existsSync(path)) { + assertPrivateFile(path); + return; + } + assertPrivateFile(envFile); + replacePrivateFile(path, readFileSync(envFile, 'utf8')); +} + +export function readOriginalEnv(stateDir: string): string { + const path = join(stateDir, ADOPTION_ENV_FILE); + assertPrivateFile(path); + return readFileSync(path, 'utf8'); +} + +export function clearAdoptionJournal(stateDir: string): void { + rmSync(join(stateDir, ADOPTION_ENV_FILE), { force: true }); + rmSync(join(stateDir, ADOPTION_JOURNAL_FILE), { force: true }); +} + +/** .env with COMPOSE_PROJECT_NAME set to `project`, every other byte preserved. */ +export function envWithProject(original: string, project: string): string { + const lines = original.split('\n'); + const kept = lines.filter((line) => !/^\s*(export\s+)?COMPOSE_PROJECT_NAME\s*=/.test(line)); + const body = kept.join('\n'); + const sep = body === '' || body.endsWith('\n') ? '' : '\n'; + return `${body}${sep}COMPOSE_PROJECT_NAME=${project}\n`; +} diff --git a/scripts/selfhost/legacy-adoption-volumes.ts b/scripts/selfhost/legacy-adoption-volumes.ts new file mode 100644 index 0000000000..f0a37db155 --- /dev/null +++ b/scripts/selfhost/legacy-adoption-volumes.ts @@ -0,0 +1,242 @@ +/** + * Volume moves for legacy adoption (legacy-adoption.ts). Each legacy volume is copied into a new + * canonical volume by a short-lived helper container with a deterministic name, so a copy killed + * with its operator process can be found and removed before it is retried. Copies are verified + * by a digest of every path's type, owner and mode plus every file's content (directory sizes are + * not compared: ext4 never shrinks a directory, so an emptied-and-recopied one differs). + */ +import { type BoxContext, check } from './backup-lib'; + +/** + * Alpine with busybox (sh, cp, find, stat, sha256sum), built locally on every box from + * deploy/selfhost/egress-fence (its celld-data-owner service already uses it on the cache volume). + */ +export const DEFAULT_ADOPTION_HELPER_IMAGE = 'sam-selfhost-egress-fence:local'; +/** Marks a canonical volume this adoption created, with the journal's random adoption id. */ +export const ADOPTION_LABEL = 'sam.selfhost.legacy-adoption'; + +const PROJECT_LABEL = 'com.docker.compose.project'; +const VOLUME_LABEL = 'com.docker.compose.volume'; + +/** Same digest on both sides; paths are sorted so readdir order does not matter. */ +const DIGEST_SCRIPT = + 'set -eu; cd "$1"; ' + + "{ find . -exec stat -c '%n|%F|%u|%g|%a' {} + | LC_ALL=C sort; " + + "find . -type f -exec sha256sum {} + | LC_ALL=C sort -k2; } | sha256sum | cut -d' ' -f1"; + +/** Empty the destination first: a retry after a kill must not merge with a partial copy. */ +const COPY_SCRIPT = 'set -eu; find /to -mindepth 1 -delete; cp -a /from/. /to/'; + +const EMPTY_SCRIPT = 'set -eu; find /cache -mindepth 1 -delete'; + +export function helperName(canonicalProject: string, suffix: string): string { + return `${canonicalProject}-legacy-adoption-${suffix}`; +} + +/** Every helper container name an adoption of these volumes can leave behind. */ +export function helperNames(canonicalProject: string, suffixes: readonly string[]): string[] { + return [ + ...suffixes.flatMap((suffix) => { + const name = helperName(canonicalProject, suffix); + return [name, `${name}-digest`]; + }), + helperName(canonicalProject, 'cache-reset'), + ]; +} + +export interface Helper { + image: string; + /** The journal's adoption id: helpers are labelled with it so a retry removes only its own. */ + adoptionId: string; +} + +function helperArgs(helper: Helper, name: string, mounts: string[], script: string[]): string[] { + return [ + 'run', + '--rm', + '--name', + name, + '--label', + `${ADOPTION_LABEL}=${helper.adoptionId}`, + '--network', + 'none', + '--cap-drop', + 'ALL', + // Root needs these to read every file and recreate exact owners, modes and setuid bits. + ...['CHOWN', 'FOWNER', 'DAC_OVERRIDE', 'DAC_READ_SEARCH', 'FSETID'].flatMap((cap) => [ + '--cap-add', + cap, + ]), + '--security-opt', + 'no-new-privileges', + ...mounts.flatMap((mount) => ['-v', mount]), + '--entrypoint', + 'sh', + helper.image, + '-c', + ...script, + ]; +} + +interface VolumeDetail { + Name?: unknown; + CreatedAt?: unknown; + Labels?: Record | null; +} + +function inspectVolume(ctx: Pick, name: string): VolumeDetail | null { + const result = ctx.run('docker', ['volume', 'inspect', name]); + if (result.status !== 0) { + if (/no such volume/i.test(result.stderr)) return null; + check(result, 'inspect adoption volume'); + } + let parsed: unknown; + try { + parsed = JSON.parse(result.stdout); + } catch { + throw new Error('Legacy adoption: cannot parse a volume inspection'); + } + if (!Array.isArray(parsed) || parsed.length !== 1) + throw new Error('Legacy adoption: ambiguous volume inspection'); + return parsed[0] as VolumeDetail; +} + +export interface CanonicalVolume { + name: string; + createdAt: string; +} + +/** A canonical volume this adoption (and only this adoption) created, or null when absent. */ +export function ownedCanonicalVolume( + ctx: Pick, + canonicalProject: string, + suffix: string, + adoptionId: string, + expectedCreatedAt?: string +): CanonicalVolume | null { + const name = `${canonicalProject}_${suffix}`; + const detail = inspectVolume(ctx, name); + if (!detail) return null; + const labels = detail.Labels ?? {}; + if ( + detail.Name !== name || + labels[PROJECT_LABEL] !== canonicalProject || + labels[VOLUME_LABEL] !== suffix || + labels[ADOPTION_LABEL] !== adoptionId || + typeof detail.CreatedAt !== 'string' || + (expectedCreatedAt !== undefined && detail.CreatedAt !== expectedCreatedAt) + ) + throw new Error( + `Legacy adoption refused: ${name} exists but was not created by this adoption; inspect it` + ); + return { name, createdAt: detail.CreatedAt }; +} + +/** Creates the canonical volume with the labels Compose expects plus this adoption's id. */ +export function createCanonicalVolume( + ctx: Pick, + canonicalProject: string, + suffix: string, + adoptionId: string +): CanonicalVolume { + const name = `${canonicalProject}_${suffix}`; + check( + ctx.run('docker', [ + 'volume', + 'create', + '--label', + `${PROJECT_LABEL}=${canonicalProject}`, + '--label', + `${VOLUME_LABEL}=${suffix}`, + '--label', + `${ADOPTION_LABEL}=${adoptionId}`, + name, + ]), + 'create canonical volume' + ); + const created = ownedCanonicalVolume(ctx, canonicalProject, suffix, adoptionId); + if (!created) throw new Error(`Legacy adoption: ${name} was not created`); + return created; +} + +/** Removes a helper a killed run left behind: only the exact name, and only if it is ours. */ +export function removeStaleHelper( + ctx: Pick, + helper: Helper, + name: string +): void { + const result = ctx.run('docker', [ + 'inspect', + '--type', + 'container', + '--format', + `{{index .Config.Labels "${ADOPTION_LABEL}"}}`, + name, + ]); + if (result.status !== 0) { + if (/no such (object|container)/i.test(result.stderr)) return; + check(result, 'inspect adoption helper'); + } + if (result.stdout.trim() !== helper.adoptionId) + throw new Error(`Legacy adoption refused: container ${name} is not this adoption's helper`); + check(ctx.run('docker', ['rm', '--force', name]), 'remove stale adoption helper'); +} + +export function volumeDigest( + ctx: Pick, + helper: Helper, + name: string, + container: string +): string { + removeStaleHelper(ctx, helper, container); + const digest = check( + ctx.run( + 'docker', + helperArgs(helper, container, [`${name}:/data:ro`], [DIGEST_SCRIPT, 'digest', '/data']) + ), + 'digest adoption volume' + ).stdout.trim(); + if (!/^[a-f0-9]{64}$/.test(digest)) throw new Error('Legacy adoption: invalid volume digest'); + return digest; +} + +/** Copies `from` into `to` (emptied first) and proves the two digests are equal. */ +export function copyVolume( + ctx: Pick, + helper: Helper, + from: string, + to: string, + container: string +): string { + removeStaleHelper(ctx, helper, container); + check( + ctx.run( + 'docker', + helperArgs(helper, container, [`${from}:/from:ro`, `${to}:/to`], [COPY_SCRIPT]) + ), + 'copy legacy volume' + ); + const source = volumeDigest(ctx, helper, from, `${container}-digest`); + const copy = volumeDigest(ctx, helper, to, `${container}-digest`); + if (source !== copy) + throw new Error(`Legacy adoption: copy of ${from} does not match its source`); + return copy; +} + +/** celld-data is a disposable cache; a stale one is emptied before the legacy celld restarts. */ +export function emptyVolume( + ctx: Pick, + helper: Helper, + name: string, + container: string +): void { + removeStaleHelper(ctx, helper, container); + check( + ctx.run('docker', helperArgs(helper, container, [`${name}:/cache`], [EMPTY_SCRIPT])), + 'empty stale legacy cache' + ); +} + +export function removeVolume(ctx: Pick, name: string): void { + check(ctx.run('docker', ['volume', 'rm', name]), 'remove canonical adoption volume'); +} diff --git a/scripts/selfhost/legacy-adoption.test.ts b/scripts/selfhost/legacy-adoption.test.ts new file mode 100644 index 0000000000..c2f8d48e49 --- /dev/null +++ b/scripts/selfhost/legacy-adoption.test.ts @@ -0,0 +1,194 @@ +/** + * Legacy adoption units: the journal refuses records it did not write, .env rewriting keeps every + * other byte, and the ownership proof refuses each ambiguous shape. The end-to-end behaviour on + * real Docker is in live/legacy-adoption.live.test.ts. + */ +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { proveLegacyOwnership } from './legacy-adoption-inventory.js'; +import { + ADOPTION_JOURNAL_FILE, + type AdoptionJournal, + envWithProject, + readAdoptionJournal, + saveOriginalEnv, + writeAdoptionJournal, +} from './legacy-adoption-journal.js'; +import type { RunResult } from './upgrade-lib.js'; + +let root: string; +beforeEach(() => { + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(join(resolve('.tmp'), 'sam-adoption-')); + mkdirSync(join(root, 'deploy/selfhost/.state'), { recursive: true, mode: 0o700 }); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +const state = () => join(root, 'deploy/selfhost/.state'); +const journal = (overrides: Partial = {}): AdoptionJournal => ({ + version: 1, + adoptionId: 'a'.repeat(32), + from: 'f'.repeat(40), + to: 'e'.repeat(40), + legacyProject: 'sam-selfhost', + canonicalProject: 'sam-selfhost-0123456789ab', + installationId: 'b'.repeat(32), + phase: 'stopped', + legacyContainers: ['c'.repeat(64)], + volumes: [ + { + suffix: 'celld-data', + legacy: 'sam-selfhost_celld-data', + canonical: 'sam-selfhost-0123456789ab_celld-data', + }, + ], + canonicalStarted: false, + ...overrides, +}); + +describe('adoption journal', () => { + it('round-trips a valid record', () => { + writeAdoptionJournal(state(), journal()); + expect(readAdoptionJournal(state())).toEqual(journal()); + }); + + it.each([ + ['an unknown phase', { phase: 'copying' }], + ['a short --from', { from: 'f'.repeat(12) }], + [ + 'a volume of another project', + { + volumes: [{ suffix: 'x', legacy: 'other_x', canonical: 'sam-selfhost-0123456789ab_x' }], + }, + ], + ['identical projects', { canonicalProject: 'sam-selfhost' }], + ['a relative backup path', { backupDir: 'backups/x' }], + ])('refuses %s', (_name, overrides) => { + writeAdoptionJournal(state(), journal(overrides as Partial)); + expect(() => readAdoptionJournal(state())).toThrow(/not a legacy adoption record/); + }); + + it('refuses a group-readable record', () => { + writeFileSync(join(state(), ADOPTION_JOURNAL_FILE), JSON.stringify(journal()), { mode: 0o644 }); + expect(() => readAdoptionJournal(state())).toThrow(/readable by group or others/); + }); + + it('keeps the first original .env across resumed runs', () => { + const env = join(root, 'deploy/selfhost/.env'); + writeFileSync(env, 'A=1\n', { mode: 0o600 }); + saveOriginalEnv(state(), env); + writeFileSync(env, 'A=1\nCOMPOSE_PROJECT_NAME=x\n', { mode: 0o600 }); + saveOriginalEnv(state(), env); + expect(readFileSync(join(state(), 'legacy-adoption.env'), 'utf8')).toBe('A=1\n'); + }); +}); + +describe('envWithProject', () => { + it('appends the project and keeps every other byte', () => { + expect(envWithProject('# c\nA=1\n', 'p')).toBe('# c\nA=1\nCOMPOSE_PROJECT_NAME=p\n'); + expect(envWithProject('A=1', 'p')).toBe('A=1\nCOMPOSE_PROJECT_NAME=p\n'); + }); + it('replaces an explicit legacy name instead of adding a second one', () => { + expect(envWithProject('COMPOSE_PROJECT_NAME=sam-selfhost\nA=1\n', 'p')).toBe( + 'A=1\nCOMPOSE_PROJECT_NAME=p\n' + ); + }); +}); + +describe('proveLegacyOwnership', () => { + const ID = 'd'.repeat(64); + const HASH = '9'.repeat(64); + let mounts: { Type: string; Name?: string; Source?: string }[]; + let volumeUsers: string[]; + let hash: string; + + const ctx = () => { + const dir = join(root, 'deploy/selfhost'); + const run = (_command: string, args: string[]): RunResult => { + const ok = (stdout: string) => ({ status: 0, stdout, stderr: '' }); + if (args[0] === 'ps' && args.includes('label=com.docker.compose.project=sam-selfhost')) + return ok(`${ID}\n`); + if (args[0] === 'ps') return ok(volumeUsers.join('\n')); + if (args[0] === 'inspect') + return ok( + JSON.stringify([ + { + Id: ID, + State: { Running: true }, + Config: { + Labels: { + 'com.docker.compose.project': 'sam-selfhost', + 'com.docker.compose.service': 'celld', + 'com.docker.compose.config-hash': hash, + 'com.docker.compose.project.working_dir': dir, + 'com.docker.compose.project.config_files': join(dir, 'docker-compose.yml'), + 'com.docker.compose.project.environment_file': join(dir, '.env'), + }, + }, + Mounts: mounts, + }, + ]) + ); + if (args[0] === 'volume' && args[1] === 'ls') return ok('sam-selfhost_celld-data\n'); + return ok( + JSON.stringify([ + { + Labels: { + 'com.docker.compose.project': 'sam-selfhost', + 'com.docker.compose.volume': 'celld-data', + }, + }, + ]) + ); + }; + return { + run, + envFile: join(dir, '.env'), + stateDir: join(dir, '.state'), + composeFiles: [join(dir, 'docker-compose.yml')], + }; + }; + const prove = () => + proveLegacyOwnership(ctx(), { + legacyProject: 'sam-selfhost', + checkoutRoot: root, + configHashOutput: `celld ${HASH}\n`, + requireRunningCelld: true, + }); + + beforeEach(() => { + mounts = [ + { Type: 'volume', Name: 'sam-selfhost_celld-data' }, + { Type: 'bind', Source: join(root, 'deploy/selfhost/celld/start.sh') }, + { Type: 'bind', Source: join(root, 'deploy/selfhost/.state/egress-fence.nft') }, + ]; + volumeUsers = [ID]; + hash = HASH; + }); + + it("accepts this checkout's legacy stack (control)", () => { + expect(prove()).toEqual({ + containers: [{ id: ID, service: 'celld', running: true }], + volumes: [{ suffix: 'celld-data', name: 'sam-selfhost_celld-data' }], + }); + }); + it("refuses a stack whose config hash is not --from's", () => { + hash = '8'.repeat(64); + expect(prove).toThrow(/does not match the --from compose configuration/); + }); + it('refuses a bind mount outside the checkout and state directory', () => { + mounts.push({ Type: 'bind', Source: '/srv/elsewhere/data' }); + expect(prove).toThrow(/outside this checkout/); + }); + it('refuses a volume another container also uses', () => { + volumeUsers = [ID, 'e'.repeat(64)]; + expect(prove).toThrow(/also used elsewhere/); + }); + it('refuses a volume of another project', () => { + mounts.push({ Type: 'volume', Name: 'other_data' }); + expect(prove).toThrow(/volume of another project/); + }); +}); diff --git a/scripts/selfhost/legacy-adoption.ts b/scripts/selfhost/legacy-adoption.ts new file mode 100644 index 0000000000..2d4daa2a12 --- /dev/null +++ b/scripts/selfhost/legacy-adoption.ts @@ -0,0 +1,422 @@ +/** + * `pnpm selfhost:upgrade --adopt-legacy --from --to `: moves a pre-L24 + * install off the shared `sam-selfhost` Compose project into its canonical installation-specific + * project, then upgrades it with the normal L24 path (upgrade-lib.ts:runUpgrade). + * + * Adoption changes no SAM code and deploys nothing: it proves ownership, takes the encrypted + * snapshot, stops the legacy stack, copies its volumes, writes COMPOSE_PROJECT_NAME, starts the + * same deployed version under the new name, verifies health and writes the creation receipts. + * Any failure before verified health rolls back to the legacy project (its volumes are never + * changed, except that a stale disposable celld cache is emptied). Every step is journaled + * (legacy-adoption-journal.ts), so a killed run resumes where it stopped. + */ +import { randomBytes } from 'node:crypto'; +import { existsSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; + +import { check, composeArgs, composeRunEnv, runBackup } from './backup-lib'; +import { REPO_ROOT } from './deploy-steps'; +import { expectedComposeProjectFor, readInstallRecord, recordInstall } from './install-record'; +import { + containersLabelled, + LEGACY_COMPOSE_PROJECT, + proveLegacyOwnership, +} from './legacy-adoption-inventory'; +import { + ADOPTION_ENV_FILE, + type AdoptionJournal, + clearAdoptionJournal, + envWithProject, + phaseAtLeast, + readAdoptionJournal, + readOriginalEnv, + saveOriginalEnv, + writeAdoptionJournal, +} from './legacy-adoption-journal'; +import { + copyVolume, + createCanonicalVolume, + DEFAULT_ADOPTION_HELPER_IMAGE, + emptyVolume, + type Helper, + helperName, + helperNames, + ownedCanonicalVolume, + removeStaleHelper, + removeVolume, +} from './legacy-adoption-volumes'; +import { assertOperatorExecution } from './operator-only'; +import { readPrivateJson, replacePrivateFile } from './secret-files'; +import { UPGRADE_PENDING_FILE } from './upgrade-journal'; +import type { BoxContext, UpgradeOptions } from './upgrade-lib'; + +export interface AdoptionOptions { + /** The target ref; the operator has already checked it out (its tool runs this adoption). */ + to: string; + /** Full SHA of the SAM commit the legacy stack is running (checked against its config hashes). */ + from: string; + checkHealth: () => Promise; + /** The adoption snapshot; default `backups/pre-adoption-` beside the state dir. */ + backupDir?: string; + /** Passed to the upgrade that follows adoption (its own fresh snapshot). */ + upgradeBackupDir?: string; + /** The encrypted snapshot (backup-lib.ts runBackup); replaceable only in tests. */ + backup?: typeof runBackup; + /** The upgrade that follows a verified adoption: upgrade-lib.ts runUpgrade. */ + upgrade: (ctx: BoxContext, opts: UpgradeOptions) => Promise; + legacyProject?: string; + helperImage?: string; + checkoutRoot?: string; +} + +const SHA = /^[a-f0-9]{40}$/; + +const helperOf = (opts: AdoptionOptions, journal: AdoptionJournal): Helper => ({ + image: opts.helperImage ?? DEFAULT_ADOPTION_HELPER_IMAGE, + adoptionId: journal.adoptionId, +}); + +function backupCtx(ctx: BoxContext) { + return { + ...ctx, + now: () => Date.now(), + user: process.getuid && process.getgid ? `${process.getuid()}:${process.getgid()}` : undefined, + }; +} + +const withProject = (ctx: BoxContext, project: string): BoxContext => ({ + ...ctx, + box: { ...ctx.box, COMPOSE_PROJECT_NAME: project }, +}); + +function compose(ctx: BoxContext, args: string[], what: string): string { + return check(ctx.run('docker', composeArgs(ctx, args), composeRunEnv(ctx)), what).stdout; +} + +function git(ctx: BoxContext, args: string[], what: string): string { + return check(ctx.run('git', args), what).stdout.trim(); +} + +function installationIdOf(stateDir: string): string { + const keys = join(stateDir, 'platform-keys.json'); + if (!existsSync(keys)) + throw new Error('Legacy adoption refused: no platform-keys.json; run deploy --init first'); + const id = readPrivateJson(keys).SAM_INSTALLATION_ID ?? ''; + if (!/^[a-f0-9]{32}$/.test(id)) + throw new Error('Legacy adoption refused: cannot read SAM_INSTALLATION_ID'); + return id; +} + +function hasComposeReceipt(stateDir: string, project: string): boolean { + return readInstallRecord(stateDir).some( + (r) => + r.cloud === 'box' && + r.kind === 'compose-project' && + r.name === project && + r.action === 'created' && + !r.removedAt + ); +} + +/** A new adoption: the install must be a legacy one this tool has not adopted yet. */ +function startJournal(ctx: BoxContext, opts: AdoptionOptions, to: string): AdoptionJournal { + const legacyProject = opts.legacyProject ?? LEGACY_COMPOSE_PROJECT; + const named = ctx.box.COMPOSE_PROJECT_NAME; + if (named !== undefined && named !== legacyProject) + throw new Error( + `Legacy adoption refused: COMPOSE_PROJECT_NAME is ${named}, not the legacy ${legacyProject}; use a normal upgrade` + ); + const installationId = installationIdOf(ctx.stateDir); + const box = { ...ctx.box }; + delete box.COMPOSE_PROJECT_NAME; + const canonicalProject = expectedComposeProjectFor(box, ctx.stateDir, installationId); + if (canonicalProject === legacyProject) + throw new Error('Legacy adoption refused: canonical and legacy projects coincide'); + if (hasComposeReceipt(ctx.stateDir, canonicalProject)) + throw new Error( + 'Legacy adoption refused: this install already has its compose creation receipt; use a normal upgrade' + ); + return { + version: 1, + adoptionId: randomBytes(16).toString('hex'), + from: opts.from, + to, + legacyProject, + canonicalProject, + installationId, + phase: 'proving', + legacyContainers: [], + volumes: [], + canonicalStarted: false, + }; +} + +/** The canonical project must be empty, apart from volumes this journal created. */ +function assertCanonicalClear(ctx: BoxContext, journal: AdoptionJournal): void { + const label = `com.docker.compose.project=${journal.canonicalProject}`; + if (!journal.canonicalStarted && containersLabelled(ctx, label).length > 0) + throw new Error( + `Legacy adoption refused: compose project ${journal.canonicalProject} already has containers` + ); + const listed = check( + ctx.run('docker', ['volume', 'ls', '--quiet', '--filter', `label=${label}`]), + 'list canonical volumes' + ) + .stdout.split('\n') + .map((s) => s.trim()) + .filter(Boolean); + for (const name of listed) { + const owned = journal.volumes.find((v) => v.canonical === name); + if (!owned?.createdAt) + throw new Error(`Legacy adoption refused: ${name} exists and is not this adoption's copy`); + ownedCanonicalVolume( + ctx, + journal.canonicalProject, + owned.suffix, + journal.adoptionId, + owned.createdAt + ); + } +} + +async function adopt(ctx: BoxContext, opts: AdoptionOptions, journal: AdoptionJournal) { + const save = () => writeAdoptionJournal(ctx.stateDir, journal); + const legacy = withProject(ctx, journal.legacyProject); + const canonical = withProject(ctx, journal.canonicalProject); + const helper = helperOf(opts, journal); + // A killed run can leave a copy or digest helper mounting the volumes: remove ours first. + for (const name of helperNames( + journal.canonicalProject, + journal.volumes.map((v) => v.suffix) + )) + removeStaleHelper(ctx, helper, name); + const stopped = phaseAtLeast(journal, 'stopped'); + const inventory = proveLegacyOwnership(legacy, { + legacyProject: journal.legacyProject, + checkoutRoot: opts.checkoutRoot ?? REPO_ROOT, + configHashOutput: compose(legacy, ['config', '--hash', '*'], 'read legacy config hashes'), + requireRunningCelld: !stopped, + }); + assertCanonicalClear(ctx, journal); + if (journal.volumes.length === 0) { + journal.legacyContainers = inventory.containers.map((c) => c.id); + journal.volumes = inventory.volumes.map((v) => ({ + suffix: v.suffix, + legacy: v.name, + canonical: `${journal.canonicalProject}_${v.suffix}`, + })); + } else if ( + JSON.stringify(inventory.volumes.map((v) => v.name).sort()) !== + JSON.stringify(journal.volumes.map((v) => v.legacy).sort()) || + inventory.containers.some((c) => !journal.legacyContainers.includes(c.id)) + ) { + throw new Error( + 'Legacy adoption refused: the legacy project changed since this adoption began' + ); + } + save(); + + if (!phaseAtLeast(journal, 'backed-up')) { + // A run killed mid-backup leaves an unproven partial: it is kept, never reused. + const fresh = join( + dirname(ctx.stateDir), + 'backups', + `pre-adoption-${new Date().toISOString().replace(/[:.]/g, '-')}` + ); + const dest = + journal.backupDir === undefined + ? (opts.backupDir ?? fresh) + : existsSync(journal.backupDir) + ? fresh + : journal.backupDir; + journal.backupDir = resolve(dest); + save(); + (opts.backup ?? runBackup)(backupCtx(legacy), journal.backupDir, journal.from); + journal.phase = 'backed-up'; + save(); + } + + try { + if (!phaseAtLeast(journal, 'stopped')) { + compose(legacy, ['stop'], 'stop legacy stack'); + journal.phase = 'stopped'; + save(); + } + if (!phaseAtLeast(journal, 'switched')) { + for (const volume of journal.volumes) { + if (volume.digest) continue; + const existing = ownedCanonicalVolume( + ctx, + journal.canonicalProject, + volume.suffix, + journal.adoptionId, + volume.createdAt + ); + if (!existing) { + volume.createdAt = createCanonicalVolume( + ctx, + journal.canonicalProject, + volume.suffix, + journal.adoptionId + ).createdAt; + save(); + } + ctx.log(`copying ${volume.legacy} -> ${volume.canonical}`); + volume.digest = copyVolume( + ctx, + helper, + volume.legacy, + volume.canonical, + helperName(journal.canonicalProject, volume.suffix) + ); + save(); + } + saveOriginalEnv(ctx.stateDir, ctx.envFile); + replacePrivateFile( + ctx.envFile, + envWithProject(readOriginalEnv(ctx.stateDir), journal.canonicalProject) + ); + journal.phase = 'switched'; + save(); + } + journal.canonicalStarted = true; + save(); + compose(canonical, ['up', '-d'], 'start canonical stack'); + if (!(await opts.checkHealth())) + throw new Error('the adopted install is not healthy under its canonical compose project'); + } catch (error) { + await rollbackToLegacy(ctx, opts, journal); + throw error; + } + + recordInstall(ctx.stateDir, ctx.envFile, canonical.box, journal.installationId); + journal.phase = 'adopted'; + save(); + removeLegacyContainers(ctx, journal); + ctx.log(`adopted: compose project ${journal.canonicalProject} is healthy with its receipts`); +} + +/** The stopped legacy containers, by their proved IDs only; volumes are kept. Idempotent. */ +function removeLegacyContainers(ctx: BoxContext, journal: AdoptionJournal): void { + const remaining = new Set( + containersLabelled(ctx, `com.docker.compose.project=${journal.legacyProject}`) + ); + const stale = journal.legacyContainers.filter((id) => remaining.has(id)); + if (stale.length) check(ctx.run('docker', ['rm', ...stale]), 'remove stopped legacy containers'); +} + +/** Back to the legacy project; its volumes were only read, except the disposable cache. */ +async function rollbackToLegacy(ctx: BoxContext, opts: AdoptionOptions, journal: AdoptionJournal) { + ctx.log('legacy adoption failed; restoring the legacy compose project'); + const legacy = withProject(ctx, journal.legacyProject); + const canonical = withProject(ctx, journal.canonicalProject); + const helper = helperOf(opts, journal); + try { + if (journal.canonicalStarted) + compose(canonical, ['down', '--remove-orphans'], 'stop canonical stack'); + for (const volume of journal.volumes) { + removeStaleHelper(ctx, helper, helperName(journal.canonicalProject, volume.suffix)); + removeStaleHelper( + ctx, + helper, + `${helperName(journal.canonicalProject, volume.suffix)}-digest` + ); + if (!volume.createdAt) continue; + const owned = ownedCanonicalVolume( + ctx, + journal.canonicalProject, + volume.suffix, + journal.adoptionId, + volume.createdAt + ); + if (owned) removeVolume(ctx, owned.name); + } + if (phaseAtLeast(journal, 'switched') || existsSync(join(ctx.stateDir, ADOPTION_ENV_FILE))) + replacePrivateFile(ctx.envFile, readOriginalEnv(ctx.stateDir)); + const cache = journal.volumes.find((v) => v.suffix === 'celld-data'); + // The canonical celld may have written newer data to the bucket than this cache holds. + if (journal.canonicalStarted && cache) + emptyVolume(ctx, helper, cache.legacy, helperName(journal.canonicalProject, 'cache-reset')); + compose(legacy, ['up', '-d'], 'restart legacy stack'); + if (!(await opts.checkHealth())) throw new Error('legacy stack is not healthy'); + } catch { + throw new Error( + `legacy adoption failed and rollback did not complete; keep ${ctx.stateDir}/legacy-adoption.json and the legacy volumes, then inspect the stack` + ); + } + clearAdoptionJournal(ctx.stateDir); + ctx.log( + `restored the legacy project ${journal.legacyProject} at ${journal.from.slice(0, 12)}; to retry, check out ${journal.to} and rerun the same command` + ); +} + +export async function runLegacyAdoption(ctx: BoxContext, opts: AdoptionOptions): Promise { + assertOperatorExecution(); + if (!SHA.test(opts.from)) throw new Error('--from must be the full 40-character deployed commit'); + if (process.env.COMPOSE_PROJECT_NAME !== undefined) + throw new Error('Unset COMPOSE_PROJECT_NAME in the shell before legacy adoption'); + if (git(ctx, ['status', '--porcelain', '--untracked-files=no'], 'git status') !== '') + throw new Error( + 'the checkout has uncommitted changes to tracked files; commit or stash them first' + ); + git(ctx, ['cat-file', '-e', `${opts.from}^{commit}`], `find --from ${opts.from}`); + const head = git(ctx, ['rev-parse', 'HEAD'], 'git rev-parse HEAD'); + + let journal = readAdoptionJournal(ctx.stateDir); + if (journal) { + if (journal.from !== opts.from) + throw new Error(`an unfinished adoption started from ${journal.from}; pass the same --from`); + if ( + head !== journal.to && + head !== journal.from && + !existsSync(join(ctx.stateDir, UPGRADE_PENDING_FILE)) + ) + throw new Error(`check out ${journal.to} (the adoption target) before resuming`); + ctx.log(`resuming legacy adoption at phase ${journal.phase}`); + } else { + if (head === opts.from) + throw new Error('check out the target SAM ref first; --from is the commit the stack runs'); + const target = git(ctx, ['rev-parse', '--verify', `${opts.to}^{commit}`], `resolve ${opts.to}`); + if (target !== head) + throw new Error(`check out ${opts.to} first: legacy adoption runs from the target checkout`); + journal = startJournal(ctx, opts, head); + } + + if (!phaseAtLeast(journal, 'adopted')) { + // The stack's bind mounts and compose files must be the deployed version while it moves. + if (head !== journal.from) git(ctx, ['checkout', '--detach', journal.from], 'check out --from'); + try { + await adopt(ctx, opts, journal); + } catch (error) { + if (!phaseAtLeast(journal, 'stopped')) { + // Nothing moved yet: return the operator's checkout and forget the attempt. + clearAdoptionJournal(ctx.stateDir); + git(ctx, ['checkout', '--detach', journal.to], 'restore target checkout'); + } + throw error; + } + } + + removeLegacyContainers(ctx, journal); + const adopted = withProject(ctx, journal.canonicalProject); + if ( + !existsSync(join(ctx.stateDir, UPGRADE_PENDING_FILE)) && + git(ctx, ['rev-parse', 'HEAD'], 'git rev-parse HEAD') !== journal.from + ) + git(ctx, ['checkout', '--detach', journal.from], 'check out --from'); + try { + await opts.upgrade(adopted, { + to: journal.to, + checkHealth: opts.checkHealth, + ...(opts.upgradeBackupDir ? { backupDir: opts.upgradeBackupDir } : {}), + }); + } catch (error) { + ctx.log( + `adoption is complete (project ${journal.canonicalProject}); the upgrade failed. Check out ${journal.to} and rerun the same command to retry it` + ); + throw error; + } + clearAdoptionJournal(ctx.stateDir); + ctx.log('legacy volumes are kept until you remove them after checking the upgraded install:'); + ctx.log(` docker volume rm ${journal.volumes.map((v) => v.legacy).join(' ')}`); +} diff --git a/scripts/selfhost/live/legacy-adoption-child.ts b/scripts/selfhost/live/legacy-adoption-child.ts new file mode 100644 index 0000000000..226dbaee82 --- /dev/null +++ b/scripts/selfhost/live/legacy-adoption-child.ts @@ -0,0 +1,45 @@ +/** + * Runs one legacy adoption in its own process so legacy-adoption.live.test.ts can SIGKILL it in + * the middle of a volume copy. argv[2] is the fixture JSON (legacy-adoption-fixture.ts). + */ +import { runLegacyAdoption } from '../legacy-adoption.js'; +import { + ALPINE, + fakeBackup, + FakeGit, + type Fixture, + fixtureContext, + FROM, + projectHealth, + TO, +} from './legacy-adoption-fixture.js'; + +const parsed: unknown = JSON.parse(process.argv[2] ?? '{}'); +const keys = [ + 'root', + 'selfhostDir', + 'envFile', + 'stateDir', + 'composeFile', + 'legacyProject', + 'envText', +]; +if ( + !parsed || + typeof parsed !== 'object' || + !keys.every((key) => typeof (parsed as Record)[key] === 'string') +) + throw new Error('legacy-adoption-child: invalid fixture argument'); +const fixture = parsed as Fixture; +const git = new FakeGit(TO); +const ctx = fixtureContext(fixture, git, []); +await runLegacyAdoption(ctx, { + to: TO, + from: FROM, + checkHealth: projectHealth(fixture), + backup: fakeBackup([]), + upgrade: async () => {}, + legacyProject: fixture.legacyProject, + helperImage: ALPINE, + checkoutRoot: fixture.root, +}); diff --git a/scripts/selfhost/live/legacy-adoption-fixture.ts b/scripts/selfhost/live/legacy-adoption-fixture.ts new file mode 100644 index 0000000000..bc66da0352 --- /dev/null +++ b/scripts/selfhost/live/legacy-adoption-fixture.ts @@ -0,0 +1,219 @@ +/** + * A real pre-L24 install for the legacy adoption tests: a checkout-shaped directory whose + * docker-compose.yml declares a fixed project name (as every pre-L24 file declared + * `name: sam-selfhost`), started with real Docker, with data in its volumes. git is answered by a + * small fake (the adoption only checks out refs); docker is real. + */ +import { spawnSync } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { parseDotenv } from '../secret-files.js'; +import type { BoxContext, RunResult } from '../upgrade-lib.js'; +import { DOCKER, LIVE_TMP } from './harness.js'; + +/** The egress fence's pinned base (deploy/selfhost/egress-fence/Dockerfile). */ +export const ALPINE = + 'alpine:3.22@sha256:49340b346798875b5592e5d420241f2f9cfba5f47e62ebb1446a1b34734e898f'; +export const FROM = 'f'.repeat(40); +export const TO = 'e'.repeat(40); + +export interface Fixture { + root: string; + selfhostDir: string; + envFile: string; + stateDir: string; + composeFile: string; + legacyProject: string; + envText: string; +} + +export function docker(args: string[], env?: NodeJS.ProcessEnv): RunResult { + const result = spawnSync(DOCKER, args, { + encoding: 'utf8', + env: env ?? process.env, + maxBuffer: 64 * 1024 * 1024, + }); + return { status: result.status ?? 1, stdout: result.stdout ?? '', stderr: result.stderr ?? '' }; +} + +export function dockerOk(args: string[]): string { + const result = docker(args); + if (result.status !== 0) throw new Error(`docker ${args.join(' ')}: ${result.stderr}`); + return result.stdout.trim(); +} + +const COMPOSE = (project: string) => `name: ${project} +services: + celld: + image: ${ALPINE} + command: ['sleep', 'infinity'] + init: true + volumes: + - celld-data:/var/lib/celld + - ./conf:/conf:ro + caddy: + image: ${ALPINE} + command: ['sleep', 'infinity'] + init: true + volumes: + - caddy-data:/data +volumes: + celld-data: + caddy-data: +`; + +export function createFixture(): Fixture { + mkdirSync(LIVE_TMP, { recursive: true }); + const root = mkdtempSync(join(LIVE_TMP, 'legacy-adoption-')); + const selfhostDir = join(root, 'deploy/selfhost'); + const stateDir = join(selfhostDir, '.state'); + mkdirSync(join(selfhostDir, 'conf'), { recursive: true }); + mkdirSync(stateDir, { recursive: true, mode: 0o700 }); + writeFileSync(join(selfhostDir, 'conf/app.conf'), 'listen 8080\n'); + const legacyProject = `samlegacy${randomBytes(4).toString('hex')}`; + const composeFile = join(selfhostDir, 'docker-compose.yml'); + writeFileSync(composeFile, COMPOSE(legacyProject)); + const envText = + '# operator settings\nSAM_DOMAIN=adopt.example.test\nCELLD_BUCKET=gs://adopt-fixture/celld\n'; + const envFile = join(selfhostDir, '.env'); + writeFileSync(envFile, envText, { mode: 0o600 }); + writeFileSync( + join(stateDir, 'platform-keys.json'), + `${JSON.stringify({ SAM_INSTALLATION_ID: randomBytes(16).toString('hex') })}\n`, + { mode: 0o600 } + ); + const fixture = { root, selfhostDir, envFile, stateDir, composeFile, legacyProject, envText }; + dockerOk(composeCli(fixture, legacyProject, ['up', '-d'])); + return fixture; +} + +export function composeCli(fixture: Fixture, project: string, args: string[]): string[] { + return [ + 'compose', + '--project-name', + project, + '-f', + fixture.composeFile, + '--env-file', + fixture.envFile, + ...args, + ]; +} + +export function containerOf(project: string, service: string): string { + return dockerOk([ + 'ps', + '--quiet', + '--filter', + `label=com.docker.compose.project=${project}`, + '--filter', + `label=com.docker.compose.service=${service}`, + ]); +} + +/** Owner, mode and content survive a copy; also a symlink and an empty directory. */ +export function seedData(fixture: Fixture, cacheFiles = 0, cacheMegabytes = 0): void { + const celld = containerOf(fixture.legacyProject, 'celld'); + const caddy = containerOf(fixture.legacyProject, 'caddy'); + const script = [ + 'set -eu', + 'mkdir -p /var/lib/celld/do/empty', + 'echo durable > /var/lib/celld/do/marker', + 'chown 7103:7103 /var/lib/celld/do/marker', + 'chmod 640 /var/lib/celld/do/marker', + 'ln -s marker /var/lib/celld/do/link', + `i=0; while [ $i -lt ${cacheFiles} ]; do echo $i > /var/lib/celld/f$i; i=$((i+1)); done`, + cacheMegabytes > 0 + ? `dd if=/dev/urandom of=/var/lib/celld/blob bs=1M count=${cacheMegabytes} 2>/dev/null` + : 'true', + ].join('\n'); + dockerOk(['exec', celld, 'sh', '-c', script]); + dockerOk(['exec', caddy, 'sh', '-c', 'echo cert > /data/cert.pem && chmod 600 /data/cert.pem']); +} + +export function readVolumeFile(volume: string, path: string): string { + return dockerOk([ + 'run', + '--rm', + '-v', + `${volume}:/v:ro`, + ALPINE, + 'sh', + '-c', + `stat -c '%u:%g:%a' /v/${path} && cat /v/${path}`, + ]); +} + +/** Records git commands; answers the few the adoption asks. */ +export class FakeGit { + head: string; + checkouts: string[] = []; + constructor(head = TO) { + this.head = head; + } + run(args: string[]): RunResult { + const ok = (stdout = '') => ({ status: 0, stdout, stderr: '' }); + if (args[0] === 'status') return ok(''); + if (args[0] === 'cat-file') return ok(''); + if (args[0] === 'rev-parse' && args[1] === 'HEAD') return ok(`${this.head}\n`); + if (args[0] === 'rev-parse' && args[1] === '--verify') { + const ref = (args[2] ?? '').replace(/\^\{commit\}$/, ''); + return ref === TO || ref === FROM ? ok(`${ref}\n`) : { status: 128, stdout: '', stderr: '' }; + } + if (args[0] === 'checkout') { + this.head = args[2] ?? this.head; + this.checkouts.push(this.head); + return ok(''); + } + return { status: 1, stdout: '', stderr: `unexpected git ${args.join(' ')}` }; + } +} + +export function fixtureContext(fixture: Fixture, git: FakeGit, logs: string[] = []): BoxContext { + return { + box: parseDotenv(readFileSync(fixture.envFile, 'utf8'), fixture.envFile), + envFile: fixture.envFile, + stateDir: fixture.stateDir, + composeFiles: [fixture.composeFile], + run: (command, args, env) => (command === 'git' ? git.run(args) : docker(args, env)), + log: (message) => logs.push(message), + }; +} + +/** Healthy when the project named in .env (or the legacy one) has a running celld. */ +export function projectHealth(fixture: Fixture): () => Promise { + return async () => { + const box = parseDotenv(readFileSync(fixture.envFile, 'utf8'), fixture.envFile); + return containerOf(box.COMPOSE_PROJECT_NAME ?? fixture.legacyProject, 'celld') !== ''; + }; +} + +/** A stand-in for the encrypted snapshot: the real one needs a fleet bucket. */ +export function fakeBackup( + calls: string[] +): (ctx: { box: Record }, dest: string) => never { + return ((ctx: { box: Record }, dest: string) => { + mkdirSync(dest, { recursive: true, mode: 0o700 }); + calls.push(`${ctx.box.COMPOSE_PROJECT_NAME}:${dest}`); + }) as never; +} + +export function removeProject(project: string): void { + const ids = docker(['ps', '-aq', '--filter', `label=com.docker.compose.project=${project}`]) + .stdout.split(/\s+/) + .filter(Boolean); + if (ids.length) docker(['rm', '-f', ...ids]); + const volumes = docker([ + 'volume', + 'ls', + '-q', + '--filter', + `label=com.docker.compose.project=${project}`, + ]) + .stdout.split(/\s+/) + .filter(Boolean); + if (volumes.length) docker(['volume', 'rm', '-f', ...volumes]); + docker(['network', 'rm', `${project}_default`]); +} diff --git a/scripts/selfhost/live/legacy-adoption.live.test.ts b/scripts/selfhost/live/legacy-adoption.live.test.ts new file mode 100644 index 0000000000..089265d128 --- /dev/null +++ b/scripts/selfhost/live/legacy-adoption.live.test.ts @@ -0,0 +1,289 @@ +/** + * Legacy adoption (legacy-adoption.ts) against real Docker: a pre-L24 style install under a fixed + * shared compose project is moved into its canonical project, after which the L24 upgrade + * preflight that refused it passes. Covers a kill in the middle of a volume copy, a second + * checkout sharing the project (refused, nothing changed) and a failed health verification + * (rolled back to the legacy project, data and .env unchanged). + */ +import { spawn } from 'node:child_process'; +import { existsSync, readFileSync, rmSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { expectedComposeProjectFor } from '../install-record.js'; +import { runLegacyAdoption } from '../legacy-adoption.js'; +import { ADOPTION_JOURNAL_FILE, readAdoptionJournal } from '../legacy-adoption-journal.js'; +import { helperName } from '../legacy-adoption-volumes.js'; +import { readPrivateJson } from '../secret-files.js'; +import type { BoxContext, UpgradeOptions } from '../upgrade-lib.js'; +import { assertRollbackReady } from '../upgrade-preflight.js'; +import { childEnv, REPO_ROOT, skipWithoutDocker } from './harness.js'; +import { + ALPINE, + containerOf, + createFixture, + docker, + dockerOk, + fakeBackup, + FakeGit, + type Fixture, + fixtureContext, + FROM, + projectHealth, + readVolumeFile, + removeProject, + seedData, + TO, +} from './legacy-adoption-fixture.js'; + +let fixture: Fixture; +let canonical: string; +let extraContainers: string[]; + +function volumesOf(project: string): string[] { + return docker(['volume', 'ls', '-q', '--filter', `label=com.docker.compose.project=${project}`]) + .stdout.split(/\s+/) + .filter(Boolean) + .sort(); +} + +function canonicalFor(f: Fixture): string { + const id = readPrivateJson(join(f.stateDir, 'platform-keys.json')).SAM_INSTALLATION_ID ?? ''; + return expectedComposeProjectFor({ SAM_DOMAIN: 'adopt.example.test' }, f.stateDir, id); +} + +describe.skipIf(skipWithoutDocker)('legacy compose adoption (real Docker)', () => { + beforeAll(() => { + dockerOk(['pull', '--quiet', ALPINE]); + }); + + beforeEach(() => { + for (const name of Object.keys(process.env)) + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + fixture = createFixture(); + canonical = canonicalFor(fixture); + extraContainers = []; + }); + + afterEach(() => { + vi.unstubAllEnvs(); + for (const id of extraContainers) docker(['rm', '-f', id]); + removeProject(canonical); + removeProject(fixture.legacyProject); + rmSync(fixture.root, { recursive: true, force: true }); + }); + + function adopt( + git: FakeGit, + overrides: Partial[1]> = {}, + logs: string[] = [] + ) { + return runLegacyAdoption(fixtureContext(fixture, git, logs), { + to: TO, + from: FROM, + checkHealth: projectHealth(fixture), + backup: fakeBackup([]), + upgrade: async () => {}, + legacyProject: fixture.legacyProject, + helperImage: ALPINE, + checkoutRoot: fixture.root, + ...overrides, + }); + } + + it('adopts a legacy install, keeps its data, and then passes the L24 upgrade preflight', async () => { + seedData(fixture); + const box = () => fixtureContext(fixture, new FakeGit()).box; + // The refusal that left pre-L24 installs without an upgrade path (main before this change). + expect(() => assertRollbackReady({ box: box(), stateDir: fixture.stateDir })).toThrow( + /missing installation compose creation receipt/ + ); + const backups: string[] = []; + const upgrades: { project?: string; to: string; head: string; legacyRunning: boolean }[] = []; + const git = new FakeGit(TO); + const legacyVolumes = volumesOf(fixture.legacyProject); + await adopt(git, { + backup: ((ctx: BoxContext, dest: string) => { + // The snapshot is taken from the live legacy stack, before anything moves. + expect(containerOf(fixture.legacyProject, 'celld')).not.toBe(''); + backups.push(`${ctx.box.COMPOSE_PROJECT_NAME}:${dest}`); + }) as never, + upgrade: async (ctx: BoxContext, opts: UpgradeOptions) => { + // The real L24 preflight, against the adopted install's receipts. + assertRollbackReady(ctx); + upgrades.push({ + project: ctx.box.COMPOSE_PROJECT_NAME, + to: opts.to, + head: git.head, + legacyRunning: containerOf(fixture.legacyProject, 'celld') !== '', + }); + }, + }); + + expect(backups).toEqual([expect.stringMatching(new RegExp(`^${fixture.legacyProject}:/`))]); + expect(upgrades).toEqual([{ project: canonical, to: TO, head: FROM, legacyRunning: false }]); + expect(readFileSync(fixture.envFile, 'utf8')).toBe( + `${fixture.envText}COMPOSE_PROJECT_NAME=${canonical}\n` + ); + expect(() => assertRollbackReady({ box: box(), stateDir: fixture.stateDir })).not.toThrow(); + expect(containerOf(canonical, 'celld')).not.toBe(''); + expect(readVolumeFile(`${canonical}_celld-data`, 'do/marker')).toBe('7103:7103:640\ndurable'); + expect(readVolumeFile(`${canonical}_caddy-data`, 'cert.pem')).toBe('0:0:600\ncert'); + expect( + dockerOk([ + 'run', + '--rm', + '-v', + `${canonical}_celld-data:/v:ro`, + ALPINE, + 'readlink', + '/v/do/link', + ]) + ).toBe('marker'); + // Legacy containers are gone; its volumes are kept until the operator removes them. + expect( + docker([ + 'ps', + '-aq', + '--filter', + `label=com.docker.compose.project=${fixture.legacyProject}`, + ]).stdout.trim() + ).toBe(''); + expect(volumesOf(fixture.legacyProject)).toEqual(legacyVolumes); + expect(readVolumeFile(`${fixture.legacyProject}_celld-data`, 'do/marker')).toContain('durable'); + expect(existsSync(join(fixture.stateDir, ADOPTION_JOURNAL_FILE))).toBe(false); + // A second run is refused: the install now has its receipt and uses the normal upgrade. + await expect(adopt(new FakeGit(TO))).rejects.toThrow( + /COMPOSE_PROJECT_NAME is .*use a normal upgrade/ + ); + }); + + it('refuses a legacy project that another checkout also uses, changing nothing', async () => { + seedData(fixture); + extraContainers.push( + dockerOk([ + 'run', + '-d', + '--label', + `com.docker.compose.project=${fixture.legacyProject}`, + '--label', + 'com.docker.compose.service=celld', + '--label', + 'com.docker.compose.project.working_dir=/srv/another-checkout/deploy/selfhost', + ALPINE, + 'sleep', + 'infinity', + ]) + ); + const git = new FakeGit(TO); + const backups: string[] = []; + await expect(adopt(git, { backup: fakeBackup(backups) })).rejects.toThrow( + /belongs to another checkout/ + ); + expect(backups).toEqual([]); + expect(readFileSync(fixture.envFile, 'utf8')).toBe(fixture.envText); + expect(containerOf(fixture.legacyProject, 'celld')).not.toBe(''); + expect(volumesOf(canonical)).toEqual([]); + expect(existsSync(join(fixture.stateDir, ADOPTION_JOURNAL_FILE))).toBe(false); + expect(git.head).toBe(TO); + + // Control: once the foreign container is gone, the same install is adopted. + docker(['rm', '-f', ...extraContainers]); + extraContainers = []; + await adopt(new FakeGit(TO)); + expect(containerOf(canonical, 'celld')).not.toBe(''); + }); + + it('rolls back to the legacy project when health verification fails', async () => { + seedData(fixture); + const legacyCelld = containerOf(fixture.legacyProject, 'celld'); + let calls = 0; + const real = projectHealth(fixture); + const upgrades: string[] = []; + const git = new FakeGit(TO); + await expect( + adopt(git, { + checkHealth: async () => (calls++ === 0 ? false : real()), + upgrade: async () => { + upgrades.push('called'); + }, + }) + ).rejects.toThrow(/not healthy under its canonical compose project/); + expect(calls).toBe(2); + expect(upgrades).toEqual([]); + expect(readFileSync(fixture.envFile, 'utf8')).toBe(fixture.envText); + expect(containerOf(fixture.legacyProject, 'celld')).toBe(legacyCelld); + expect(containerOf(canonical, 'celld')).toBe(''); + expect(volumesOf(canonical)).toEqual([]); + expect(readVolumeFile(`${fixture.legacyProject}_caddy-data`, 'cert.pem')).toBe('0:0:600\ncert'); + // The canonical celld ran, so the disposable legacy cache was emptied (the bucket is durable). + expect( + dockerOk([ + 'run', + '--rm', + '-v', + `${fixture.legacyProject}_celld-data:/v:ro`, + ALPINE, + 'ls', + '-A', + '/v', + ]) + ).toBe(''); + expect(existsSync(join(fixture.stateDir, ADOPTION_JOURNAL_FILE))).toBe(false); + expect(git.head).toBe(FROM); + }); + + it('resumes after the operator process is killed in the middle of a volume copy', async () => { + seedData(fixture, 4000, 256); + const child = spawn( + resolve(REPO_ROOT, 'node_modules/.bin/tsx'), + [resolve(import.meta.dirname, 'legacy-adoption-child.ts'), JSON.stringify(fixture)], + { cwd: REPO_ROOT, env: childEnv(), stdio: 'ignore', detached: true } + ); + const exited = new Promise((done) => child.on('exit', (code) => done(code))); + const helper = helperName(canonical, 'celld-data'); + let killedMidCopy = false; + const deadline = Date.now() + 90_000; + while (Date.now() < deadline && child.exitCode === null) { + const journal = existsSync(join(fixture.stateDir, ADOPTION_JOURNAL_FILE)) + ? readAdoptionJournal(fixture.stateDir) + : null; + const cache = journal?.volumes.find((v) => v.suffix === 'celld-data'); + const copying = docker(['ps', '-q', '--filter', `name=^${helper}$`]).stdout.trim() !== ''; + if (cache?.createdAt && !cache.digest && copying) { + process.kill(-(child.pid as number), 'SIGKILL'); + killedMidCopy = true; + break; + } + await new Promise((done) => setTimeout(done, 20)); + } + await exited; + expect(killedMidCopy).toBe(true); + const interrupted = readAdoptionJournal(fixture.stateDir); + expect(interrupted?.phase).toBe('stopped'); + expect(interrupted?.volumes.find((v) => v.suffix === 'celld-data')?.digest).toBeUndefined(); + + // The rerun (same command) removes the orphaned copy helper, recopies and completes. + const logs: string[] = []; + await adopt(new FakeGit(FROM), {}, logs); + expect(logs).toContain('resuming legacy adoption at phase stopped'); + expect(docker(['ps', '-aq', '--filter', `name=^${helper}$`]).stdout.trim()).toBe(''); + expect(readVolumeFile(`${canonical}_celld-data`, 'do/marker')).toBe('7103:7103:640\ndurable'); + const count = (volume: string) => + dockerOk([ + 'run', + '--rm', + '-v', + `${volume}:/v:ro`, + ALPINE, + 'sh', + '-c', + 'ls /v | wc -l; md5sum /v/blob | cut -d" " -f1', + ]); + expect(count(`${canonical}_celld-data`)).toBe(count(`${fixture.legacyProject}_celld-data`)); + expect(containerOf(canonical, 'celld')).not.toBe(''); + expect(existsSync(join(fixture.stateDir, ADOPTION_JOURNAL_FILE))).toBe(false); + }); +}); diff --git a/scripts/selfhost/upgrade.ts b/scripts/selfhost/upgrade.ts index 0a2eb82f2f..10c3d53096 100644 --- a/scripts/selfhost/upgrade.ts +++ b/scripts/selfhost/upgrade.ts @@ -5,11 +5,15 @@ * inputs changed, verify health and print how to roll back (upgrade-lib.ts). * * Every upgrade takes an encrypted snapshot and automatically restores it on failure. + * + * `--adopt-legacy --from ` first moves a pre-L24 install off the shared + * `sam-selfhost` Compose project (legacy-adoption.ts), then upgrades it the same way. */ import { join, resolve } from 'node:path'; import { parseArgs } from 'node:util'; import { celldPort, SELFHOST_DIR, waitForHealth } from './deploy-steps.js'; +import { runLegacyAdoption } from './legacy-adoption.js'; import { assertOperatorExecution } from './operator-only.js'; import { loadBox, runUpgrade } from './upgrade-lib.js'; import { runManualRollback } from './upgrade-rollback.js'; @@ -26,6 +30,9 @@ const { values } = parseArgs({ 'rollback-from': { type: 'string' }, rebuild: { type: 'string', multiple: true }, 'encryption-key-file': { type: 'string' }, + 'adopt-legacy': { type: 'boolean', default: false }, + from: { type: 'string' }, + 'adoption-backup-to': { type: 'string' }, }, }); if (!values.to) throw new Error('--to is required (a tag, branch or commit)'); @@ -47,7 +54,23 @@ const checkHealth = async () => { } }; -if (values['rollback-from']) { +if (values['adopt-legacy'] && values['rollback-from']) + throw new Error('--adopt-legacy and --rollback-from cannot be combined'); +if (!values['adopt-legacy'] && (values.from || values['adoption-backup-to'])) + throw new Error('--from and --adoption-backup-to are only used with --adopt-legacy'); + +if (values['adopt-legacy']) { + if (!values.from) throw new Error('--adopt-legacy needs --from '); + if (values.rebuild?.length) throw new Error('--rebuild is only used with --rollback-from'); + await runLegacyAdoption(ctx, { + to: values.to, + from: values.from, + checkHealth, + upgrade: runUpgrade, + ...(values['adoption-backup-to'] ? { backupDir: resolve(values['adoption-backup-to']) } : {}), + ...(values['backup-to'] ? { upgradeBackupDir: resolve(values['backup-to']) } : {}), + }); +} else if (values['rollback-from']) { await runManualRollback(ctx, { from: values.to, backupDir: resolve(values['rollback-from']), From 087ae2b9bd813db64bfe0b6e65d5c7c12ee7b26b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 06:22:25 +0000 Subject: [PATCH 03/10] fix(selfhost): address legacy adoption review findings - A failed rollback keeps its journal and .env copy (the outer catch no longer clears them). - Rollback copies the canonical celld cache back over the legacy cache instead of emptying it, so nothing celld kept locally is lost. - A canonical volume created before its CreatedAt was journaled is re-adopted by its random adoption-id label instead of dead-ending the resume. - Stricter journal validation, refusal of an orphaned .env copy and of missing compose labels, and a correct path-containment check. - README: preconditions, flag rules, phases, checkout position after refusal versus rollback, and failed-rollback handling. - Tests: argument guards (no docker call on refusal), resume after a kill past the .env switch followed by a failed verify, and the cache copy-back. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 86 +++++++++++------ scripts/selfhost/legacy-adoption-inventory.ts | 10 +- scripts/selfhost/legacy-adoption-journal.ts | 6 ++ scripts/selfhost/legacy-adoption-volumes.ts | 19 +--- scripts/selfhost/legacy-adoption.test.ts | 83 ++++++++++++++++- scripts/selfhost/legacy-adoption.ts | 64 ++++++++----- .../selfhost/live/legacy-adoption-child.ts | 8 +- .../live/legacy-adoption.live.test.ts | 92 +++++++++++++++---- ...-11-20-selfhost-legacy-compose-adoption.md | 25 ++--- 9 files changed, 291 insertions(+), 102 deletions(-) diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index e26a21bfc1..ebb9730393 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -241,7 +241,7 @@ including `selfhost-hosted-git-v1` when present in that checkout, participate in (`scripts/selfhost/upgrade-migrations.ts:installedMigrations`, `assertMigrationProgression`). The command requires a clean tracked checkout and an installation-specific Compose project with -creation receipts. It checks out the target, runs `deploy --init`, rebuilds changed local images, +creation receipts (an older `sam-selfhost` install first needs `--adopt-legacy`, below). It checks out the target, runs `deploy --init`, rebuilds changed local images, restarts Compose when its inputs changed, deploys and checks health. Failure automatically restores the encrypted snapshot and previous code/dependencies before starting the previous version. The recovery checks the original installation, bucket, state and Compose ownership before removing @@ -295,7 +295,8 @@ install to its installation-specific project with legacy adoption (below) first. Installs created before `pnpm selfhost:upgrade` gained snapshots run under the fixed Compose project `sam-selfhost` and have no compose creation receipt, so a plain upgrade refuses them. Their own checkout also still holds the old upgrade tool. Check out the new SAM ref, then let its tool -adopt the install and upgrade it in one command; `--from` is the full commit the stack runs now: +adopt the install and upgrade it in one command. `--from` is the full 40-character commit the +stack runs now, and `--to` must resolve to the checked-out ref: ```sh git fetch origin && git checkout --detach && pnpm install --frozen-lockfile @@ -303,36 +304,65 @@ pnpm selfhost:upgrade --adopt-legacy --from --to ` next to the state directory). `--backup-to` applies to the +upgrade that follows. `--from` and `--adoption-backup-to` require `--adopt-legacy`, which cannot +be combined with `--rollback-from` or `--rebuild`. The checkout must be clean for tracked files. +The shell must not set `COMPOSE_PROJECT_NAME`, and the box `.env` must leave it unset or set it to +`sam-selfhost`. An install that already has its compose creation receipt is refused: use the plain +upgrade. + The running stack is not touched by the checkout. Adoption changes no SAM code and deploys nothing (`scripts/selfhost/legacy-adoption.ts:runLegacyAdoption`): 1. It checks out `--from` again, so the compose files and bind mounts match the running stack. -2. It proves ownership (`legacy-adoption-inventory.ts:proveLegacyOwnership`): every container of - the `sam-selfhost` project carries this checkout's compose directory, compose files and `.env`; - bind mounts stay inside this checkout or its state directory; each project volume is used only - by those containers; each container's config hash equals `--from`'s compose configuration; and - the canonical project is empty. Another checkout on the same host using `sam-selfhost`, or a - wrong `--from`, refuses before any change. A shell `COMPOSE_PROJECT_NAME` also refuses. -3. It takes the encrypted backup (`--adoption-backup-to`, default - `backups/pre-adoption-`) from the live legacy stack. -4. It stops the legacy stack and copies each volume into `_` with the locally - built egress-fence image (no network, labelled with a random adoption id), verified by a digest of - every path's type, owner and mode and every file's content. -5. It writes `COMPOSE_PROJECT_NAME=` into `.env` (every other byte kept), starts the - same version under that project and checks health. It then writes the installation and - compose-project creation receipts and removes the stopped legacy containers. -6. It runs the normal upgrade from `--from` to the target, with its own fresh snapshot - (`--backup-to`), automatic rollback and printed rollback command. - -Each step is journaled in `.state/legacy-adoption.json`, beside a private copy of the original -`.env`. If the process is killed, check out the target ref again and rerun the identical command: -it resumes at the recorded step, removes any copy helper the killed run left and recopies an -unfinished volume from scratch. If adoption fails or the new project is unhealthy, it rolls back -to `sam-selfhost`: it removes the canonical containers and the volumes it created, restores `.env` -byte for byte and restarts the legacy stack. The legacy volumes are only read, except that the -disposable celld cache is emptied when the new celld already ran, because the fleet bucket may then -be newer than that cache. Adoption never restores the bucket: the same deployed version kept -writing it. After a rollback the checkout stays at `--from`, which matches the running stack. +2. It proves ownership (`legacy-adoption-inventory.ts:proveLegacyOwnership`): + - every container of the `sam-selfhost` project carries this checkout's compose directory, + compose files and `.env`; a missing label refuses; + - bind mounts stay inside this checkout or its state directory; + - each project volume is used only by those containers; + - each container's config hash equals `--from`'s compose configuration; + - there is exactly one running celld; + - the canonical project is empty. + + Another checkout on the same host using `sam-selfhost`, or a wrong `--from`, refuses before + any change. + +3. It takes the encrypted backup from the live legacy stack. +4. It stops the legacy stack. It copies each volume into `_` with the + `sam-selfhost-egress-fence:local` image the legacy deploy already built. Adoption builds no + image. The helper runs with no network, all capabilities dropped except the file-ownership + ones a faithful copy needs, and a label carrying a random adoption id. Each copy is verified by + a digest of every path's type, owner and mode and every file's content. +5. It writes `COMPOSE_PROJECT_NAME=` into `.env`, keeping every other byte, then starts + the same version under that project and checks health. After health it writes the installation + and compose-project creation receipts and removes the stopped legacy containers. +6. It runs the normal upgrade from `--from` to the target, with its own fresh snapshot, automatic + rollback and printed rollback command. + +Each step is journaled (phases `proving`, `backed-up`, `stopped`, `switched`, `adopted`) in +`legacy-adoption.json` in the state directory, beside `legacy-adoption.env`, a private copy of the +original `.env`. Both are removed when the run succeeds or rolls back completely. If the process is +killed, check out the target ref again and rerun the identical command: + +- it resumes at the recorded step; +- it removes any helper container the killed run left (only those with its adoption id); +- it recopies an unfinished volume from scratch; +- a backup interrupted mid-way is kept and a new one is taken. + +A refusal or failure before the legacy stack stopped returns the checkout to the target and +discards the journal. A later failure, or an unhealthy new project, rolls back to `sam-selfhost`: + +- it removes the canonical containers and the volumes it created; +- if the new celld ran, it first copies the new project's celld cache back over the legacy one, so + nothing celld kept locally is lost; +- it restores `.env` byte for byte and restarts the legacy stack. + +The other legacy volumes are only read. Adoption never restores the bucket: the same deployed +version kept writing it. After such a rollback the checkout stays at `--from`, which matches the +running stack. If the rollback itself fails, the journal, the `.env` copy and the legacy volumes +are kept. Inspect the stack (`docker compose -p sam-selfhost ps`) before rerunning, and do not +delete those files to get past the error. If the upgrade step fails, its automatic rollback restores `--from` under the adopted project; the adoption stands and its journal remains. Check out the target and rerun the same command to retry diff --git a/scripts/selfhost/legacy-adoption-inventory.ts b/scripts/selfhost/legacy-adoption-inventory.ts index bb4b9bd197..c320208e24 100644 --- a/scripts/selfhost/legacy-adoption-inventory.ts +++ b/scripts/selfhost/legacy-adoption-inventory.ts @@ -69,7 +69,7 @@ function real(path: string): string { function inside(root: string, path: string): boolean { const rel = relative(root, path); - return rel === '' || (!rel.startsWith('..') && !rel.startsWith('/')); + return rel === '' || (rel !== '..' && !rel.startsWith('../') && !rel.startsWith('/')); } /** Container IDs carrying `label`, all states. */ @@ -151,6 +151,14 @@ export function proveLegacyOwnership( const labels = item.Config?.Labels ?? {}; const label = (name: string) => (typeof labels[name] === 'string' ? labels[name] : ''); if (label(PROJECT_LABEL) !== opts.legacyProject) refuse(`container ${id} changed project`); + if ( + !label('com.docker.compose.project.working_dir') || + !label('com.docker.compose.project.config_files') || + !label('com.docker.compose.project.environment_file') + ) + refuse( + `container ${id.slice(0, 12)} of project ${opts.legacyProject} belongs to another checkout, compose file set or .env (labels missing)` + ); const files = label('com.docker.compose.project.config_files') .split(',') .filter(Boolean) diff --git a/scripts/selfhost/legacy-adoption-journal.ts b/scripts/selfhost/legacy-adoption-journal.ts index 613e3c1ba3..8f75aadad9 100644 --- a/scripts/selfhost/legacy-adoption-journal.ts +++ b/scripts/selfhost/legacy-adoption-journal.ts @@ -62,11 +62,15 @@ export function phaseAtLeast(journal: AdoptionJournal, phase: AdoptionPhase): bo return ADOPTION_PHASES.indexOf(journal.phase) >= ADOPTION_PHASES.indexOf(phase); } +const PROJECT = /^[a-z0-9][a-z0-9_-]*$/; +const SUFFIX = /^[a-z0-9][a-z0-9_.-]*$/; + function validVolume(value: unknown, legacyProject: string, canonicalProject: string): boolean { if (!value || typeof value !== 'object') return false; const v = value as Record; return ( typeof v.suffix === 'string' && + SUFFIX.test(v.suffix) && v.legacy === `${legacyProject}_${v.suffix}` && v.canonical === `${canonicalProject}_${v.suffix}` && (v.createdAt === undefined || typeof v.createdAt === 'string') && @@ -98,7 +102,9 @@ export function readAdoptionJournal(stateDir: string): AdoptionJournal | null { typeof j.to !== 'string' || !SHA.test(j.to) || typeof j.legacyProject !== 'string' || + !PROJECT.test(j.legacyProject) || typeof j.canonicalProject !== 'string' || + !/^sam-selfhost-[a-f0-9]{12}$/.test(j.canonicalProject) || j.legacyProject === j.canonicalProject || typeof j.installationId !== 'string' || !/^[a-f0-9]{32}$/.test(j.installationId) || diff --git a/scripts/selfhost/legacy-adoption-volumes.ts b/scripts/selfhost/legacy-adoption-volumes.ts index f0a37db155..c79dfd6bcd 100644 --- a/scripts/selfhost/legacy-adoption-volumes.ts +++ b/scripts/selfhost/legacy-adoption-volumes.ts @@ -27,8 +27,6 @@ const DIGEST_SCRIPT = /** Empty the destination first: a retry after a kill must not merge with a partial copy. */ const COPY_SCRIPT = 'set -eu; find /to -mindepth 1 -delete; cp -a /from/. /to/'; -const EMPTY_SCRIPT = 'set -eu; find /cache -mindepth 1 -delete'; - export function helperName(canonicalProject: string, suffix: string): string { return `${canonicalProject}-legacy-adoption-${suffix}`; } @@ -40,7 +38,8 @@ export function helperNames(canonicalProject: string, suffixes: readonly string[ const name = helperName(canonicalProject, suffix); return [name, `${name}-digest`]; }), - helperName(canonicalProject, 'cache-reset'), + helperName(canonicalProject, 'cache-return'), + `${helperName(canonicalProject, 'cache-return')}-digest`, ]; } @@ -223,20 +222,6 @@ export function copyVolume( return copy; } -/** celld-data is a disposable cache; a stale one is emptied before the legacy celld restarts. */ -export function emptyVolume( - ctx: Pick, - helper: Helper, - name: string, - container: string -): void { - removeStaleHelper(ctx, helper, container); - check( - ctx.run('docker', helperArgs(helper, container, [`${name}:/cache`], [EMPTY_SCRIPT])), - 'empty stale legacy cache' - ); -} - export function removeVolume(ctx: Pick, name: string): void { check(ctx.run('docker', ['volume', 'rm', name]), 'remove canonical adoption volume'); } diff --git a/scripts/selfhost/legacy-adoption.test.ts b/scripts/selfhost/legacy-adoption.test.ts index c2f8d48e49..250c989643 100644 --- a/scripts/selfhost/legacy-adoption.test.ts +++ b/scripts/selfhost/legacy-adoption.test.ts @@ -6,8 +6,9 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { runLegacyAdoption } from './legacy-adoption.js'; import { proveLegacyOwnership } from './legacy-adoption-inventory.js'; import { ADOPTION_JOURNAL_FILE, @@ -192,3 +193,83 @@ describe('proveLegacyOwnership', () => { expect(prove).toThrow(/volume of another project/); }); }); + +describe('runLegacyAdoption argument guards', () => { + const FROM = 'f'.repeat(40); + const TO = 'e'.repeat(40); + let head: string; + let dirty: boolean; + let docker: string[]; + + const ctx = () => { + const dir = join(root, 'deploy/selfhost'); + writeFileSync(join(dir, '.env'), 'SAM_DOMAIN=x.test\n', { mode: 0o600 }); + return { + box: { SAM_DOMAIN: 'x.test' } as Record, + envFile: join(dir, '.env'), + stateDir: state(), + composeFiles: [join(dir, 'docker-compose.yml')], + log: () => {}, + run: (command: string, args: string[]): RunResult => { + const ok = (stdout = '') => ({ status: 0, stdout, stderr: '' }); + if (command === 'docker') { + docker.push(args.join(' ')); + return { status: 1, stdout: '', stderr: 'docker must not run' }; + } + if (args[0] === 'status') return ok(dirty ? ' M x.ts' : ''); + if (args[0] === 'rev-parse' && args[1] === 'HEAD') return ok(head); + if (args[0] === 'rev-parse') return ok(args[2]?.startsWith('main') ? TO : 'c'.repeat(40)); + return ok(); + }, + }; + }; + const adopt = (overrides: { from?: string; to?: string } = {}) => + runLegacyAdoption(ctx(), { + from: overrides.from ?? FROM, + to: overrides.to ?? 'main', + checkHealth: async () => true, + upgrade: async () => {}, + }); + + beforeEach(() => { + for (const name of Object.keys(process.env)) + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + vi.stubEnv('COMPOSE_PROJECT_NAME', undefined); + head = TO; + dirty = false; + docker = []; + }); + afterEach(() => { + vi.unstubAllEnvs(); + // Every refusal happens before any container, volume or compose command. + expect(docker).toEqual([]); + }); + + it('refuses an abbreviated --from', async () => { + await expect(adopt({ from: 'f'.repeat(12) })).rejects.toThrow(/full 40-character/); + }); + it('refuses a shell COMPOSE_PROJECT_NAME', async () => { + vi.stubEnv('COMPOSE_PROJECT_NAME', 'sam-selfhost'); + await expect(adopt()).rejects.toThrow(/Unset COMPOSE_PROJECT_NAME/); + }); + it('refuses a dirty checkout', async () => { + dirty = true; + await expect(adopt()).rejects.toThrow(/uncommitted changes/); + }); + it('refuses to run from the deployed commit itself', async () => { + head = FROM; + await expect(adopt()).rejects.toThrow(/check out the target SAM ref first/); + }); + it('refuses a --to that is not the checked-out target', async () => { + await expect(adopt({ to: 'v2026.11.19' })).rejects.toThrow(/check out v2026.11.19 first/); + }); + it('refuses to resume an adoption with a different --from', async () => { + writeAdoptionJournal(state(), journal()); + await expect(adopt({ from: 'a'.repeat(40) })).rejects.toThrow(/pass the same --from/); + }); + it('refuses an orphaned .env copy left without its journal', async () => { + writeFileSync(join(state(), 'legacy-adoption.env'), 'A=1\n', { mode: 0o600 }); + await expect(adopt()).rejects.toThrow(/exists without its journal/); + }); +}); diff --git a/scripts/selfhost/legacy-adoption.ts b/scripts/selfhost/legacy-adoption.ts index 2d4daa2a12..2ca17ed0ca 100644 --- a/scripts/selfhost/legacy-adoption.ts +++ b/scripts/selfhost/legacy-adoption.ts @@ -37,7 +37,6 @@ import { copyVolume, createCanonicalVolume, DEFAULT_ADOPTION_HELPER_IMAGE, - emptyVolume, type Helper, helperName, helperNames, @@ -126,6 +125,10 @@ function startJournal(ctx: BoxContext, opts: AdoptionOptions, to: string): Adopt throw new Error( `Legacy adoption refused: COMPOSE_PROJECT_NAME is ${named}, not the legacy ${legacyProject}; use a normal upgrade` ); + if (existsSync(join(ctx.stateDir, ADOPTION_ENV_FILE))) + throw new Error( + `Legacy adoption refused: ${ctx.stateDir}/${ADOPTION_ENV_FILE} exists without its journal; inspect it (it is a copy of an earlier .env) and remove it` + ); const installationId = installationIdOf(ctx.stateDir); const box = { ...ctx.box }; delete box.COMPOSE_PROJECT_NAME; @@ -167,15 +170,17 @@ function assertCanonicalClear(ctx: BoxContext, journal: AdoptionJournal): void { .filter(Boolean); for (const name of listed) { const owned = journal.volumes.find((v) => v.canonical === name); - if (!owned?.createdAt) + if (!owned) throw new Error(`Legacy adoption refused: ${name} exists and is not this adoption's copy`); - ownedCanonicalVolume( + // Labelled with this journal's random adoption id; a kill can precede recording its CreatedAt. + const volume = ownedCanonicalVolume( ctx, journal.canonicalProject, owned.suffix, journal.adoptionId, owned.createdAt ); + if (volume && !owned.createdAt) owned.createdAt = volume.createdAt; } } @@ -252,7 +257,8 @@ async function adopt(ctx: BoxContext, opts: AdoptionOptions, journal: AdoptionJo journal.adoptionId, volume.createdAt ); - if (!existing) { + if (existing) volume.createdAt = existing.createdAt; + else { volume.createdAt = createCanonicalVolume( ctx, journal.canonicalProject, @@ -305,43 +311,55 @@ function removeLegacyContainers(ctx: BoxContext, journal: AdoptionJournal): void if (stale.length) check(ctx.run('docker', ['rm', ...stale]), 'remove stopped legacy containers'); } -/** Back to the legacy project; its volumes were only read, except the disposable cache. */ +/** Rollback could not restore the legacy stack: its journal and env copy must be kept. */ +class RollbackIncomplete extends Error {} + +/** + * Back to the legacy project. Its volumes were only read, except the celld cache: when the + * canonical celld ran, its cache is the newest local state, so it is copied back over the legacy + * cache (nothing celld kept locally is lost, whatever its flush semantics) before the canonical + * volumes are removed. + */ async function rollbackToLegacy(ctx: BoxContext, opts: AdoptionOptions, journal: AdoptionJournal) { ctx.log('legacy adoption failed; restoring the legacy compose project'); const legacy = withProject(ctx, journal.legacyProject); const canonical = withProject(ctx, journal.canonicalProject); const helper = helperOf(opts, journal); try { + for (const name of helperNames( + journal.canonicalProject, + journal.volumes.map((v) => v.suffix) + )) + removeStaleHelper(ctx, helper, name); if (journal.canonicalStarted) compose(canonical, ['down', '--remove-orphans'], 'stop canonical stack'); - for (const volume of journal.volumes) { - removeStaleHelper(ctx, helper, helperName(journal.canonicalProject, volume.suffix)); - removeStaleHelper( - ctx, - helper, - `${helperName(journal.canonicalProject, volume.suffix)}-digest` - ); - if (!volume.createdAt) continue; - const owned = ownedCanonicalVolume( + const owned = journal.volumes.map((volume) => ({ + volume, + present: ownedCanonicalVolume( ctx, journal.canonicalProject, volume.suffix, journal.adoptionId, volume.createdAt + ), + })); + const cache = owned.find((o) => o.volume.suffix === 'celld-data'); + if (journal.canonicalStarted && cache?.present) + copyVolume( + ctx, + helper, + cache.present.name, + cache.volume.legacy, + helperName(journal.canonicalProject, 'cache-return') ); - if (owned) removeVolume(ctx, owned.name); - } + for (const { present } of owned) if (present) removeVolume(ctx, present.name); if (phaseAtLeast(journal, 'switched') || existsSync(join(ctx.stateDir, ADOPTION_ENV_FILE))) replacePrivateFile(ctx.envFile, readOriginalEnv(ctx.stateDir)); - const cache = journal.volumes.find((v) => v.suffix === 'celld-data'); - // The canonical celld may have written newer data to the bucket than this cache holds. - if (journal.canonicalStarted && cache) - emptyVolume(ctx, helper, cache.legacy, helperName(journal.canonicalProject, 'cache-reset')); compose(legacy, ['up', '-d'], 'restart legacy stack'); if (!(await opts.checkHealth())) throw new Error('legacy stack is not healthy'); } catch { - throw new Error( - `legacy adoption failed and rollback did not complete; keep ${ctx.stateDir}/legacy-adoption.json and the legacy volumes, then inspect the stack` + throw new RollbackIncomplete( + `legacy adoption failed and rollback did not complete; keep ${ctx.stateDir}/legacy-adoption.json, its legacy-adoption.env and the legacy volumes, then inspect the stack` ); } clearAdoptionJournal(ctx.stateDir); @@ -388,7 +406,7 @@ export async function runLegacyAdoption(ctx: BoxContext, opts: AdoptionOptions): try { await adopt(ctx, opts, journal); } catch (error) { - if (!phaseAtLeast(journal, 'stopped')) { + if (!(error instanceof RollbackIncomplete) && !phaseAtLeast(journal, 'stopped')) { // Nothing moved yet: return the operator's checkout and forget the attempt. clearAdoptionJournal(ctx.stateDir); git(ctx, ['checkout', '--detach', journal.to], 'restore target checkout'); diff --git a/scripts/selfhost/live/legacy-adoption-child.ts b/scripts/selfhost/live/legacy-adoption-child.ts index 226dbaee82..6a7bc489b9 100644 --- a/scripts/selfhost/live/legacy-adoption-child.ts +++ b/scripts/selfhost/live/legacy-adoption-child.ts @@ -31,12 +31,18 @@ if ( ) throw new Error('legacy-adoption-child: invalid fixture argument'); const fixture = parsed as Fixture; +const delay = Number(process.argv[3] ?? '0'); +const health = projectHealth(fixture); const git = new FakeGit(TO); const ctx = fixtureContext(fixture, git, []); await runLegacyAdoption(ctx, { to: TO, from: FROM, - checkHealth: projectHealth(fixture), + checkHealth: async () => { + // A slow health check gives the test a window to kill the run after the .env switch. + await new Promise((done) => setTimeout(done, delay)); + return health(); + }, backup: fakeBackup([]), upgrade: async () => {}, legacyProject: fixture.legacyProject, diff --git a/scripts/selfhost/live/legacy-adoption.live.test.ts b/scripts/selfhost/live/legacy-adoption.live.test.ts index 089265d128..a385e5759f 100644 --- a/scripts/selfhost/live/legacy-adoption.live.test.ts +++ b/scripts/selfhost/live/legacy-adoption.live.test.ts @@ -53,6 +53,19 @@ function canonicalFor(f: Fixture): string { return expectedComposeProjectFor({ SAM_DOMAIN: 'adopt.example.test' }, f.stateDir, id); } +/** One adoption in its own process group, so the test can SIGKILL it and any child. */ +function spawnChild(f: Fixture, healthDelayMs: number) { + return spawn( + resolve(REPO_ROOT, 'node_modules/.bin/tsx'), + [ + resolve(import.meta.dirname, 'legacy-adoption-child.ts'), + JSON.stringify(f), + String(healthDelayMs), + ], + { cwd: REPO_ROOT, env: childEnv(), stdio: 'ignore', detached: true } + ); +} + describe.skipIf(skipWithoutDocker)('legacy compose adoption (real Docker)', () => { beforeAll(() => { dockerOk(['pull', '--quiet', ALPINE]); @@ -205,7 +218,18 @@ describe.skipIf(skipWithoutDocker)('legacy compose adoption (real Docker)', () = const git = new FakeGit(TO); await expect( adopt(git, { - checkHealth: async () => (calls++ === 0 ? false : real()), + checkHealth: async () => { + if (calls++ > 0) return real(); + // The canonical celld writes before verification fails: that state must not be lost. + dockerOk([ + 'exec', + containerOf(canonical, 'celld'), + 'sh', + '-c', + 'echo newer > /var/lib/celld/do/after', + ]); + return false; + }, upgrade: async () => { upgrades.push('called'); }, @@ -218,30 +242,60 @@ describe.skipIf(skipWithoutDocker)('legacy compose adoption (real Docker)', () = expect(containerOf(canonical, 'celld')).toBe(''); expect(volumesOf(canonical)).toEqual([]); expect(readVolumeFile(`${fixture.legacyProject}_caddy-data`, 'cert.pem')).toBe('0:0:600\ncert'); - // The canonical celld ran, so the disposable legacy cache was emptied (the bucket is durable). - expect( - dockerOk([ - 'run', - '--rm', - '-v', - `${fixture.legacyProject}_celld-data:/v:ro`, - ALPINE, - 'ls', - '-A', - '/v', - ]) - ).toBe(''); + // The canonical cache (the newest local celld state) was carried back to the legacy cache. + expect(readVolumeFile(`${fixture.legacyProject}_celld-data`, 'do/marker')).toBe( + '7103:7103:640\ndurable' + ); + expect(readVolumeFile(`${fixture.legacyProject}_celld-data`, 'do/after')).toContain('newer'); expect(existsSync(join(fixture.stateDir, ADOPTION_JOURNAL_FILE))).toBe(false); expect(git.head).toBe(FROM); }); + it('resumes after a kill past the .env switch, then rolls back cleanly on a failed verify', async () => { + seedData(fixture); + const child = spawnChild(fixture, 60_000); + const exited = new Promise((done) => child.on('exit', done)); + let killed = false; + const deadline = Date.now() + 90_000; + while (Date.now() < deadline && child.exitCode === null) { + const journal = existsSync(join(fixture.stateDir, ADOPTION_JOURNAL_FILE)) + ? readAdoptionJournal(fixture.stateDir) + : null; + if ( + journal?.phase === 'switched' && + journal.canonicalStarted && + containerOf(canonical, 'celld') + ) { + process.kill(-(child.pid as number), 'SIGKILL'); + killed = true; + break; + } + await new Promise((done) => setTimeout(done, 50)); + } + await exited; + expect(killed).toBe(true); + expect(readFileSync(fixture.envFile, 'utf8')).toContain(`COMPOSE_PROJECT_NAME=${canonical}`); + + let calls = 0; + const real = projectHealth(fixture); + const logs: string[] = []; + await expect( + adopt(new FakeGit(FROM), { checkHealth: async () => (calls++ === 0 ? false : real()) }, logs) + ).rejects.toThrow(/not healthy/); + expect(logs).toContain('resuming legacy adoption at phase switched'); + expect(readFileSync(fixture.envFile, 'utf8')).toBe(fixture.envText); + expect(containerOf(fixture.legacyProject, 'celld')).not.toBe(''); + expect(containerOf(canonical, 'celld')).toBe(''); + expect(volumesOf(canonical)).toEqual([]); + expect(readVolumeFile(`${fixture.legacyProject}_celld-data`, 'do/marker')).toBe( + '7103:7103:640\ndurable' + ); + expect(existsSync(join(fixture.stateDir, ADOPTION_JOURNAL_FILE))).toBe(false); + }); + it('resumes after the operator process is killed in the middle of a volume copy', async () => { seedData(fixture, 4000, 256); - const child = spawn( - resolve(REPO_ROOT, 'node_modules/.bin/tsx'), - [resolve(import.meta.dirname, 'legacy-adoption-child.ts'), JSON.stringify(fixture)], - { cwd: REPO_ROOT, env: childEnv(), stdio: 'ignore', detached: true } - ); + const child = spawnChild(fixture, 0); const exited = new Promise((done) => child.on('exit', (code) => done(code))); const helper = helperName(canonical, 'celld-data'); let killedMidCopy = false; diff --git a/tasks/active/2026-11-20-selfhost-legacy-compose-adoption.md b/tasks/active/2026-11-20-selfhost-legacy-compose-adoption.md index 36f809f457..7579d8a9ca 100644 --- a/tasks/active/2026-11-20-selfhost-legacy-compose-adoption.md +++ b/tasks/active/2026-11-20-selfhost-legacy-compose-adoption.md @@ -32,27 +32,28 @@ every install created before L24 (#2918) cannot upgrade to main: ## Checklist -- [ ] `--adopt-legacy --from ` on `selfhost:upgrade` (upgrade.ts), operator-only -- [ ] Ownership proof: every container in the legacy project is labelled with this checkout's +- [x] `--adopt-legacy --from ` on `selfhost:upgrade` (upgrade.ts), operator-only +- [x] Ownership proof: every container in the legacy project is labelled with this checkout's working dir, compose files and env file; bind mounts sit inside the checkout or state dir; each legacy volume is mounted only by proven containers; the running config hash equals `--from`'s compose config; there is exactly one running celld; the canonical project is empty (or exactly what this journal created). Anything else refuses. -- [ ] Backup first (runBackup against the explicit legacy project) before any change -- [ ] Durable private journal (`.state/legacy-adoption.json`) plus a private copy of the original +- [x] Backup first (runBackup against the explicit legacy project) before any change +- [x] Durable private journal (`.state/legacy-adoption.json`) plus a private copy of the original .env; resume after a kill at every phase; a killed copy helper is removed before re-copy -- [ ] Copy each volume into a labelled canonical volume; verify by a content, mode and owner digest -- [ ] Set `COMPOSE_PROJECT_NAME`, start the canonical project, verify health, write receipts via +- [x] Copy each volume into a labelled canonical volume; verify by a content, mode and owner digest +- [x] Set `COMPOSE_PROJECT_NAME`, start the canonical project, verify health, write receipts via `recordInstall`, remove the stopped legacy containers, keep the legacy volumes (print rm command) -- [ ] Failure or failed verify rolls back to the legacy project: canonical containers and owned - volumes removed, .env restored byte for byte, legacy cache emptied if canonical celld ran, +- [x] Failure or failed verify rolls back to the legacy project: canonical containers and owned + volumes removed, .env restored byte for byte, canonical celld cache copied back if it ran, legacy stack started and health-checked -- [ ] Chain into `runUpgrade` from `--from`; keep the journal until the upgrade succeeds -- [ ] README: legacy adoption procedure, resume and rollback behaviour -- [ ] Live real-Docker tests: adopt-then-upgrade (the L24 preflight passes afterwards), kill +- [x] Chain into `runUpgrade` from `--from`; keep the journal until the upgrade succeeds +- [x] README: legacy adoption procedure, resume and rollback behaviour +- [x] Live real-Docker tests: adopt-then-upgrade (the L24 preflight passes afterwards), kill mid-copy then resume, ambiguous-ownership refusal (another checkout on the same project), failed verify rolls back to legacy; plus unit tests for argument and journal validation -- [ ] Security review; box adoption plus smoke steps 1, 2 and 4 after merge +- [ ] Box adoption from the PR head BEFORE merge (staging gate, coordinator); after merge, the normal L24 upgrade to main plus the forced-verify rollback (smoke steps 1, 2 and 4) +- [x] Security review (security-auditor PASS: 3 MEDIUM and 4 LOW fixed in the second commit) ## Acceptance criteria From 80cce88eab3070eeabedc9294348fc98ef3f1992 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 06:23:41 +0000 Subject: [PATCH 04/10] fix(selfhost): log the cause when legacy adoption rollback fails Co-Authored-By: Claude Opus 5.5 --- scripts/selfhost/legacy-adoption.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/scripts/selfhost/legacy-adoption.ts b/scripts/selfhost/legacy-adoption.ts index 2ca17ed0ca..39a1867ed1 100644 --- a/scripts/selfhost/legacy-adoption.ts +++ b/scripts/selfhost/legacy-adoption.ts @@ -357,7 +357,11 @@ async function rollbackToLegacy(ctx: BoxContext, opts: AdoptionOptions, journal: replacePrivateFile(ctx.envFile, readOriginalEnv(ctx.stateDir)); compose(legacy, ['up', '-d'], 'restart legacy stack'); if (!(await opts.checkHealth())) throw new Error('legacy stack is not healthy'); - } catch { + } catch (rollbackError) { + // check() never relays tool output, so these messages carry no secrets. + ctx.log( + `rollback step failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}` + ); throw new RollbackIncomplete( `legacy adoption failed and rollback did not complete; keep ${ctx.stateDir}/legacy-adoption.json, its legacy-adoption.env and the legacy volumes, then inspect the stack` ); From f98892c1ffee42cf2d2abbe0d769d5915085bf04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 06:41:11 +0000 Subject: [PATCH 05/10] fix(selfhost): close legacy adoption kill windows found by Codex review - A killed rollback resumes as a rollback (journaled `rollingBack`), and the forward path refuses to start the canonical stack when a journaled copy is missing, instead of letting Compose recreate it empty. - The copy helper defaults to the digest-pinned Alpine base of the egress fence (a test keeps them equal), and it is pulled before any mutation: installs older than the fence never built a local image. - The chained upgrade marks the adoption journal inside its own completed-marker window (`completeUpgradeJournal` hook, success path only), so a kill after a successful upgrade never replays it. A target re-checkout makes HEAD useless as that evidence. - The legacy stop is journaled as an intent first, so a kill between the stop and the phase write resumes from the stopped stack instead of refusing it and discarding the journal. Each fix has a real-Docker or unit test proven discriminating by deleting its guard. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 20 +++- scripts/selfhost/legacy-adoption-journal.ts | 11 +- scripts/selfhost/legacy-adoption-volumes.ts | 14 ++- scripts/selfhost/legacy-adoption.test.ts | 50 +++++++++ scripts/selfhost/legacy-adoption.ts | 85 ++++++++++---- .../selfhost/live/legacy-adoption-child.ts | 3 +- .../live/legacy-adoption.live.test.ts | 105 +++++++++++++++++- scripts/selfhost/upgrade-journal.ts | 19 +++- scripts/selfhost/upgrade-lib.ts | 4 +- 9 files changed, 275 insertions(+), 36 deletions(-) diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index ebb9730393..ed70eeb0a5 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -329,11 +329,12 @@ nothing (`scripts/selfhost/legacy-adoption.ts:runLegacyAdoption`): any change. 3. It takes the encrypted backup from the live legacy stack. -4. It stops the legacy stack. It copies each volume into `_` with the - `sam-selfhost-egress-fence:local` image the legacy deploy already built. Adoption builds no - image. The helper runs with no network, all capabilities dropped except the file-ownership - ones a faithful copy needs, and a label carrying a random adoption id. Each copy is verified by - a digest of every path's type, owner and mode and every file's content. +4. It stops the legacy stack, journaling the intent first. It copies each volume into + `_` with a digest-pinned Alpine image, the egress fence's own base, which it + pulls before changing anything if the box does not have it. The helper runs with no network, + all capabilities dropped except the file-ownership ones a faithful copy needs, and a label + carrying a random adoption id. Each copy is verified by a digest of every path's type, owner and + mode and every file's content. 5. It writes `COMPOSE_PROJECT_NAME=` into `.env`, keeping every other byte, then starts the same version under that project and checks health. After health it writes the installation and compose-project creation receipts and removes the stopped legacy containers. @@ -348,11 +349,18 @@ killed, check out the target ref again and rerun the identical command: - it resumes at the recorded step; - it removes any helper container the killed run left (only those with its adoption id); - it recopies an unfinished volume from scratch; -- a backup interrupted mid-way is kept and a new one is taken. +- a backup interrupted mid-way is kept and a new one is taken; +- a stop that completed before its phase was journaled resumes from the stopped stack; +- a rollback that was interrupted is finished as a rollback, never resumed forward; +- an upgrade that already completed is not run again. + +The upgrade marks the adoption journal while its own completed marker is still durable, so a +re-checkout of the target cannot make a finished upgrade look unstarted. A refusal or failure before the legacy stack stopped returns the checkout to the target and discards the journal. A later failure, or an unhealthy new project, rolls back to `sam-selfhost`: +- it journals the rollback first, so a killed rollback is finished on the next run; - it removes the canonical containers and the volumes it created; - if the new celld ran, it first copies the new project's celld cache back over the legacy one, so nothing celld kept locally is lost; diff --git a/scripts/selfhost/legacy-adoption-journal.ts b/scripts/selfhost/legacy-adoption-journal.ts index 8f75aadad9..b953bbbf36 100644 --- a/scripts/selfhost/legacy-adoption-journal.ts +++ b/scripts/selfhost/legacy-adoption-journal.ts @@ -47,6 +47,12 @@ export interface AdoptionJournal { volumes: AdoptionVolume[]; /** Set before the canonical stack is first started: its celld may have written the bucket. */ canonicalStarted: boolean; + /** Set before `compose stop`: a kill after the stop must not look like an untouched stack. */ + stopRequested?: boolean; + /** Set before rollback starts: a killed rollback resumes as a rollback, never forward. */ + rollingBack?: boolean; + /** Set while the chained upgrade's completed marker is still durable (upgrade-journal.ts). */ + upgraded?: boolean; } const SHA = /^[a-f0-9]{40}$/; @@ -116,7 +122,10 @@ export function readAdoptionJournal(stateDir: string): AdoptionJournal | null { !j.volumes.every((v) => validVolume(v, j.legacyProject as string, j.canonicalProject as string) ) || - typeof j.canonicalStarted !== 'boolean' + typeof j.canonicalStarted !== 'boolean' || + !['stopRequested', 'rollingBack', 'upgraded'].every( + (key) => j[key] === undefined || typeof j[key] === 'boolean' + ) ) return invalid(path); return raw as AdoptionJournal; diff --git a/scripts/selfhost/legacy-adoption-volumes.ts b/scripts/selfhost/legacy-adoption-volumes.ts index c79dfd6bcd..a4ab723976 100644 --- a/scripts/selfhost/legacy-adoption-volumes.ts +++ b/scripts/selfhost/legacy-adoption-volumes.ts @@ -8,10 +8,18 @@ import { type BoxContext, check } from './backup-lib'; /** - * Alpine with busybox (sh, cp, find, stat, sha256sum), built locally on every box from - * deploy/selfhost/egress-fence (its celld-data-owner service already uses it on the cache volume). + * Digest-pinned Alpine (busybox: sh, cp, find, stat, sha256sum): the egress fence's own base + * (deploy/selfhost/egress-fence/Dockerfile, kept equal by a test). Installs older than the fence + * never built a local image, so the pinned base is pulled before adoption changes anything. */ -export const DEFAULT_ADOPTION_HELPER_IMAGE = 'sam-selfhost-egress-fence:local'; +export const DEFAULT_ADOPTION_HELPER_IMAGE = + 'alpine:3.22@sha256:49340b346798875b5592e5d420241f2f9cfba5f47e62ebb1446a1b34734e898f'; + +/** Present or pulled before any mutation, so a missing image cannot strand a stopped stack. */ +export function ensureHelperImage(ctx: Pick, image: string): void { + if (ctx.run('docker', ['image', 'inspect', '--format', '{{.Id}}', image]).status === 0) return; + check(ctx.run('docker', ['pull', '--quiet', image]), 'pull adoption helper image'); +} /** Marks a canonical volume this adoption created, with the journal's random adoption id. */ export const ADOPTION_LABEL = 'sam.selfhost.legacy-adoption'; diff --git a/scripts/selfhost/legacy-adoption.test.ts b/scripts/selfhost/legacy-adoption.test.ts index 250c989643..9446c54e5f 100644 --- a/scripts/selfhost/legacy-adoption.test.ts +++ b/scripts/selfhost/legacy-adoption.test.ts @@ -18,6 +18,8 @@ import { saveOriginalEnv, writeAdoptionJournal, } from './legacy-adoption-journal.js'; +import { DEFAULT_ADOPTION_HELPER_IMAGE, ensureHelperImage } from './legacy-adoption-volumes.js'; +import { completeUpgradeJournal, upgradeCompletedTo } from './upgrade-journal.js'; import type { RunResult } from './upgrade-lib.js'; let root: string; @@ -273,3 +275,51 @@ describe('runLegacyAdoption argument guards', () => { await expect(adopt()).rejects.toThrow(/exists without its journal/); }); }); + +describe('adoption helper image', () => { + it('is the egress fence base image, pinned by digest', () => { + const dockerfile = readFileSync(resolve('deploy/selfhost/egress-fence/Dockerfile'), 'utf8'); + const base = /^FROM\s+(\S+)/m.exec(dockerfile)?.[1]; + expect(DEFAULT_ADOPTION_HELPER_IMAGE).toBe(base); + expect(DEFAULT_ADOPTION_HELPER_IMAGE).toMatch(/@sha256:[a-f0-9]{64}$/); + }); + it('is pulled before any change when it is not present locally', () => { + const calls: string[] = []; + ensureHelperImage( + { + run: (_c, args) => { + calls.push(args.slice(0, 2).join(' ')); + return { status: args[0] === 'image' ? 1 : 0, stdout: '', stderr: '' }; + }, + }, + DEFAULT_ADOPTION_HELPER_IMAGE + ); + expect(calls).toEqual(['image inspect', 'pull --quiet']); + }); +}); + +describe('upgrade completion marker', () => { + it('is durable while the completion hook runs, then cleared', () => { + let seen = false; + completeUpgradeJournal( + state(), + { from: 'f'.repeat(40), to: 'e'.repeat(40), backupDir: '/b' }, + () => { + seen = upgradeCompletedTo(state(), 'e'.repeat(40)); + } + ); + expect(seen).toBe(true); + expect(upgradeCompletedTo(state(), 'e'.repeat(40))).toBe(false); + }); + it('does not count a recovery to the previous version as an upgrade', () => { + let seen = true; + completeUpgradeJournal( + state(), + { from: 'f'.repeat(40), to: 'f'.repeat(40), backupDir: '/b' }, + () => { + seen = upgradeCompletedTo(state(), 'f'.repeat(40)); + } + ); + expect(seen).toBe(false); + }); +}); diff --git a/scripts/selfhost/legacy-adoption.ts b/scripts/selfhost/legacy-adoption.ts index 39a1867ed1..1446fe480f 100644 --- a/scripts/selfhost/legacy-adoption.ts +++ b/scripts/selfhost/legacy-adoption.ts @@ -37,6 +37,7 @@ import { copyVolume, createCanonicalVolume, DEFAULT_ADOPTION_HELPER_IMAGE, + ensureHelperImage, type Helper, helperName, helperNames, @@ -46,7 +47,7 @@ import { } from './legacy-adoption-volumes'; import { assertOperatorExecution } from './operator-only'; import { readPrivateJson, replacePrivateFile } from './secret-files'; -import { UPGRADE_PENDING_FILE } from './upgrade-journal'; +import { readPendingFrom, UPGRADE_PENDING_FILE, upgradeCompletedTo } from './upgrade-journal'; import type { BoxContext, UpgradeOptions } from './upgrade-lib'; export interface AdoptionOptions { @@ -195,7 +196,7 @@ async function adopt(ctx: BoxContext, opts: AdoptionOptions, journal: AdoptionJo journal.volumes.map((v) => v.suffix) )) removeStaleHelper(ctx, helper, name); - const stopped = phaseAtLeast(journal, 'stopped'); + const stopped = phaseAtLeast(journal, 'stopped') || journal.stopRequested === true; const inventory = proveLegacyOwnership(legacy, { legacyProject: journal.legacyProject, checkoutRoot: opts.checkoutRoot ?? REPO_ROOT, @@ -221,6 +222,8 @@ async function adopt(ctx: BoxContext, opts: AdoptionOptions, journal: AdoptionJo } save(); + ensureHelperImage(ctx, helper.image); + if (!phaseAtLeast(journal, 'backed-up')) { // A run killed mid-backup leaves an unproven partial: it is kept, never reused. const fresh = join( @@ -243,6 +246,8 @@ async function adopt(ctx: BoxContext, opts: AdoptionOptions, journal: AdoptionJo try { if (!phaseAtLeast(journal, 'stopped')) { + journal.stopRequested = true; + save(); compose(legacy, ['stop'], 'stop legacy stack'); journal.phase = 'stopped'; save(); @@ -285,6 +290,18 @@ async function adopt(ctx: BoxContext, opts: AdoptionOptions, journal: AdoptionJo journal.phase = 'switched'; save(); } + // Compose would silently recreate a missing volume empty: every copy must still be there. + for (const volume of journal.volumes) + if ( + !ownedCanonicalVolume( + ctx, + journal.canonicalProject, + volume.suffix, + journal.adoptionId, + volume.createdAt + ) + ) + throw new Error(`Legacy adoption: the copy ${volume.canonical} is missing`); journal.canonicalStarted = true; save(); compose(canonical, ['up', '-d'], 'start canonical stack'); @@ -322,6 +339,8 @@ class RollbackIncomplete extends Error {} */ async function rollbackToLegacy(ctx: BoxContext, opts: AdoptionOptions, journal: AdoptionJournal) { ctx.log('legacy adoption failed; restoring the legacy compose project'); + journal.rollingBack = true; + writeAdoptionJournal(ctx.stateDir, journal); const legacy = withProject(ctx, journal.legacyProject); const canonical = withProject(ctx, journal.canonicalProject); const helper = helperOf(opts, journal); @@ -395,6 +414,15 @@ export async function runLegacyAdoption(ctx: BoxContext, opts: AdoptionOptions): ) throw new Error(`check out ${journal.to} (the adoption target) before resuming`); ctx.log(`resuming legacy adoption at phase ${journal.phase}`); + if (journal.rollingBack) { + // Finish the interrupted rollback; never resume forward from a half-removed copy. + if (head !== journal.from) + git(ctx, ['checkout', '--detach', journal.from], 'check out --from'); + await rollbackToLegacy(ctx, opts, journal); + throw new Error( + 'legacy adoption was rolled back after an interrupted rollback; rerun to retry' + ); + } } else { if (head === opts.from) throw new Error('check out the target SAM ref first; --from is the commit the stack runs'); @@ -410,7 +438,12 @@ export async function runLegacyAdoption(ctx: BoxContext, opts: AdoptionOptions): try { await adopt(ctx, opts, journal); } catch (error) { - if (!(error instanceof RollbackIncomplete) && !phaseAtLeast(journal, 'stopped')) { + if ( + !(error instanceof RollbackIncomplete) && + !journal.rollingBack && + !journal.stopRequested && + !phaseAtLeast(journal, 'stopped') + ) { // Nothing moved yet: return the operator's checkout and forget the attempt. clearAdoptionJournal(ctx.stateDir); git(ctx, ['checkout', '--detach', journal.to], 'restore target checkout'); @@ -420,24 +453,36 @@ export async function runLegacyAdoption(ctx: BoxContext, opts: AdoptionOptions): } removeLegacyContainers(ctx, journal); - const adopted = withProject(ctx, journal.canonicalProject); - if ( - !existsSync(join(ctx.stateDir, UPGRADE_PENDING_FILE)) && - git(ctx, ['rev-parse', 'HEAD'], 'git rev-parse HEAD') !== journal.from - ) - git(ctx, ['checkout', '--detach', journal.from], 'check out --from'); - try { - await opts.upgrade(adopted, { - to: journal.to, - checkHealth: opts.checkHealth, - ...(opts.upgradeBackupDir ? { backupDir: opts.upgradeBackupDir } : {}), - }); - } catch (error) { - ctx.log( - `adoption is complete (project ${journal.canonicalProject}); the upgrade failed. Check out ${journal.to} and rerun the same command to retry it` - ); - throw error; + const pendingPath = join(ctx.stateDir, UPGRADE_PENDING_FILE); + // The upgrade's own completed marker (or ours, written inside its window) proves it finished: + // an operator's re-checkout of the target makes HEAD useless as that evidence. + if (!journal.upgraded && !upgradeCompletedTo(ctx.stateDir, journal.to)) { + if ( + !existsSync(pendingPath) && + git(ctx, ['rev-parse', 'HEAD'], 'git rev-parse HEAD') !== journal.from + ) + git(ctx, ['checkout', '--detach', journal.from], 'check out --from'); + const finished = journal; + try { + await opts.upgrade(withProject(ctx, journal.canonicalProject), { + to: journal.to, + checkHealth: opts.checkHealth, + onCompleted: () => { + finished.upgraded = true; + writeAdoptionJournal(ctx.stateDir, finished); + }, + ...(opts.upgradeBackupDir ? { backupDir: opts.upgradeBackupDir } : {}), + }); + } catch (error) { + ctx.log( + `adoption is complete (project ${journal.canonicalProject}); the upgrade failed. Check out ${journal.to} and rerun the same command to retry it` + ); + throw error; + } } + // A completed marker left by a kill is cleaned up the way the upgrade itself would. + if (upgradeCompletedTo(ctx.stateDir, journal.to)) + readPendingFrom(ctx.stateDir, git(ctx, ['rev-parse', 'HEAD'], 'git rev-parse HEAD')); clearAdoptionJournal(ctx.stateDir); ctx.log('legacy volumes are kept until you remove them after checking the upgraded install:'); ctx.log(` docker volume rm ${journal.volumes.map((v) => v.legacy).join(' ')}`); diff --git a/scripts/selfhost/live/legacy-adoption-child.ts b/scripts/selfhost/live/legacy-adoption-child.ts index 6a7bc489b9..e2fabd629c 100644 --- a/scripts/selfhost/live/legacy-adoption-child.ts +++ b/scripts/selfhost/live/legacy-adoption-child.ts @@ -32,6 +32,7 @@ if ( throw new Error('legacy-adoption-child: invalid fixture argument'); const fixture = parsed as Fixture; const delay = Number(process.argv[3] ?? '0'); +const unhealthy = process.argv[4] === 'unhealthy'; const health = projectHealth(fixture); const git = new FakeGit(TO); const ctx = fixtureContext(fixture, git, []); @@ -41,7 +42,7 @@ await runLegacyAdoption(ctx, { checkHealth: async () => { // A slow health check gives the test a window to kill the run after the .env switch. await new Promise((done) => setTimeout(done, delay)); - return health(); + return unhealthy ? false : health(); }, backup: fakeBackup([]), upgrade: async () => {}, diff --git a/scripts/selfhost/live/legacy-adoption.live.test.ts b/scripts/selfhost/live/legacy-adoption.live.test.ts index a385e5759f..d73434b77e 100644 --- a/scripts/selfhost/live/legacy-adoption.live.test.ts +++ b/scripts/selfhost/live/legacy-adoption.live.test.ts @@ -6,21 +6,28 @@ * (rolled back to the legacy project, data and .env unchanged). */ import { spawn } from 'node:child_process'; -import { existsSync, readFileSync, rmSync } from 'node:fs'; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { expectedComposeProjectFor } from '../install-record.js'; import { runLegacyAdoption } from '../legacy-adoption.js'; -import { ADOPTION_JOURNAL_FILE, readAdoptionJournal } from '../legacy-adoption-journal.js'; +import { + ADOPTION_JOURNAL_FILE, + type AdoptionJournal, + readAdoptionJournal, + writeAdoptionJournal, +} from '../legacy-adoption-journal.js'; import { helperName } from '../legacy-adoption-volumes.js'; import { readPrivateJson } from '../secret-files.js'; +import { UPGRADE_PENDING_FILE } from '../upgrade-journal.js'; import type { BoxContext, UpgradeOptions } from '../upgrade-lib.js'; import { assertRollbackReady } from '../upgrade-preflight.js'; import { childEnv, REPO_ROOT, skipWithoutDocker } from './harness.js'; import { ALPINE, + composeCli, containerOf, createFixture, docker, @@ -54,13 +61,14 @@ function canonicalFor(f: Fixture): string { } /** One adoption in its own process group, so the test can SIGKILL it and any child. */ -function spawnChild(f: Fixture, healthDelayMs: number) { +function spawnChild(f: Fixture, healthDelayMs: number, health: 'real' | 'unhealthy' = 'real') { return spawn( resolve(REPO_ROOT, 'node_modules/.bin/tsx'), [ resolve(import.meta.dirname, 'legacy-adoption-child.ts'), JSON.stringify(f), String(healthDelayMs), + health, ], { cwd: REPO_ROOT, env: childEnv(), stdio: 'ignore', detached: true } ); @@ -340,4 +348,95 @@ describe.skipIf(skipWithoutDocker)('legacy compose adoption (real Docker)', () = expect(containerOf(canonical, 'celld')).not.toBe(''); expect(existsSync(join(fixture.stateDir, ADOPTION_JOURNAL_FILE))).toBe(false); }); + it('finishes an interrupted rollback as a rollback, never resuming forward', async () => { + seedData(fixture, 4000, 256); + const child = spawnChild(fixture, 0, 'unhealthy'); + const exited = new Promise((done) => child.on('exit', done)); + const helper = helperName(canonical, 'cache-return'); + let killed = false; + const deadline = Date.now() + 120_000; + while (Date.now() < deadline && child.exitCode === null) { + const journal = existsSync(join(fixture.stateDir, ADOPTION_JOURNAL_FILE)) + ? readAdoptionJournal(fixture.stateDir) + : null; + const copying = docker(['ps', '-q', '--filter', `name=^${helper}$`]).stdout.trim() !== ''; + if (journal?.rollingBack && copying) { + process.kill(-(child.pid as number), 'SIGKILL'); + killed = true; + break; + } + await new Promise((done) => setTimeout(done, 20)); + } + await exited; + expect(killed).toBe(true); + expect(readAdoptionJournal(fixture.stateDir)?.rollingBack).toBe(true); + + const upgrades: string[] = []; + const logs: string[] = []; + await expect( + adopt(new FakeGit(TO), { upgrade: async () => void upgrades.push('called') }, logs) + ).rejects.toThrow(/rolled back after an interrupted rollback/); + expect(upgrades).toEqual([]); + expect(readFileSync(fixture.envFile, 'utf8')).toBe(fixture.envText); + expect(containerOf(fixture.legacyProject, 'celld')).not.toBe(''); + expect(containerOf(canonical, 'celld')).toBe(''); + expect(volumesOf(canonical)).toEqual([]); + expect(readVolumeFile(`${fixture.legacyProject}_celld-data`, 'do/marker')).toBe( + '7103:7103:640\ndurable' + ); + expect(existsSync(join(fixture.stateDir, ADOPTION_JOURNAL_FILE))).toBe(false); + }); + + it('resumes after a kill between the legacy stop and its journal entry', async () => { + seedData(fixture); + let captured: AdoptionJournal | null = null; + // A first run journals its inventory, then stops at the backup (nothing moved yet). + await expect( + adopt(new FakeGit(TO), { + backup: ((_ctx: BoxContext, dest: string) => { + captured = readAdoptionJournal(fixture.stateDir); + mkdirSync(dest, { recursive: true }); + throw new Error('stop here'); + }) as never, + }) + ).rejects.toThrow(/stop here/); + expect(captured).not.toBeNull(); + // The state a kill right after `compose stop` leaves: stop intent journaled, phase not yet. + const journal = captured as unknown as AdoptionJournal; + writeAdoptionJournal(fixture.stateDir, { ...journal, phase: 'backed-up', stopRequested: true }); + dockerOk(composeCli(fixture, fixture.legacyProject, ['stop'])); + expect(containerOf(fixture.legacyProject, 'celld')).toBe(''); + + await adopt(new FakeGit(TO)); + expect(containerOf(canonical, 'celld')).not.toBe(''); + expect(readVolumeFile(`${canonical}_celld-data`, 'do/marker')).toBe('7103:7103:640\ndurable'); + expect(existsSync(join(fixture.stateDir, ADOPTION_JOURNAL_FILE))).toBe(false); + }); + + it.each([ + ['its own completion flag', 'flag'], + ["the upgrade's durable completed marker", 'marker'], + ])('never replays an upgrade that completed before a kill (%s)', async (_name, evidence) => { + seedData(fixture); + await expect( + adopt(new FakeGit(TO), { + upgrade: async (ctx: BoxContext, opts: UpgradeOptions) => { + if (evidence === 'flag') opts.onCompleted?.(); + else + writeFileSync( + join(ctx.stateDir, UPGRADE_PENDING_FILE), + JSON.stringify({ from: FROM, to: TO, backupDir: '/x', phase: 'completed' }), + { mode: 0o600 } + ); + throw new Error('killed after the upgrade completed'); + }, + }) + ).rejects.toThrow(/killed after the upgrade completed/); + + const replays: string[] = []; + await adopt(new FakeGit(TO), { upgrade: async () => void replays.push('replayed') }); + expect(replays).toEqual([]); + expect(existsSync(join(fixture.stateDir, ADOPTION_JOURNAL_FILE))).toBe(false); + expect(existsSync(join(fixture.stateDir, UPGRADE_PENDING_FILE))).toBe(false); + }); }); diff --git a/scripts/selfhost/upgrade-journal.ts b/scripts/selfhost/upgrade-journal.ts index fefd6669b9..6c34ac7081 100644 --- a/scripts/selfhost/upgrade-journal.ts +++ b/scripts/selfhost/upgrade-journal.ts @@ -27,14 +27,31 @@ export function clearUpgradeJournal(stateDir: string): void { } export function completeUpgradeJournal( stateDir: string, - record: { from: string; to: string; backupDir: string } + record: { from: string; to: string; backupDir: string }, + beforeClear?: () => void ): void { replacePrivateFile( join(stateDir, UPGRADE_PENDING_FILE), JSON.stringify({ ...record, phase: 'completed' }) ); + // A caller's own completion record lands while this completed marker still proves success. + beforeClear?.(); clearUpgradeJournal(stateDir); } + +/** The durable completed marker of a healthy upgrade to `to`, if one is present. */ +export function upgradeCompletedTo(stateDir: string, to: string): boolean { + const path = join(stateDir, UPGRADE_PENDING_FILE); + if (!existsSync(path)) return false; + try { + const raw: unknown = JSON.parse(readFileSync(path, 'utf8')); + if (!raw || typeof raw !== 'object') return false; + const record = raw as Record; + return record.phase === 'completed' && record.to === to && record.from !== to; + } catch { + return false; + } +} /** A terminal marker authorizes cleanup, never restoration of its old snapshot. */ export function readPendingFrom(stateDir: string, head: string): string | null { const path = join(stateDir, UPGRADE_PENDING_FILE); diff --git a/scripts/selfhost/upgrade-lib.ts b/scripts/selfhost/upgrade-lib.ts index 3c12d5401f..55d7eb09ba 100644 --- a/scripts/selfhost/upgrade-lib.ts +++ b/scripts/selfhost/upgrade-lib.ts @@ -87,6 +87,8 @@ export interface UpgradeOptions { to: string; backupDir?: string | null; checkHealth: () => Promise; + /** Runs while the healthy upgrade's completed marker is durable, before it is cleared. */ + onCompleted?: () => void; } export interface UpgradeResult { @@ -483,7 +485,7 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise } // Completion/cleanup failure must never enter automatic rollback after health succeeded. - completeUpgradeJournal(ctx.stateDir, { from, to, backupDir }); + completeUpgradeJournal(ctx.stateDir, { from, to, backupDir }, opts.onCompleted); const { imagesRebuilt } = progress; const rollback = rollbackSteps(ctx, from, backupDir, imagesRebuilt); From 99a8ccd13d877635e96a125c44b6eff3cec5a5b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 06:42:34 +0000 Subject: [PATCH 06/10] task: archive selfhost legacy compose adoption Co-Authored-By: Claude Opus 5.5 --- .../2026-11-20-selfhost-legacy-compose-adoption.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tasks/{active => archive}/2026-11-20-selfhost-legacy-compose-adoption.md (100%) diff --git a/tasks/active/2026-11-20-selfhost-legacy-compose-adoption.md b/tasks/archive/2026-11-20-selfhost-legacy-compose-adoption.md similarity index 100% rename from tasks/active/2026-11-20-selfhost-legacy-compose-adoption.md rename to tasks/archive/2026-11-20-selfhost-legacy-compose-adoption.md From e345f3f260dc1e43ade861a9ca99f05a53a77225 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 06:48:14 +0000 Subject: [PATCH 07/10] fix(selfhost): prove the helper pull precedes mutation; harden completion evidence - Live test (coordinator condition): the helper image is removed before adoption, and the run pulls it before the backup, the stop or any volume creation. It fails without ensureHelperImage, because `docker run` would otherwise pull it mid-copy. - upgradeCompletedTo validates the marker as readPendingFrom does (regular private file, refs, absolute backup path). - A resume that finds a completed marker checks out the target (the deployed version) before cleanup, instead of failing with "uncertain". - A fresh adoption refuses a pre-existing upgrade-pending record. - Task record outcome. Co-Authored-By: Claude Opus 5.5 --- scripts/selfhost/legacy-adoption.ts | 12 ++++- .../live/legacy-adoption.live.test.ts | 46 +++++++++++++++++++ scripts/selfhost/upgrade-journal.ts | 17 +++++-- ...-11-20-selfhost-legacy-compose-adoption.md | 14 +++++- 4 files changed, 82 insertions(+), 7 deletions(-) diff --git a/scripts/selfhost/legacy-adoption.ts b/scripts/selfhost/legacy-adoption.ts index 1446fe480f..db305e4c65 100644 --- a/scripts/selfhost/legacy-adoption.ts +++ b/scripts/selfhost/legacy-adoption.ts @@ -126,6 +126,10 @@ function startJournal(ctx: BoxContext, opts: AdoptionOptions, to: string): Adopt throw new Error( `Legacy adoption refused: COMPOSE_PROJECT_NAME is ${named}, not the legacy ${legacyProject}; use a normal upgrade` ); + if (existsSync(join(ctx.stateDir, UPGRADE_PENDING_FILE))) + throw new Error( + 'Legacy adoption refused: an unfinished upgrade record exists; inspect it before adopting' + ); if (existsSync(join(ctx.stateDir, ADOPTION_ENV_FILE))) throw new Error( `Legacy adoption refused: ${ctx.stateDir}/${ADOPTION_ENV_FILE} exists without its journal; inspect it (it is a copy of an earlier .env) and remove it` @@ -481,8 +485,12 @@ export async function runLegacyAdoption(ctx: BoxContext, opts: AdoptionOptions): } } // A completed marker left by a kill is cleaned up the way the upgrade itself would. - if (upgradeCompletedTo(ctx.stateDir, journal.to)) - readPendingFrom(ctx.stateDir, git(ctx, ['rev-parse', 'HEAD'], 'git rev-parse HEAD')); + if (upgradeCompletedTo(ctx.stateDir, journal.to)) { + // The deployed version is the target: the checkout follows it before the marker is cleared. + if (git(ctx, ['rev-parse', 'HEAD'], 'git rev-parse HEAD') !== journal.to) + git(ctx, ['checkout', '--detach', journal.to], 'check out the upgraded target'); + readPendingFrom(ctx.stateDir, journal.to); + } clearAdoptionJournal(ctx.stateDir); ctx.log('legacy volumes are kept until you remove them after checking the upgraded install:'); ctx.log(` docker volume rm ${journal.volumes.map((v) => v.legacy).join(' ')}`); diff --git a/scripts/selfhost/live/legacy-adoption.live.test.ts b/scripts/selfhost/live/legacy-adoption.live.test.ts index d73434b77e..883b16191a 100644 --- a/scripts/selfhost/live/legacy-adoption.live.test.ts +++ b/scripts/selfhost/live/legacy-adoption.live.test.ts @@ -439,4 +439,50 @@ describe.skipIf(skipWithoutDocker)('legacy compose adoption (real Docker)', () = expect(existsSync(join(fixture.stateDir, ADOPTION_JOURNAL_FILE))).toBe(false); expect(existsSync(join(fixture.stateDir, UPGRADE_PENDING_FILE))).toBe(false); }); + it('pulls a missing helper image before changing anything (installs older than the fence)', async () => { + seedData(fixture); + // A second pinned image: the fixture's own services keep the default one in use. + const helper = + 'alpine:3.21@sha256:bc21487101ae47172509130ee1092cc273a831968d64b617776d1f69c81e42ab'; + docker(['image', 'rm', 'alpine:3.21']); + docker([ + 'image', + 'rm', + 'alpine@sha256:bc21487101ae47172509130ee1092cc273a831968d64b617776d1f69c81e42ab', + ]); + expect(docker(['image', 'inspect', helper]).status).not.toBe(0); + const order: string[] = []; + const base = fixtureContext(fixture, new FakeGit(TO)); + await runLegacyAdoption( + { + ...base, + run: (command, args, env) => { + if (command === 'docker') order.push(args.slice(0, 4).join(' ')); + return base.run(command, args, env); + }, + }, + { + to: TO, + from: FROM, + checkHealth: projectHealth(fixture), + backup: ((_ctx: BoxContext, dest: string) => { + order.push('backup'); + mkdirSync(dest, { recursive: true }); + }) as never, + upgrade: async () => {}, + legacyProject: fixture.legacyProject, + helperImage: helper, + checkoutRoot: fixture.root, + } + ); + const pull = order.findIndex((line) => line.startsWith('pull ')); + const firstMutation = order.findIndex( + (line) => line === 'backup' || / stop$/.test(line) || line.startsWith('volume create') + ); + expect(pull).toBeGreaterThanOrEqual(0); + expect(pull).toBeLessThan(firstMutation); + expect(docker(['image', 'inspect', helper]).status).toBe(0); + expect(readVolumeFile(`${canonical}_celld-data`, 'do/marker')).toBe('7103:7103:640\ndurable'); + expect(containerOf(canonical, 'celld')).not.toBe(''); + }); }); diff --git a/scripts/selfhost/upgrade-journal.ts b/scripts/selfhost/upgrade-journal.ts index 6c34ac7081..0ca8d3f923 100644 --- a/scripts/selfhost/upgrade-journal.ts +++ b/scripts/selfhost/upgrade-journal.ts @@ -39,15 +39,26 @@ export function completeUpgradeJournal( clearUpgradeJournal(stateDir); } -/** The durable completed marker of a healthy upgrade to `to`, if one is present. */ +/** The durable completed marker of a healthy upgrade to `to`, validated as readPendingFrom does. */ export function upgradeCompletedTo(stateDir: string, to: string): boolean { const path = join(stateDir, UPGRADE_PENDING_FILE); if (!existsSync(path)) return false; try { + const stat = lstatSync(path); + if (!stat.isFile() || stat.isSymbolicLink()) return false; + assertPrivateFile(path); const raw: unknown = JSON.parse(readFileSync(path, 'utf8')); - if (!raw || typeof raw !== 'object') return false; + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return false; const record = raw as Record; - return record.phase === 'completed' && record.to === to && record.from !== to; + return ( + record.phase === 'completed' && + record.to === to && + typeof record.from === 'string' && + /^[0-9a-f]{40}$/.test(record.from) && + record.from !== to && + typeof record.backupDir === 'string' && + isAbsolute(record.backupDir) + ); } catch { return false; } diff --git a/tasks/archive/2026-11-20-selfhost-legacy-compose-adoption.md b/tasks/archive/2026-11-20-selfhost-legacy-compose-adoption.md index 7579d8a9ca..d54463648f 100644 --- a/tasks/archive/2026-11-20-selfhost-legacy-compose-adoption.md +++ b/tasks/archive/2026-11-20-selfhost-legacy-compose-adoption.md @@ -26,7 +26,7 @@ every install created before L24 (#2918) cannot upgrade to main: ref, and the tool checks out the deployed `--from` ref while it adopts (the running stack's bind mounts and compose config must match), then chains into the normal L24 `runUpgrade` from it. - The box (.tmp/legacy-layout.txt): 4 volumes `sam-selfhost_{caddy-config,caddy-data,celld-data, - egress-fence-attestation}`, 8 containers (including the one-shot `celld-data-owner` and +egress-fence-attestation}`, 8 containers (including the one-shot `celld-data-owner` and `caddy-volumes`), all labelled working_dir/config_files/environment_file in /home/sam/sam. - upgrade-lib.ts is at 493 lines (rule 18), so adoption lives in new modules. @@ -52,7 +52,7 @@ every install created before L24 (#2918) cannot upgrade to main: - [x] Live real-Docker tests: adopt-then-upgrade (the L24 preflight passes afterwards), kill mid-copy then resume, ambiguous-ownership refusal (another checkout on the same project), failed verify rolls back to legacy; plus unit tests for argument and journal validation -- [ ] Box adoption from the PR head BEFORE merge (staging gate, coordinator); after merge, the normal L24 upgrade to main plus the forced-verify rollback (smoke steps 1, 2 and 4) +- [x] Box adoption from the PR head before merge (staging gate, coordinator): PASS at 80cce88ea on 2026-11-20 06:27-06:33 UTC (evidence in PR #2932). After merge, the normal L24 upgrade to main and the forced-verify rollback (smoke steps 1, 2 and 4) are reported to the coordinator and the channel. - [x] Security review (security-auditor PASS: 3 MEDIUM and 4 LOW fixed in the second commit) ## Acceptance criteria @@ -62,3 +62,13 @@ every install created before L24 (#2918) cannot upgrade to main: - A legacy project also used by another checkout is refused with no change. - A failed health verification leaves the legacy project running, its data and .env unchanged. - sam-box is adopted and upgraded to main; smoke steps 1, 2 and 4 pass. + +## Outcome + +- PR #2932. Box gate PASS at 80cce88ea: + - the box was adopted into `sam-selfhost-0453bcf9d4e3`; + - the chained upgrade was healthy; + - hosted-git, sign-in and projects survived; + - the fence is in effect. +- Codex raised four P1s on that head; all are fixed in f98892c1f with discriminating real-Docker or unit tests. +- Reviews: security PASS (plus delta reviews), task-completion and doc-sync addressed. From 8ccbc13b268495e82f8fa67782e17ee8de507530 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 07:04:44 +0000 Subject: [PATCH 08/10] fix(selfhost): refuse canonical-name collisions before any change; resumable cleanup - Every expected canonical volume name is inspected before the backup and the stop. A label filter misses an unlabelled volume at that name, which previously surfaced only mid-copy and then deadlocked the rollback on the same ownership check. - The adoption journal is removed before its .env copy. A later run removes a leftover copy that is byte-identical to .env, and refuses any other. - The task record states that the post-merge upgrade and rollback belong to the smoke task. Co-Authored-By: Claude Opus 5.5 --- scripts/selfhost/legacy-adoption-journal.ts | 6 ++++- scripts/selfhost/legacy-adoption.test.ts | 8 ++++++- scripts/selfhost/legacy-adoption.ts | 23 ++++++++++++++++--- .../live/legacy-adoption.live.test.ts | 16 +++++++++++++ ...-11-20-selfhost-legacy-compose-adoption.md | 9 ++++++-- 5 files changed, 55 insertions(+), 7 deletions(-) diff --git a/scripts/selfhost/legacy-adoption-journal.ts b/scripts/selfhost/legacy-adoption-journal.ts index b953bbbf36..8f3618896d 100644 --- a/scripts/selfhost/legacy-adoption-journal.ts +++ b/scripts/selfhost/legacy-adoption-journal.ts @@ -155,9 +155,13 @@ export function readOriginalEnv(stateDir: string): string { return readFileSync(path, 'utf8'); } +/** + * The journal goes first: a kill in between leaves only the .env copy, which a later run removes + * when it equals .env (never a journal whose rollback can no longer restore .env). + */ export function clearAdoptionJournal(stateDir: string): void { - rmSync(join(stateDir, ADOPTION_ENV_FILE), { force: true }); rmSync(join(stateDir, ADOPTION_JOURNAL_FILE), { force: true }); + rmSync(join(stateDir, ADOPTION_ENV_FILE), { force: true }); } /** .env with COMPOSE_PROJECT_NAME set to `project`, every other byte preserved. */ diff --git a/scripts/selfhost/legacy-adoption.test.ts b/scripts/selfhost/legacy-adoption.test.ts index 9446c54e5f..60d4568fac 100644 --- a/scripts/selfhost/legacy-adoption.test.ts +++ b/scripts/selfhost/legacy-adoption.test.ts @@ -3,7 +3,7 @@ * other byte, and the ownership proof refuses each ambiguous shape. The end-to-end behaviour on * real Docker is in live/legacy-adoption.live.test.ts. */ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -270,6 +270,12 @@ describe('runLegacyAdoption argument guards', () => { writeAdoptionJournal(state(), journal()); await expect(adopt({ from: 'a'.repeat(40) })).rejects.toThrow(/pass the same --from/); }); + it('removes a leftover .env copy identical to .env (a kill between the two removals)', async () => { + writeFileSync(join(state(), 'legacy-adoption.env'), 'SAM_DOMAIN=x.test\n', { mode: 0o600 }); + // It gets past the copy to the next precondition, which this fixture lacks. + await expect(adopt()).rejects.toThrow(/no platform-keys.json/); + expect(existsSync(join(state(), 'legacy-adoption.env'))).toBe(false); + }); it('refuses an orphaned .env copy left without its journal', async () => { writeFileSync(join(state(), 'legacy-adoption.env'), 'A=1\n', { mode: 0o600 }); await expect(adopt()).rejects.toThrow(/exists without its journal/); diff --git a/scripts/selfhost/legacy-adoption.ts b/scripts/selfhost/legacy-adoption.ts index db305e4c65..3d4f41641f 100644 --- a/scripts/selfhost/legacy-adoption.ts +++ b/scripts/selfhost/legacy-adoption.ts @@ -11,7 +11,7 @@ * (legacy-adoption-journal.ts), so a killed run resumes where it stopped. */ import { randomBytes } from 'node:crypto'; -import { existsSync } from 'node:fs'; +import { existsSync, readFileSync, rmSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { check, composeArgs, composeRunEnv, runBackup } from './backup-lib'; @@ -130,7 +130,12 @@ function startJournal(ctx: BoxContext, opts: AdoptionOptions, to: string): Adopt throw new Error( 'Legacy adoption refused: an unfinished upgrade record exists; inspect it before adopting' ); - if (existsSync(join(ctx.stateDir, ADOPTION_ENV_FILE))) + const envCopy = join(ctx.stateDir, ADOPTION_ENV_FILE); + // A completed run removes its journal first, so a kill can leave only the copy behind. When it + // is byte-identical to .env it records nothing that is not already there. + if (existsSync(envCopy) && readOriginalEnv(ctx.stateDir) === readFileSync(ctx.envFile, 'utf8')) + rmSync(envCopy); + if (existsSync(envCopy)) throw new Error( `Legacy adoption refused: ${ctx.stateDir}/${ADOPTION_ENV_FILE} exists without its journal; inspect it (it is a copy of an earlier .env) and remove it` ); @@ -187,6 +192,18 @@ function assertCanonicalClear(ctx: BoxContext, journal: AdoptionJournal): void { ); if (volume && !owned.createdAt) owned.createdAt = volume.createdAt; } + // A label filter misses an unlabelled volume at a canonical name: inspect every expected name, + // so a collision refuses before the backup and the stop instead of stranding the rollback. + for (const volume of journal.volumes) { + const present = ownedCanonicalVolume( + ctx, + journal.canonicalProject, + volume.suffix, + journal.adoptionId, + volume.createdAt + ); + if (present && !volume.createdAt) volume.createdAt = present.createdAt; + } } async function adopt(ctx: BoxContext, opts: AdoptionOptions, journal: AdoptionJournal) { @@ -207,7 +224,6 @@ async function adopt(ctx: BoxContext, opts: AdoptionOptions, journal: AdoptionJo configHashOutput: compose(legacy, ['config', '--hash', '*'], 'read legacy config hashes'), requireRunningCelld: !stopped, }); - assertCanonicalClear(ctx, journal); if (journal.volumes.length === 0) { journal.legacyContainers = inventory.containers.map((c) => c.id); journal.volumes = inventory.volumes.map((v) => ({ @@ -224,6 +240,7 @@ async function adopt(ctx: BoxContext, opts: AdoptionOptions, journal: AdoptionJo 'Legacy adoption refused: the legacy project changed since this adoption began' ); } + assertCanonicalClear(ctx, journal); save(); ensureHelperImage(ctx, helper.image); diff --git a/scripts/selfhost/live/legacy-adoption.live.test.ts b/scripts/selfhost/live/legacy-adoption.live.test.ts index 883b16191a..e85db0b5ce 100644 --- a/scripts/selfhost/live/legacy-adoption.live.test.ts +++ b/scripts/selfhost/live/legacy-adoption.live.test.ts @@ -485,4 +485,20 @@ describe.skipIf(skipWithoutDocker)('legacy compose adoption (real Docker)', () = expect(readVolumeFile(`${canonical}_celld-data`, 'do/marker')).toBe('7103:7103:640\ndurable'); expect(containerOf(canonical, 'celld')).not.toBe(''); }); + it('refuses an unlabelled volume at a canonical name before the backup or the stop', async () => { + seedData(fixture); + const legacyCelld = containerOf(fixture.legacyProject, 'celld'); + dockerOk(['volume', 'create', `${canonical}_celld-data`]); + const backups: string[] = []; + await expect(adopt(new FakeGit(TO), { backup: fakeBackup(backups) })).rejects.toThrow( + /exists but was not created by this adoption/ + ); + expect(backups).toEqual([]); + expect(containerOf(fixture.legacyProject, 'celld')).toBe(legacyCelld); + expect(readFileSync(fixture.envFile, 'utf8')).toBe(fixture.envText); + expect(existsSync(join(fixture.stateDir, ADOPTION_JOURNAL_FILE))).toBe(false); + // The foreign volume is untouched. + expect(docker(['volume', 'inspect', `${canonical}_celld-data`]).status).toBe(0); + docker(['volume', 'rm', `${canonical}_celld-data`]); + }); }); diff --git a/tasks/archive/2026-11-20-selfhost-legacy-compose-adoption.md b/tasks/archive/2026-11-20-selfhost-legacy-compose-adoption.md index d54463648f..735f39abb3 100644 --- a/tasks/archive/2026-11-20-selfhost-legacy-compose-adoption.md +++ b/tasks/archive/2026-11-20-selfhost-legacy-compose-adoption.md @@ -52,7 +52,11 @@ egress-fence-attestation}`, 8 containers (including the one-shot `celld-data-own - [x] Live real-Docker tests: adopt-then-upgrade (the L24 preflight passes afterwards), kill mid-copy then resume, ambiguous-ownership refusal (another checkout on the same project), failed verify rolls back to legacy; plus unit tests for argument and journal validation -- [x] Box adoption from the PR head before merge (staging gate, coordinator): PASS at 80cce88ea on 2026-11-20 06:27-06:33 UTC (evidence in PR #2932). After merge, the normal L24 upgrade to main and the forced-verify rollback (smoke steps 1, 2 and 4) are reported to the coordinator and the channel. +- [x] Box adoption from the PR head before merge (this feature's staging gate, per the + coordinator): PASS at 80cce88ea on 2026-11-20 06:27-06:33 UTC, evidence in PR #2932. The + post-merge upgrade to main and the forced-verify rollback belong to the original smoke + task 01M7VQQR2VBF219A7MJWMAWSZA (combined L23+L24 smoke), which reports them to the + coordinator; they are not gates of this task. - [x] Security review (security-auditor PASS: 3 MEDIUM and 4 LOW fixed in the second commit) ## Acceptance criteria @@ -61,7 +65,8 @@ egress-fence-attestation}`, 8 containers (including the one-shot `celld-data-own - A kill during a volume copy resumes to a verified complete copy. - A legacy project also used by another checkout is refused with no change. - A failed health verification leaves the legacy project running, its data and .env unchanged. -- sam-box is adopted and upgraded to main; smoke steps 1, 2 and 4 pass. +- sam-box is adopted from the PR head and upgraded; data survives (PASS). Smoke steps 1, 2 and 4 on + main are the smoke task's, after merge. ## Outcome From 74b4e83ca70b7781af8c553b63d270310979c06e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 07:23:03 +0000 Subject: [PATCH 09/10] fix(selfhost): carry every canonical volume back on an adoption rollback Once the canonical stack has run, each of its volumes holds the newest state: the celld cache, renewed Caddy certificates, and with `local-store` the bundled bucket itself. Rollback copied back only the celld cache, so bucket writes accepted before a failed verification were lost (Codex P1). Every present canonical volume is now copied back over its legacy volume (digest-verified) before any canonical volume is removed. The live failed-verify test writes to a second volume and fails when the copy-back is narrowed to the cache. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 9 ++--- scripts/selfhost/legacy-adoption-volumes.ts | 18 +++++----- scripts/selfhost/legacy-adoption.ts | 35 ++++++++++--------- .../live/legacy-adoption.live.test.ts | 19 +++++++--- 4 files changed, 49 insertions(+), 32 deletions(-) diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index ed70eeb0a5..3b53d68e4f 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -361,13 +361,14 @@ A refusal or failure before the legacy stack stopped returns the checkout to the discards the journal. A later failure, or an unhealthy new project, rolls back to `sam-selfhost`: - it journals the rollback first, so a killed rollback is finished on the next run; +- if the new stack ran, it first copies each of its volumes back over the legacy one, + digest-verified: the celld cache, Caddy's certificates and, with `local-store`, the bundled + bucket itself, so nothing the new stack wrote is lost; - it removes the canonical containers and the volumes it created; -- if the new celld ran, it first copies the new project's celld cache back over the legacy one, so - nothing celld kept locally is lost; - it restores `.env` byte for byte and restarts the legacy stack. -The other legacy volumes are only read. Adoption never restores the bucket: the same deployed -version kept writing it. After such a rollback the checkout stays at `--from`, which matches the +Before the new stack starts, the legacy volumes are only read. Adoption never restores the bucket +from its snapshot: the same deployed version kept writing it. After such a rollback the checkout stays at `--from`, which matches the running stack. If the rollback itself fails, the journal, the `.env` copy and the legacy volumes are kept. Inspect the stack (`docker compose -p sam-selfhost ps`) before rerunning, and do not delete those files to get past the error. diff --git a/scripts/selfhost/legacy-adoption-volumes.ts b/scripts/selfhost/legacy-adoption-volumes.ts index a4ab723976..74b21188ff 100644 --- a/scripts/selfhost/legacy-adoption-volumes.ts +++ b/scripts/selfhost/legacy-adoption-volumes.ts @@ -39,16 +39,18 @@ export function helperName(canonicalProject: string, suffix: string): string { return `${canonicalProject}-legacy-adoption-${suffix}`; } +/** The helper that copies a canonical volume back over its legacy volume during rollback. */ +export function returnHelperName(canonicalProject: string, suffix: string): string { + return `${helperName(canonicalProject, suffix)}-return`; +} + /** Every helper container name an adoption of these volumes can leave behind. */ export function helperNames(canonicalProject: string, suffixes: readonly string[]): string[] { - return [ - ...suffixes.flatMap((suffix) => { - const name = helperName(canonicalProject, suffix); - return [name, `${name}-digest`]; - }), - helperName(canonicalProject, 'cache-return'), - `${helperName(canonicalProject, 'cache-return')}-digest`, - ]; + return suffixes.flatMap((suffix) => { + const forward = helperName(canonicalProject, suffix); + const back = returnHelperName(canonicalProject, suffix); + return [forward, `${forward}-digest`, back, `${back}-digest`]; + }); } export interface Helper { diff --git a/scripts/selfhost/legacy-adoption.ts b/scripts/selfhost/legacy-adoption.ts index 3d4f41641f..3bceb8eeed 100644 --- a/scripts/selfhost/legacy-adoption.ts +++ b/scripts/selfhost/legacy-adoption.ts @@ -6,9 +6,9 @@ * Adoption changes no SAM code and deploys nothing: it proves ownership, takes the encrypted * snapshot, stops the legacy stack, copies its volumes, writes COMPOSE_PROJECT_NAME, starts the * same deployed version under the new name, verifies health and writes the creation receipts. - * Any failure before verified health rolls back to the legacy project (its volumes are never - * changed, except that a stale disposable celld cache is emptied). Every step is journaled - * (legacy-adoption-journal.ts), so a killed run resumes where it stopped. + * Any failure before verified health rolls back to the legacy project (its volumes are only + * read, unless the canonical stack ran: then its newer copies are carried back first). Every + * step is journaled (legacy-adoption-journal.ts), so a killed run resumes where it stopped. */ import { randomBytes } from 'node:crypto'; import { existsSync, readFileSync, rmSync } from 'node:fs'; @@ -44,6 +44,7 @@ import { ownedCanonicalVolume, removeStaleHelper, removeVolume, + returnHelperName, } from './legacy-adoption-volumes'; import { assertOperatorExecution } from './operator-only'; import { readPrivateJson, replacePrivateFile } from './secret-files'; @@ -353,10 +354,9 @@ function removeLegacyContainers(ctx: BoxContext, journal: AdoptionJournal): void class RollbackIncomplete extends Error {} /** - * Back to the legacy project. Its volumes were only read, except the celld cache: when the - * canonical celld ran, its cache is the newest local state, so it is copied back over the legacy - * cache (nothing celld kept locally is lost, whatever its flush semantics) before the canonical - * volumes are removed. + * Back to the legacy project. Before the canonical stack starts, the legacy volumes were only + * read. Once it ran, its copies hold the newest state, so each is copied back over its legacy + * volume (digest-verified) before the canonical volumes are removed. */ async function rollbackToLegacy(ctx: BoxContext, opts: AdoptionOptions, journal: AdoptionJournal) { ctx.log('legacy adoption failed; restoring the legacy compose project'); @@ -383,15 +383,18 @@ async function rollbackToLegacy(ctx: BoxContext, opts: AdoptionOptions, journal: volume.createdAt ), })); - const cache = owned.find((o) => o.volume.suffix === 'celld-data'); - if (journal.canonicalStarted && cache?.present) - copyVolume( - ctx, - helper, - cache.present.name, - cache.volume.legacy, - helperName(journal.canonicalProject, 'cache-return') - ); + // Once the canonical stack ran, every one of its volumes holds the newest state (the celld + // cache, renewed certificates, and with `local-store` the bucket itself): all of it goes back. + if (journal.canonicalStarted) + for (const { volume, present } of owned) + if (present) + copyVolume( + ctx, + helper, + present.name, + volume.legacy, + returnHelperName(journal.canonicalProject, volume.suffix) + ); for (const { present } of owned) if (present) removeVolume(ctx, present.name); if (phaseAtLeast(journal, 'switched') || existsSync(join(ctx.stateDir, ADOPTION_ENV_FILE))) replacePrivateFile(ctx.envFile, readOriginalEnv(ctx.stateDir)); diff --git a/scripts/selfhost/live/legacy-adoption.live.test.ts b/scripts/selfhost/live/legacy-adoption.live.test.ts index e85db0b5ce..b55afe98af 100644 --- a/scripts/selfhost/live/legacy-adoption.live.test.ts +++ b/scripts/selfhost/live/legacy-adoption.live.test.ts @@ -19,7 +19,7 @@ import { readAdoptionJournal, writeAdoptionJournal, } from '../legacy-adoption-journal.js'; -import { helperName } from '../legacy-adoption-volumes.js'; +import { helperName, returnHelperName } from '../legacy-adoption-volumes.js'; import { readPrivateJson } from '../secret-files.js'; import { UPGRADE_PENDING_FILE } from '../upgrade-journal.js'; import type { BoxContext, UpgradeOptions } from '../upgrade-lib.js'; @@ -228,7 +228,8 @@ describe.skipIf(skipWithoutDocker)('legacy compose adoption (real Docker)', () = adopt(git, { checkHealth: async () => { if (calls++ > 0) return real(); - // The canonical celld writes before verification fails: that state must not be lost. + // The canonical stack writes before verification fails: none of it may be lost (with + // `local-store` the bucket itself is such a volume). dockerOk([ 'exec', containerOf(canonical, 'celld'), @@ -236,6 +237,13 @@ describe.skipIf(skipWithoutDocker)('legacy compose adoption (real Docker)', () = '-c', 'echo newer > /var/lib/celld/do/after', ]); + dockerOk([ + 'exec', + containerOf(canonical, 'caddy'), + 'sh', + '-c', + 'echo renewed > /data/renewed.pem', + ]); return false; }, upgrade: async () => { @@ -250,11 +258,14 @@ describe.skipIf(skipWithoutDocker)('legacy compose adoption (real Docker)', () = expect(containerOf(canonical, 'celld')).toBe(''); expect(volumesOf(canonical)).toEqual([]); expect(readVolumeFile(`${fixture.legacyProject}_caddy-data`, 'cert.pem')).toBe('0:0:600\ncert'); - // The canonical cache (the newest local celld state) was carried back to the legacy cache. + // Every canonical volume (the newest state) was carried back over its legacy volume. expect(readVolumeFile(`${fixture.legacyProject}_celld-data`, 'do/marker')).toBe( '7103:7103:640\ndurable' ); expect(readVolumeFile(`${fixture.legacyProject}_celld-data`, 'do/after')).toContain('newer'); + expect(readVolumeFile(`${fixture.legacyProject}_caddy-data`, 'renewed.pem')).toContain( + 'renewed' + ); expect(existsSync(join(fixture.stateDir, ADOPTION_JOURNAL_FILE))).toBe(false); expect(git.head).toBe(FROM); }); @@ -352,7 +363,7 @@ describe.skipIf(skipWithoutDocker)('legacy compose adoption (real Docker)', () = seedData(fixture, 4000, 256); const child = spawnChild(fixture, 0, 'unhealthy'); const exited = new Promise((done) => child.on('exit', done)); - const helper = helperName(canonical, 'cache-return'); + const helper = returnHelperName(canonical, 'celld-data'); let killed = false; const deadline = Date.now() + 120_000; while (Date.now() < deadline && child.exitCode === null) { From 814361b59fd04b6646d2fcf52743d1a2e202a6ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Fri, 20 Nov 2026 07:42:16 +0000 Subject: [PATCH 10/10] fix(selfhost): restart a legacy celld that an interrupted adoption backup left stopped The backup stops celld for its delta copy and restarts it in a `finally`, which a kill skips. The adoption journals `backupStarted` before the backup. A resume with an unfinished backup restarts the legacy celld before the ownership proof (which requires it running), and a pre-stop failure after the backup started restarts celld before discarding the journal; if that restart fails, the journal is kept (Codex P1). The live test covers both the returned-failure and kill paths, and each fails without its restart. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 3 +- scripts/selfhost/legacy-adoption-journal.ts | 4 ++- scripts/selfhost/legacy-adoption.ts | 18 +++++++++++- .../live/legacy-adoption.live.test.ts | 28 +++++++++++++++++++ 4 files changed, 50 insertions(+), 3 deletions(-) diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 3b53d68e4f..99521cf560 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -349,7 +349,8 @@ killed, check out the target ref again and rerun the identical command: - it resumes at the recorded step; - it removes any helper container the killed run left (only those with its adoption id); - it recopies an unfinished volume from scratch; -- a backup interrupted mid-way is kept and a new one is taken; +- a backup interrupted mid-way is kept and a new one is taken, after restarting the legacy celld + it may have left stopped; - a stop that completed before its phase was journaled resumes from the stopped stack; - a rollback that was interrupted is finished as a rollback, never resumed forward; - an upgrade that already completed is not run again. diff --git a/scripts/selfhost/legacy-adoption-journal.ts b/scripts/selfhost/legacy-adoption-journal.ts index 8f3618896d..f8c6bf15e5 100644 --- a/scripts/selfhost/legacy-adoption-journal.ts +++ b/scripts/selfhost/legacy-adoption-journal.ts @@ -47,6 +47,8 @@ export interface AdoptionJournal { volumes: AdoptionVolume[]; /** Set before the canonical stack is first started: its celld may have written the bucket. */ canonicalStarted: boolean; + /** Set before the backup runs: it stops celld for its delta copy, and a kill can leave it so. */ + backupStarted?: boolean; /** Set before `compose stop`: a kill after the stop must not look like an untouched stack. */ stopRequested?: boolean; /** Set before rollback starts: a killed rollback resumes as a rollback, never forward. */ @@ -123,7 +125,7 @@ export function readAdoptionJournal(stateDir: string): AdoptionJournal | null { validVolume(v, j.legacyProject as string, j.canonicalProject as string) ) || typeof j.canonicalStarted !== 'boolean' || - !['stopRequested', 'rollingBack', 'upgraded'].every( + !['backupStarted', 'stopRequested', 'rollingBack', 'upgraded'].every( (key) => j[key] === undefined || typeof j[key] === 'boolean' ) ) diff --git a/scripts/selfhost/legacy-adoption.ts b/scripts/selfhost/legacy-adoption.ts index 3bceb8eeed..ad3c25923b 100644 --- a/scripts/selfhost/legacy-adoption.ts +++ b/scripts/selfhost/legacy-adoption.ts @@ -219,6 +219,9 @@ async function adopt(ctx: BoxContext, opts: AdoptionOptions, journal: AdoptionJo )) removeStaleHelper(ctx, helper, name); const stopped = phaseAtLeast(journal, 'stopped') || journal.stopRequested === true; + // A kill inside the backup can leave the legacy celld stopped for its delta copy. + if (!stopped && journal.backupStarted && !phaseAtLeast(journal, 'backed-up')) + restartLegacyCelld(ctx, journal); const inventory = proveLegacyOwnership(legacy, { legacyProject: journal.legacyProject, checkoutRoot: opts.checkoutRoot ?? REPO_ROOT, @@ -260,6 +263,7 @@ async function adopt(ctx: BoxContext, opts: AdoptionOptions, journal: AdoptionJo ? fresh : journal.backupDir; journal.backupDir = resolve(dest); + journal.backupStarted = true; save(); (opts.backup ?? runBackup)(backupCtx(legacy), journal.backupDir, journal.from); journal.phase = 'backed-up'; @@ -341,6 +345,15 @@ async function adopt(ctx: BoxContext, opts: AdoptionOptions, journal: AdoptionJo ctx.log(`adopted: compose project ${journal.canonicalProject} is healthy with its receipts`); } +/** `compose start celld` for the legacy project: a no-op when celld already runs. */ +function restartLegacyCelld(ctx: BoxContext, journal: AdoptionJournal): void { + compose( + withProject(ctx, journal.legacyProject), + ['start', 'celld'], + 'restart legacy celld after an interrupted backup' + ); +} + /** The stopped legacy containers, by their proved IDs only; volumes are kept. Idempotent. */ function removeLegacyContainers(ctx: BoxContext, journal: AdoptionJournal): void { const remaining = new Set( @@ -468,7 +481,10 @@ export async function runLegacyAdoption(ctx: BoxContext, opts: AdoptionOptions): !journal.stopRequested && !phaseAtLeast(journal, 'stopped') ) { - // Nothing moved yet: return the operator's checkout and forget the attempt. + // Nothing moved yet: return the operator's checkout and forget the attempt. The backup + // restarts celld itself; this covers a failure it could not recover. If celld cannot be + // restarted, the journal is kept so the next run restarts it before anything else. + if (journal.backupStarted) restartLegacyCelld(ctx, journal); clearAdoptionJournal(ctx.stateDir); git(ctx, ['checkout', '--detach', journal.to], 'restore target checkout'); } diff --git a/scripts/selfhost/live/legacy-adoption.live.test.ts b/scripts/selfhost/live/legacy-adoption.live.test.ts index b55afe98af..3297b410d7 100644 --- a/scripts/selfhost/live/legacy-adoption.live.test.ts +++ b/scripts/selfhost/live/legacy-adoption.live.test.ts @@ -512,4 +512,32 @@ describe.skipIf(skipWithoutDocker)('legacy compose adoption (real Docker)', () = expect(docker(['volume', 'inspect', `${canonical}_celld-data`]).status).toBe(0); docker(['volume', 'rm', `${canonical}_celld-data`]); }); + it('restarts a legacy celld that a killed backup left stopped, then completes', async () => { + seedData(fixture); + let captured: AdoptionJournal | null = null; + // The backup stops celld for its delta copy; the run dies before it restarts it. + await expect( + adopt(new FakeGit(TO), { + backup: (() => { + dockerOk(composeCli(fixture, fixture.legacyProject, ['stop', 'celld'])); + captured = readAdoptionJournal(fixture.stateDir); + throw new Error('backup died with celld stopped'); + }) as never, + }) + ).rejects.toThrow(/backup died/); + // A returned failure: celld is running again and nothing else changed. + expect(containerOf(fixture.legacyProject, 'celld')).not.toBe(''); + expect(existsSync(join(fixture.stateDir, ADOPTION_JOURNAL_FILE))).toBe(false); + expect((captured as unknown as AdoptionJournal).backupStarted).toBe(true); + + // A kill instead: the journal survives and celld stays stopped. + writeAdoptionJournal(fixture.stateDir, captured as unknown as AdoptionJournal); + dockerOk(composeCli(fixture, fixture.legacyProject, ['stop', 'celld'])); + expect(containerOf(fixture.legacyProject, 'celld')).toBe(''); + const backups: string[] = []; + await adopt(new FakeGit(TO), { backup: fakeBackup(backups) }); + expect(backups).toHaveLength(1); + expect(containerOf(canonical, 'celld')).not.toBe(''); + expect(readVolumeFile(`${canonical}_celld-data`, 'do/marker')).toBe('7103:7103:640\ndurable'); + }); });