Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Round 40: the update path under hostile conditions (8 updater and master fixes) (#807)

Dee8c0b7085499a
diff --git a/cli/e2e/updateHostile.e2e.ts b/cli/e2e/updateHostile.e2e.ts
new file mode 100644
index 000000000..ee8346b83
--- /dev/null
+++ b/cli/e2e/updateHostile.e2e.ts
@@ -0,0 +1,601 @@
+/**
+ * Round 40: the update path under hostile conditions, end to end on real release bundles (built from
+ * this checkout at made-up versions and served from a local manifest, as in e2e/update.e2e.ts and
+ * e2e/reexec.e2e.ts). It is how every fix reaches every machine, so it has to hold when the link
+ * drops, the release is broken, the manifest lies, two checks race the master, agents are mid-turn,
+ * the new core cannot start, the master dies mid-update and the disk fills.
+ *
+ * After each: the daemon runs a working build (the old one or the new one) under its master, every
+ * agent is back and takes a turn, nothing half-written is left in the install for the next update to
+ * trip on, and a build that failed on this machine is remembered, while one that only met a bad moment
+ * (a dropped link, a full disk) is installed once the moment passes.
+ *
+ * The full-disk half mounts a small disk image of its own (macOS `hdiutil`), as e2e/diskfull.e2e.ts
+ * does, so it is opt-in: `DISKFULL=1 npm run test:e2e -- updateHostile`.
+ */
+import { execFileSync } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import {
+ closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, rmSync, statSync, truncateSync, writeFileSync, writeSync,
+} from 'node:fs'
+import { createServer, type Server, type ServerResponse } from 'node:http'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterAll, afterEach, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient, type Frame } from './harness/client.js'
+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'
+
+const FIRST = '43.0.1'
+const DISKFULL = process.env.DISKFULL === '1' && process.platform === 'darwin'
+/** Passes the updater's canary (`cli.js version`), then dies on every start as a core. */
+const CRASHES_AS_A_CORE = 'if(process.argv[2]==="__run")process.exit(3);'
+const sha = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex')
+const count = (text: string, part: string): number => text.split(part).length - 1
+const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms))
+type Row = Record<string, any>
+
+/** One bundle built from this checkout; every release below is it at another version. */
+let built = ''
+let builtNotify = ''
+let buildDir = ''
+
+beforeAll(() => {
+ buildDir = mkdtempSync(join(tmpdir(), 'harnessd-hostile-build-'))
+ execFileSync(process.execPath, ['build-bundle.mjs'], {
+ cwd: CLI_ROOT, env: { ...process.env, ADAPTER_VERSION: FIRST, BUNDLE_OUT_DIR: buildDir }, stdio: 'pipe',
+ })
+ built = readFileSync(join(buildDir, 'cli.js'), 'utf8')
+ builtNotify = readFileSync(join(buildDir, 'notify.mjs'), 'utf8')
+ // The version is baked in at build time; the others are the same bytes with it swapped.
+ expect(count(built, FIRST)).toBeGreaterThanOrEqual(2)
+}, 180_000)
+
+afterAll(() => { if (buildDir) rmSync(buildDir, { recursive: true, force: true }) })
+
+/**
+ * Releases: the build at another version, with a fault put in at the top where a test needs one, and a
+ * notify.mjs of its own, so an install mixed from two releases shows.
+ */
+class Releases {
+ readonly cli = new Map<string, Buffer>()
+ readonly notify = new Map<string, Buffer>()
+ add(version: string, inject = ''): void {
+ const source = built.replaceAll(FIRST, version).replace('\n', `\n${inject}\n`)
+ const file = join(buildDir, `cli-${version}.js`)
+ writeFileSync(file, source)
+ expect(execFileSync(process.execPath, [file, 'version'], { encoding: 'utf8' }).trim()).toBe(version)
+ this.cli.set(version, Buffer.from(source))
+ this.notify.set(version, Buffer.from(`${builtNotify}\n// release ${version}\n`))
+ }
+}
+
+/** What a download of cli.js meets: cut short with a length to match, a connection that dies halfway
+ * through the length it promised, or a wait until the test lets it through. */
+type Fault = 'truncate' | 'drop' | 'hold'
+
+interface Offer {
+ version: string
+ /** Bytes served as this version's cli.js instead of its own: a release whose manifest lies about it. */
+ bytes?: Buffer
+ /** The sha256 the manifest names, when it is not that of the bytes served. */
+ manifestSha?: string
+}
+
+/** The release channel: a manifest naming one build, and the files it names, with the faults asked for. */
+class UpdateServer {
+ offer: Offer
+ /** What the next downloads of cli.js meet, one fault each. */
+ faults: Fault[] = []
+ /** Every download of a cli.js asked for, by version, in order. */
+ readonly downloads: string[] = []
+ private held: Array<() => void> = []
+ private server: Server | null = null
+
+ constructor(private readonly releases: Releases, first: string) { this.offer = { version: first } }
+
+ get origin(): string { return `http://127.0.0.1:${(this.server!.address() as { port: number }).port}` }
+ get holding(): number { return this.held.length }
+ downloadsOf(version: string): number { return this.downloads.filter((one) => one === version).length }
+
+ async start(): Promise<void> {
+ this.server = createServer((request, response) => this.answer(request.url ?? '', response))
+ await new Promise<void>((done) => this.server!.listen(0, '127.0.0.1', done))
+ }
+
+ stop(): Promise<void> {
+ this.release()
+ return new Promise((done) => this.server ? this.server.close(() => done()) : done())
+ }
+
+ /** Every held download goes through. */
+ release(): void {
+ const held = this.held
+ this.held = []
+ for (const go of held) go()
+ }
+
+ private bytesOf(version: string): Buffer {
+ return this.offer.version === version && this.offer.bytes ? this.offer.bytes : this.releases.cli.get(version)!
+ }
+
+ private answer(url: string, response: ServerResponse): void {
+ if (url === '/metadata.json') {
+ const { version } = this.offer
+ const cli = this.bytesOf(version)
+ const notify = this.releases.notify.get(version)!
+ response.end(JSON.stringify({ cli: {
+ version,
+ cli: { url: `${this.origin}/cli-${version}.js`, sha256: this.offer.manifestSha ?? sha(cli), size: cli.length },
+ notify: { url: `${this.origin}/notify-${version}.mjs`, sha256: sha(notify), size: notify.length },
+ } }))
+ return
+ }
+ const cliVersion = /^\/cli-(.+)\.js$/.exec(url)?.[1]
+ if (cliVersion && this.releases.cli.has(cliVersion)) {
+ this.downloads.push(cliVersion)
+ const bytes = this.bytesOf(cliVersion)
+ const half = bytes.subarray(0, bytes.length >> 1)
+ const fault = this.faults.shift()
+ if (fault === 'truncate') {
+ response.setHeader('content-length', half.length)
+ response.end(half)
+ } else if (fault === 'drop') {
+ response.setHeader('content-length', bytes.length)
+ response.write(half, () => setTimeout(() => response.socket?.destroy(), 20))
+ } else if (fault === 'hold') {
+ this.held.push(() => response.end(bytes))
+ } else {
+ response.end(bytes)
+ }
+ return
+ }
+ const notifyVersion = /^\/notify-(.+)\.mjs$/.exec(url)?.[1]
+ if (notifyVersion && this.releases.notify.has(notifyVersion)) { response.end(this.releases.notify.get(notifyVersion)); return }
+ response.statusCode = 404
+ response.end()
+ }
+}
+
+const rows = async (client: LocalClient): Promise<Row[]> =>
+ (await client.request<{ agents: Row[] }>('agents_list', { includeStopped: true }, 30_000)).agents
+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId
+async function turn(client: LocalClient, agentId: string, content: string): Promise<void> {
+ const started = client.next(isTurn('turn_started', agentId), 60_000, `turn_started (${content})`)
+ const ended = client.next(isTurn('turn_ended', agentId), 60_000, `turn_ended (${content})`)
+ client.send('message', { agentId, content })
+ expect((await started).payload?.userMessage).toBe(content)
+ await ended
+}
+
+/** A machine with a release installed, a daemon running it under harnessd, and two agents at work. */
+class Installed {
+ daemon!: IsolatedDaemon
+ agents: Row[] = []
+
+ constructor(readonly releases: Releases, readonly server: UpdateServer, readonly cliDir: string) {}
+
+ async boot(first: string, dataDir?: string): Promise<void> {
+ mkdirSync(this.cliDir, { recursive: true })
+ writeFileSync(join(this.cliDir, 'cli.js'), this.releases.cli.get(first)!)
+ writeFileSync(join(this.cliDir, 'notify.mjs'), this.releases.notify.get(first)!)
+ writeFileSync(join(this.cliDir, 'package.json'), '{"type":"module"}\n')
+ const local = this.server.origin
+ this.daemon = await IsolatedDaemon.create({
+ scriptPath: join(this.cliDir, 'cli.js'),
+ ...(dataDir ? { dataDir } : {}),
+ env: {
+ ADAPTER_CLI_DIR: this.cliDir,
+ ADAPTER_UPDATE_DISABLE: 'false',
+ ADAPTER_UPDATE_URL: `${local}/metadata.json`,
+ ADAPTER_UPDATE_CHECK_MS: '1000',
+ ADAPTER_UPDATE_SLOT_SEC: '-1',
+ HARNESSD_UPDATE_PROBATION_MS: '6000',
+ HARNESSD_INITIAL_BACKOFF_MS: '100',
+ // Every other download an installed daemon looks for stays on this machine too.
+ HARNESS_TUI_MANIFEST_URL: `${local}/tui/metadata.json`,
+ ADAPTER_RUNTIME_METADATA_URL: `${local}/runtime/metadata.json`,
+ ADAPTER_GRID_RUNTIME_METADATA_URL: `${local}/grid/metadata.json`,
+ },
+ })
+ await this.daemon.start()
+ expect(await this.status()).toMatchObject({ version: first, harnessd: { masterVersion: first } })
+ const client = await LocalClient.connect(this.daemon)
+ try {
+ for (const engine of ['claude', 'codex'] as const) {
+ const cwd = join(this.daemon.projectsDir, `hostile-${engine}`)
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ this.agents.push(await until(`${engine} to bind its conversation`, async () => {
+ const row = (await rows(client)).find((one) => one.id === created.agent.id)
+ return row?.sessionId && row.status === 'active' ? row : null
+ }, 90_000, 500))
+ }
+ // At work before any update: a daemon that has finished a turn has made the folders a turn's end
+ // writes to. (On a data folder that never had them, a turn ending while the disk is full is lost:
+ // the orchestrator's state folder cannot be made. Reported with round 40, not part of updating.)
+ for (const agent of this.agents) await turn(client, agent.id, `before any update (${agent.engine})`)
+ } finally { client.close() }
+ }
+
+ log(): string { return this.daemon.log() }
+ showLogOnFailure(): void {
+ onTestFailed(() => {
+ console.log(`---- daemon log\n${this.daemon?.log().split('\n').slice(-200).join('\n')}`)
+ // The runner keeps only so much: UPDATE_HOSTILE_LOG=<file> keeps the daemon's whole log for reading.
+ if (process.env.UPDATE_HOSTILE_LOG) writeFileSync(process.env.UPDATE_HOSTILE_LOG, this.daemon?.log() ?? '')
+ })
+ }
+
+ async status(): Promise<Row | null> {
+ return fetch(`http://127.0.0.1:${this.daemon.port}/api/status`).then((response) => response.json() as Promise<Row>).catch(() => null)
+ }
+
+ async version(): Promise<string | null> { return (await this.status())?.version ?? null }
+
+ /** The core runs `version`, ready, under a master that runs one of `masters`. */
+ on(version: string, masters: string[] = [version], ms = 150_000): Promise<Row> {
+ return until(`the core on ${version}, ready, under a master on ${masters.join(' or ')}`, async () => {
+ const now = await this.status()
+ return now?.version === version && now?.harnessd?.state === 'running' && masters.includes(now?.harnessd?.masterVersion) ? now : null
+ }, ms, 250)
+ }
+
+ /** Nothing is waiting to be kept or rolled back. */
+ judged(ms = 90_000): Promise<true> {
+ return until('the update to be kept or rolled back', () => !['update-pending.json', 'cli.js.prev', 'notify.mjs.prev'].some((name) => existsSync(join(this.cliDir, name))), ms, 250)
+ }
+
+ /** The install holds `version`'s own files, both of them. */
+ holds(version: string): void {
+ expect(sha(readFileSync(join(this.cliDir, 'cli.js'))), `cli.js is ${version}'s`).toBe(sha(this.releases.cli.get(version)!))
+ expect(sha(readFileSync(join(this.cliDir, 'notify.mjs'))), `notify.mjs is ${version}'s`).toBe(sha(this.releases.notify.get(version)!))
+ }
+
+ rejected(): string[] {
+ try { return JSON.parse(readFileSync(join(this.cliDir, 'update-rejected.json'), 'utf8')) as string[] } catch { return [] }
+ }
+
+ /** Whatever an update left in the install or the data folder that the next one could trip on. */
+ leftovers(): string[] {
+ const kept = new Set(['cli.js', 'notify.mjs', 'package.json', 'update-rejected.json'])
+ const install = readdirSync(this.cliDir).filter((name) => !kept.has(name)).map((name) => `install: ${name}`)
+ const data = readdirSync(this.daemon.dataDir).filter((name) => name.startsWith('harnessd-reexec.json') || name === 'adapter.spawn.lock')
+ .map((name) => `data: ${name}`)
+ return [...install, ...data]
+ }
+
+ /** Both agents are back on their own conversations, and each takes a turn. */
+ async agentsBack(label: string): Promise<void> {
+ const client = await LocalClient.connect(this.daemon)
+ try {
+ for (const agent of this.agents) {
+ await until(`the ${agent.engine} agent back on its conversation`, async () => {
+ const row = (await rows(client)).find((one) => one.id === agent.id)
+ return row?.status === 'active' && row.sessionId === agent.sessionId ? row : null
+ }, 90_000, 500)
+ await turn(client, agent.id, `${label} (${agent.engine})`)
+ }
+ } finally { client.close() }
+ }
+
+ /** Every process running a build of this install, from the process table. */
+ daemonProcesses(): Array<{ pid: number; ppid: number; command: string }> {
+ return execFileSync('ps', ['-axo', 'pid=,ppid=,command='], { encoding: 'utf8' }).split('\n')
+ .map((line) => /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line))
+ .filter((match): match is RegExpExecArray => !!match && match[3].includes(join(this.cliDir, 'cli.js')))
+ .map((match) => ({ pid: Number(match[1]), ppid: Number(match[2]), command: match[3] }))
+ }
+
+ /** One core, the master's child, and nothing else running this install: no orphan, no probe left. */
+ async nothingOrphaned(): Promise<void> {
+ const master = this.daemon.pid!
+ await until('only the master\'s own core', () => this.daemonProcesses().every((one) => one.ppid === master && one.command.endsWith(' __run')), 15_000, 200)
+ expect(this.daemonProcesses().filter((one) => one.command.endsWith(' __run'))).toHaveLength(1)
+ }
+
+ /** What every scenario ends in: one build installed and running under its master, every agent back,
+ * nothing in between left behind, and exactly these builds remembered as rolled back. */
+ async settled(version: string, expected: { masters?: string[]; rejected: string[] }): Promise<void> {
+ await this.on(version, expected.masters)
+ await this.judged()
+ this.holds(version)
+ expect(this.leftovers()).toEqual([])
+ expect(this.rejected()).toEqual(expected.rejected)
+ await this.agentsBack(`settled on ${version}`)
+ await this.nothingOrphaned()
+ }
+}
+
+describe('an update under hostile conditions', () => {
+ const releases = new Releases()
+ let server: UpdateServer
+ let scratch = ''
+ let machine: Installed
+
+ beforeAll(async () => {
+ for (let patch = 1; patch <= 12; patch++) releases.add(`43.0.${patch}`, patch === 10 || patch === 11 ? CRASHES_AS_A_CORE : '')
+ scratch = mkdtempSync(join(tmpdir(), 'harnessd-hostile-'))
+ server = new UpdateServer(releases, FIRST)
+ await server.start()
+ machine = new Installed(releases, server, join(scratch, 'cli'))
+ await machine.boot(FIRST)
+ }, 300_000)
+
+ afterAll(async () => {
+ await machine?.daemon?.close()
+ await server?.stop()
+ if (scratch) rmSync(scratch, { recursive: true, force: true })
+ })
+
+ it('a link that drops mid-download: nothing is written, and the build lands once the link holds', async () => {
+ machine.showLogOnFailure()
+ const from = machine.log().length
+ server.faults = ['drop', 'drop', 'drop']
+ server.offer = { version: '43.0.2' }
+ await until('three downloads dropped halfway', () => server.downloadsOf('43.0.2') >= 3, 90_000)
+ expect(await machine.version()).toBe(FIRST)
+ machine.holds(FIRST)
+ await machine.settled('43.0.2', { rejected: [] })
+ expect(machine.log().slice(from)).toContain('[update] check failed (will retry)')
+ }, 300_000)
+
+ it('a download cut short is refused, and the whole build lands', async () => {
+ machine.showLogOnFailure()
+ const from = machine.log().length
+ server.faults = ['truncate', 'truncate']
+ server.offer = { version: '43.0.3' }
+ await until('two downloads cut short', () => server.downloadsOf('43.0.3') >= 2, 90_000)
+ expect(await machine.version()).toBe('43.0.2')
+ await machine.settled('43.0.3', { rejected: [] })
+ expect(machine.log().slice(from)).toContain('sha256 mismatch')
+ }, 300_000)
+
+ /** A build that cannot be installed must cost one download now and then, not one at every check. */
+ const refusedQuietly = async (version: string): Promise<void> => {
+ const cores = machine.daemon.coresStarted()
+ await until(`a download of ${version}`, () => server.downloadsOf(version) >= 1, 90_000)
+ await sleep(12_000)
+ expect(machine.daemon.coresStarted(), 'no restart for a build that cannot be installed').toBe(cores)
+ expect(await machine.version()).toBe('43.0.3')
+ machine.holds('43.0.3')
+ expect(machine.leftovers()).toEqual([])
+ expect(server.downloadsOf(version), 'a check a second, and only a handful of downloads').toBeLessThanOrEqual(5)
+ }
+
+ it('a release published broken (its manifest names the cut-short bytes) fails its canary, is never staged, and is not downloaded at every check', async () => {
+ machine.showLogOnFailure()
+ const whole = releases.cli.get('43.0.4')!
+ server.offer = { version: '43.0.4', bytes: whole.subarray(0, whole.length >> 1) }
+ await refusedQuietly('43.0.4')
+ }, 300_000)
+
+ it('a manifest whose hash lies is refused, without a download at every check', async () => {
+ machine.showLogOnFailure()
+ server.offer = { version: '43.0.5', manifestSha: sha(Buffer.from('not what is served')) }
+ await refusedQuietly('43.0.5')
+ }, 300_000)
+
+ it('a manifest whose version lies (it names the bytes of the build running) does not restart the daemon over and over', async () => {
+ machine.showLogOnFailure()
+ server.offer = { version: '43.0.6', bytes: releases.cli.get('43.0.3') }
+ await refusedQuietly('43.0.6')
+ }, 300_000)
+
+ it('a newer build published while the last is on probation: two checks race the master, and the newest is kept, nothing rejected', async () => {
+ machine.showLogOnFailure()
+ const from = machine.log().length
+ server.offer = { version: '43.0.7' }
+ await until('the core on 43.0.7', async () => (await machine.version()) === '43.0.7', 150_000, 100)
+ // Its probation has six seconds to run, and its updater checks every second.
+ expect(existsSync(join(machine.cliDir, 'update-pending.json'))).toBe(true)
+ server.offer = { version: '43.0.8' }
+ await machine.settled('43.0.8', { rejected: [] })
+ expect(machine.log().slice(from)).toContain('[harnessd] the updated core staged a newer build before it was kept')
+ expect(machine.log().slice(from)).not.toContain('the updated core failed')
+ }, 300_000)
+
+ it('an update while both agents are mid-turn: their turns finish, both are back, and the next turns work', async () => {
+ machine.showLogOnFailure()
+ const client = await LocalClient.connect(machine.daemon)
+ for (const agent of machine.agents) {
+ const started = client.next(isTurn('turn_started', agent.id), 60_000, `the long turn of ${agent.engine}`)
+ client.send('message', { agentId: agent.id, content: '!slow 15000' })
+ await started
+ }
+ server.offer = { version: '43.0.9' }
+ await machine.on('43.0.9')
+ client.close()
+ // The turns were running in their panes through the swap; the core on the new build reads how they end.
+ const after = await LocalClient.connect(machine.daemon)
+ try {
+ for (const agent of machine.agents) {
+ const ended = after.frames.find(isTurn('turn_ended', agent.id)) ?? await after.waitFor(isTurn('turn_ended', agent.id), 120_000, `the long turn of ${agent.engine} to end`)
+ expect(ended).toBeTruthy()
+ }
+ const now = await rows(after)
+ for (const agent of machine.agents) expect(now.find((one) => one.id === agent.id)?.activity?.state, `${agent.engine} is not left working`).not.toBe('working')
+ } finally { after.close() }
+ await machine.settled('43.0.9', { rejected: [] })
+ }, 300_000)
+
+ it('a build whose master answers its probe but whose core crashes at start is rolled back and remembered, and the master goes back with it', async () => {
+ machine.showLogOnFailure()
+ const from = machine.log().length
+ server.offer = { version: '43.0.10' }
+ await until('the rollback', () => machine.log().slice(from).includes('the updated core failed (code 3) — rolled back'), 150_000)
+ expect(machine.log().slice(from)).toContain(`master re-executed (pid ${machine.daemon.pid}) · now v43.0.10`)
+ await machine.settled('43.0.9', { rejected: ['43.0.10'] })
+ const cores = machine.daemon.coresStarted()
+ await sleep(5_000)
+ expect(machine.daemon.coresStarted()).toBe(cores)
+ expect(server.downloadsOf('43.0.10')).toBe(1)
+ }, 300_000)
+
+ it('the master killed mid-update, as a power cut would: the next start judges the build it finds staged, and rolls back one whose core crashes', async () => {
+ machine.showLogOnFailure()
+ const from = machine.log().length
+ server.offer = { version: '43.0.11' }
+ await until('the core to stage 43.0.11', () => machine.log().slice(from).includes('[update] staged 43.0.11'), 90_000)
+ const core = machine.daemon.corePid()
+ await machine.daemon.kill()
+ await until('the core it was running to be gone', () => !IsolatedDaemon.alive(core), 30_000, 100)
+ machine.holds('43.0.11')
+ // What launchd restarting the master, or the desktop app's `harness start`, does.
+ const restart = machine.log().length
+ await machine.daemon.start()
+ await machine.settled('43.0.9', { rejected: ['43.0.10', '43.0.11'] })
+ expect(machine.log().slice(restart)).toContain('[harnessd] the bundle on disk is 43.0.11, an update no master kept or rolled back — its first core is on probation')
+ expect(machine.log().slice(restart)).toContain('the updated core failed (code 3) — rolled back')
+ }, 300_000)
+
+ it('moves on when a newer build is published', async () => {
+ machine.showLogOnFailure()
+ server.offer = { version: '43.0.12' }
+ await machine.settled('43.0.12', { rejected: ['43.0.10', '43.0.11'] })
+ }, 300_000)
+})
+
+describe.skipIf(!DISKFULL)('an update on a disk that fills', () => {
+ const releases = new Releases()
+ let server: UpdateServer
+ let scratch = ''
+ let volume = ''
+ let machine: Installed
+ const filler = () => join(volume, 'filler')
+ const lock = () => join(machine.daemon.dataDir, 'adapter.spawn.lock')
+
+ /** Writes until the volume refuses. */
+ const fill = (): void => {
+ const fd = openSync(filler(), 'a')
+ const chunk = Buffer.alloc(1024 * 1024, 7)
+ try { for (;;) writeSync(fd, chunk) } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOSPC') throw error } finally { closeSync(fd) }
+ // The last blocks a metadata write may still find: take those too.
+ const tail = openSync(join(volume, 'filler-tail'), 'a')
+ try { for (;;) writeSync(tail, Buffer.alloc(4096, 7)) } catch { /* full */ } finally { closeSync(tail) }
+ }
+ /** Gives back this much room. */
+ const room = (bytes: number): void => {
+ rmSync(join(volume, 'filler-tail'), { force: true })
+ truncateSync(filler(), Math.max(0, statSync(filler()).size - bytes))
+ }
+ const unfill = (): void => {
+ rmSync(filler(), { force: true })
+ rmSync(join(volume, 'filler-tail'), { force: true })
+ }
+ /** Holds the daemon spawn lock as a `harness start` would: the updater waits for it with its build verified. */
+ const holdLock = (): void => {
+ mkdirSync(lock(), { mode: 0o700 })
+ writeFileSync(join(lock(), 'owner.json'), JSON.stringify({ pid: process.pid, startMarker: '', token: 'e2e-update-hostile', purpose: 'start', since: Date.now() }), { mode: 0o600 })
+ }
+ const releaseLock = (): void => { rmSync(lock(), { recursive: true, force: true }) }
+
+ beforeAll(async () => {
+ for (let patch = 1; patch <= 5; patch++) releases.add(`44.0.${patch}`, patch === 5 ? CRASHES_AS_A_CORE : '')
+ // Short names: the daemon's socket lives in the data folder, and a Unix socket's path has a
+ // 104-byte limit on macOS that a long temporary folder alone nearly uses up.
+ scratch = mkdtempSync(join(tmpdir(), 'hu-'))
+ volume = join(scratch, 'v')
+ mkdirSync(volume)
+ const image = join(scratch, 'u.dmg')
+ execFileSync('hdiutil', ['create', '-size', '96m', '-fs', 'HFS+', '-volname', 'hutest', '-type', 'UDIF', image], { stdio: 'pipe' })
+ execFileSync('hdiutil', ['attach', image, '-mountpoint', volume, '-nobrowse', '-noverify', '-noautoopen'], { stdio: 'pipe' })
+ server = new UpdateServer(releases, '44.0.1')
+ await server.start()
+ machine = new Installed(releases, server, join(volume, 'c'))
+ const data = join(volume, 'd')
+ mkdirSync(data)
+ await machine.boot('44.0.1', data)
+ }, 300_000)
+
+ // A scenario that fails part way must not leave the next one a full disk or a held lock.
+ afterEach(() => {
+ try { unfill() } catch { /* not mounted */ }
+ if (machine?.daemon) { try { if (readFileSync(join(lock(), 'owner.json'), 'utf8').includes('e2e-update-hostile')) releaseLock() } catch { /* not held */ } }
+ })
+
+ afterAll(async () => {
+ try { unfill() } catch { /* not mounted */ }
+ if (process.env.UPDATE_HOSTILE_LOG && machine?.daemon) writeFileSync(process.env.UPDATE_HOSTILE_LOG, machine.daemon.log())
+ await machine?.daemon?.close()
+ await server?.stop()
+ if (volume) { try { execFileSync('hdiutil', ['detach', volume, '-force'], { stdio: 'pipe' }) } catch { /* already gone */ } }
+ if (scratch) rmSync(scratch, { recursive: true, force: true })
+ })
+
+ it('the disk fills while the build downloads: the canary cannot be written, nothing is left, the agents keep working, and the build lands once there is room', async () => {
+ machine.showLogOnFailure()
+ const from = machine.log().length
+ server.faults = ['hold']
+ server.offer = { version: '44.0.2' }
+ await until('the download to be under way', () => server.holding === 1, 90_000)
+ fill()
+ server.release()
+ await until('the canary to fail on the full disk', () => /\[update\][^\n]*canary/.test(machine.log().slice(from)), 60_000)
+ await sleep(3_000)
+ expect(await machine.version()).toBe('44.0.1')
+ machine.holds('44.0.1')
+ expect(machine.leftovers()).toEqual([])
+ await machine.agentsBack('while the disk is full')
+ unfill()
+ await machine.settled('44.0.2', { rejected: [] })
+ }, 400_000)
+
+ it('the disk fills between the canary and the swap: the install is left as it was, the spawn lock is not left behind, and the build lands once there is room', async () => {
+ machine.showLogOnFailure()
+ const from = machine.log().length
+ holdLock()
+ server.offer = { version: '44.0.3' }
+ await until('the updater to wait for the lock with the build verified', () => machine.log().slice(from).includes('[update] waiting — the daemon is'), 90_000)
+ fill()
+ releaseLock()
+ await until('a swap to fail on the full disk', () => count(machine.log().slice(from), '[update] check failed') >= 1, 60_000)
+ // Room for the lock and part of one copy of the bundle, not all of it.
+ room(3 * 1024 * 1024)
+ const second = machine.log().length
+ await until('another swap to fail', () => count(machine.log().slice(second), '[update] check failed') >= 1, 60_000)
+ await until('the updater to let go of the lock', () => !existsSync(lock()), 30_000, 50)
+ // Held again, so nothing is mid-write while the install is looked at.
+ holdLock()
+ try {
+ machine.holds('44.0.2')
+ expect(machine.leftovers().filter((one) => one !== 'data: adapter.spawn.lock')).toEqual([])
+ } finally { releaseLock() }
+ unfill()
+ await machine.settled('44.0.3', { rejected: [] })
+ }, 400_000)
+
+ it('the disk fills just after the swap: the master outlives it, and the daemon is back on a working build, the new one kept or the old one with the new remembered', async () => {
+ machine.showLogOnFailure()
+ const from = machine.log().length
+ const master = machine.daemon.pid
+ server.offer = { version: '44.0.4' }
+ await until('the core to stage 44.0.4', () => machine.log().slice(from).includes('[update] staged 44.0.4'), 90_000, 50)
+ fill()
+ // A core cannot open its socket on a full disk (listen ENOSPC): one started on the new bundle comes up
+ // in safe mode, and the master rolls the update back, the rollback itself freeing the room the build
+ // before needs. One that came up before the disk filled stays up and is kept.
+ await until('the update to be kept or rolled back on the full disk', () => /the update stayed up — keeping it|the updated core failed[^\n]*rolled back/.test(machine.log().slice(from)), 150_000, 100)
+ expect(IsolatedDaemon.alive(master), 'the master outlives a full disk in the middle of an update').toBe(true)
+ unfill()
+ if (machine.log().slice(from).includes('the update stayed up — keeping it')) await machine.settled('44.0.4', { masters: ['44.0.3', '44.0.4'], rejected: [] })
+ else await machine.settled('44.0.3', { masters: ['44.0.3', '44.0.4'], rejected: ['44.0.4'] })
+ expect(machine.daemon.pid).toBe(master)
+ }, 400_000)
+
+ it('a build that crashes on a full disk is rolled back and remembered, and never staged again', async () => {
+ machine.showLogOnFailure()
+ const from = machine.log().length
+ const before = (await machine.version())!
+ const rejectedBefore = machine.rejected()
+ server.offer = { version: '44.0.5' }
+ await until('the core to stage 44.0.5', () => machine.log().slice(from).includes('[update] staged 44.0.5'), 90_000, 50)
+ fill()
+ await until('the rollback', () => machine.log().slice(from).includes('the updated core failed (code 3) — rolled back'), 150_000)
+ await until(`the core back on ${before}`, async () => (await machine.version()) === before, 150_000, 250)
+ unfill()
+ await machine.settled(before, { masters: ['44.0.3', '44.0.4'], rejected: [...rejectedBefore, '44.0.5'] })
+ await sleep(5_000)
+ expect(server.downloadsOf('44.0.5')).toBe(1)
+ }, 400_000)
+})
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 139068eff..b657f3308 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -217,7 +217,7 @@ import { DeviceLogSyncer, type DeviceLogFetched } from './lib/e2ee/deviceLogSync
import { DeviceLogStore } from './lib/e2ee/deviceLogStore.js'
import { TrustGroupStore, type GroupMember } from './lib/e2ee/trustGroup.js'
import {
- startSelfUpdater, restore as restoreUpdate, confirm as confirmUpdate,
+ startSelfUpdater, restore as restoreUpdate, confirm as confirmUpdate, unjudgedUpdate,
fetchManifest, downloadVerified, canary, stage, semverGt, isLocalDevBuild,
type Poller, type UpdateEntry,
} from './lib/selfUpdate.js'
@@ -1385,7 +1385,7 @@ const RESOLVE_ON_START_TIMEOUT_MS = 10_000
async function downloadCanaryStage(entry: UpdateEntry, dir: string, log: (m: string) => void): Promise<boolean> {
const cliBuf = await downloadVerified(entry.cli)
const notifyBuf = await downloadVerified(entry.notify)
- if (!canary(cliBuf, dir)) { log(` ✗ the new build failed its self-check — keeping v${VERSION}`); return false }
+ if (!canary(cliBuf, dir, entry.version)) { log(` ✗ the new build failed its self-check — keeping v${VERSION}`); return false }
// Asked for by name, so a version this machine once rolled back is installed and no longer rejected.
stage(dir, cliBuf, notifyBuf, entry.version)
confirmUpdate(dir) // canary passed + bytes already verified ⇒ drop the .prev backups
@@ -5522,6 +5522,7 @@ switch (cmd) {
confirmUpdate: () => confirmUpdate(env.ADAPTER_CLI_DIR),
version: VERSION,
reexecMarkerFile: HARNESSD_REEXEC_FILE,
+ unjudgedUpdate: (bundle) => unjudgedUpdate(env.ADAPTER_CLI_DIR, bundle),
})
break
case '__harnessd-probe': // internal: a master about to re-execute on this bundle asks it first (harnessd/reexec.ts)
diff --git a/cli/src/harnessd/master.spec.ts b/cli/src/harnessd/master.spec.ts
index 87a37e5e9..49db5673e 100644
--- a/cli/src/harnessd/master.spec.ts
+++ b/cli/src/harnessd/master.spec.ts
@@ -536,6 +536,42 @@ describe('runMaster', () => {
await master.stop()
})
+ it('judges, when it starts fresh, an update on disk that no master kept or rolled back: kept once its core stays up, rolled back when it crashes', async () => {
+ const lines: string[] = []
+ const log = vi.spyOn(console, 'log').mockImplementation((line: string) => { lines.push(line) })
+ try {
+ const good = bundle('')
+ const asked: Array<string | null> = []
+ const kept = start(good, { reexecMarkerFile: undefined, unjudgedUpdate: (fingerprintOnDisk: string | null) => { asked.push(fingerprintOnDisk); return '2.0.0' } })
+ await until('the update to be kept', () => kept.calls.includes('confirm'))
+ expect(asked).toEqual([fingerprint(good)])
+ expect(lines.some((line) => line.endsWith('[harnessd] the bundle on disk is 2.0.0, an update no master kept or rolled back — its first core is on probation'))).toBe(true)
+ await kept.stop()
+
+ const crashing = start(bundle('process.exit(3)'), { reexecMarkerFile: undefined, unjudgedUpdate: () => '2.0.1' })
+ await until('the update to be rolled back', () => crashing.calls.includes('restore'))
+ expect(crashing.calls).toEqual(['restore'])
+ await crashing.stop()
+
+ // Nothing unjudged: a core like any other.
+ const plain = start(bundle(''), { reexecMarkerFile: undefined, unjudgedUpdate: () => null })
+ await until('its core', () => plain.supervisor.status().state === 'running')
+ await new Promise((resolve) => setTimeout(resolve, 200))
+ expect(plain.calls).toEqual([])
+ await plain.stop()
+ } finally { log.mockRestore() }
+ })
+
+ it('judges the newer build a core on probation staged, instead of rolling it back as a failure', async () => {
+ // Its first core stages a build and exits for the update; the next, on probation, stages another before it is kept.
+ const script = bundle(`if (process.env.HARNESSD_RESTARTS !== '2') setTimeout(() => { fs.appendFileSync(__filename, '\\n// a newer build\\n'); process.exit(75) }, process.env.HARNESSD_RESTARTS === '0' ? 100 : 20)`)
+ const master = start(script, { reexecMarkerFile: undefined })
+ await until('the newest build to be kept', () => master.calls.includes('confirm'))
+ expect(master.calls).toEqual(['confirm'])
+ expect(master.supervisor.status()).toMatchObject({ state: 'running', restarts: 2 })
+ await master.stop()
+ })
+
it('removes its marker once its core is up, and leaves alone what it does not judge', async () => {
const script = bundle('')
writeMarker(marker(), { pid: process.pid, from: 'the one before', to: fingerprint(script)!, at: 1 })
diff --git a/cli/src/harnessd/master.ts b/cli/src/harnessd/master.ts
index 769959763..648d567c4 100644
--- a/cli/src/harnessd/master.ts
+++ b/cli/src/harnessd/master.ts
@@ -46,6 +46,9 @@ export interface MasterConfig {
reexecMarkerFile?: string
/** Replace this process (`process.execve`); defaults to this Node's, null where it has none. */
execve?: Execve | null
+ /** The version of the update the bundle with this fingerprint is, when it is one no master kept or
+ * rolled back (`selfUpdate.unjudgedUpdate`); null otherwise. Left out, never. */
+ unjudgedUpdate?: (bundle: string | null) => string | null
}
export type Execve = (file: string, args: string[], env: NodeJS.ProcessEnv) => void
@@ -245,6 +248,10 @@ export function runMaster(config: MasterConfig): Supervisor {
restoreUpdate: config.restoreUpdate, removeMarker: () => removeMarker(markerFile), log,
})
}
+ // Started fresh on an update the master judging it never finished with (it died: a crash, a kill, a
+ // power cut): this master judges it. A re-executed master was handed its own.
+ const unjudged = resume ? null : config.unjudgedUpdate?.(own) ?? null
+ if (unjudged) log(`[harnessd] the bundle on disk is ${unjudged}, an update no master kept or rolled back — its first core is on probation`)
let stopping = false
// A new one every boot, given to the core and to each service: how the core knows a service
// connection is one this master started, and no other local process.
@@ -286,6 +293,7 @@ export function runMaster(config: MasterConfig): Supervisor {
releasePidFile: () => { if (readPid() === process.pid) rmSync(config.pidFile, { force: true }) },
restoreUpdate: config.restoreUpdate,
confirmUpdate: config.confirmUpdate,
+ bundle,
log,
// The services go with the master, after the core: none is left holding the core's socket.
exit: (code) => {
@@ -301,7 +309,7 @@ export function runMaster(config: MasterConfig): Supervisor {
// The re-executed master has brought a core up: its marker has served.
coreUp: () => removeMarker(markerFile),
} : {}),
- }, options, { version: config.version, resume })
+ }, options, { version: config.version, resume, unjudgedUpdate: unjudged })
// Services stop beside the core, inside the same grace `harness stop` gives the whole daemon.
for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const) {
onSignal(signal, () => {
diff --git a/cli/src/harnessd/reexec.spec.ts b/cli/src/harnessd/reexec.spec.ts
index aaffa5e21..c1d67bf6b 100644
--- a/cli/src/harnessd/reexec.spec.ts
+++ b/cli/src/harnessd/reexec.spec.ts
@@ -253,6 +253,23 @@ describe('re-executing', () => {
expect(calls).toContain('[harnessd] could not re-execute this master (odd) — keeping it')
})
+ it('carries on as itself, and does not end, when its marker cannot be written (a full disk)', async () => {
+ const full = make({ writeMarker: () => { throw new Error('ENOSPC: no space left on device, write') } })
+ full.reexec(state(), (outcome) => outcomes.push(outcome))
+ stopped[0]()
+ await settle({ ok: true, detail: PROBE_ANSWER })
+ expect(execs).toEqual([])
+ expect(outcomes).toEqual(['kept'])
+ expect(calls.slice(-2)).toEqual(['[harnessd] could not leave the re-execution marker (ENOSPC: no space left on device, write) — keeping this master', 'start children'])
+
+ const odd = make({ writeMarker: () => { throw 'read-only' } })
+ odd.reexec(state(), (outcome) => outcomes.push(outcome))
+ stopped[1]()
+ await settle({ ok: true, detail: PROBE_ANSWER })
+ expect(outcomes).toEqual(['kept', 'kept'])
+ expect(calls).toContain('[harnessd] could not leave the re-execution marker (read-only) — keeping this master')
+ })
+
it('does nothing more once the master is stopping, at any step, and abandons its probe', async () => {
const first = make()
first.reexec(state(), (outcome) => outcomes.push(outcome))
diff --git a/cli/src/harnessd/reexec.ts b/cli/src/harnessd/reexec.ts
index 70d34ce71..828809e7e 100644
--- a/cli/src/harnessd/reexec.ts
+++ b/cli/src/harnessd/reexec.ts
@@ -234,7 +234,17 @@ export function createReexec(deps: ReexecDeps): {
carryOn('refused')
return
}
- deps.writeMarker({ pid: deps.pid, from: deps.own, to: next, at: now })
+ try {
+ deps.writeMarker({ pid: deps.pid, from: deps.own, to: next, at: now })
+ } catch (error) {
+ // A full disk (e2e/updateHostile.e2e.ts). Thrown from here, it was a rejection nothing handles,
+ // which ends a master that has no core and no services running at this point. Without the
+ // marker a re-execution that never came up would be taken for one in progress, so this master
+ // keeps its code and starts the core on the new bundle itself, judging it as every update.
+ deps.log(`[harnessd] could not leave the re-execution marker (${error instanceof Error ? error.message : String(error)}) — keeping this master`)
+ carryOn('kept')
+ return
+ }
try {
// Never returns: from here this process is the new bundle's master, with the same pid.
deps.execve!(deps.nodePath, [deps.nodePath, ...args, '__harnessd'], env)
diff --git a/cli/src/harnessd/supervisor.spec.ts b/cli/src/harnessd/supervisor.spec.ts
index 13de403af..99b9b5eae 100644
--- a/cli/src/harnessd/supervisor.spec.ts
+++ b/cli/src/harnessd/supervisor.spec.ts
@@ -482,6 +482,82 @@ describe('Supervisor', () => {
expect(calls).toEqual(['claim', 'restore'])
})
+ it('judges the newer build a core on probation staged, instead of rolling it back as a failure', () => {
+ let disk = 'v1'
+ const supervisor = make({}, { bundle: () => disk })
+ supervisor.start()
+ core().up()
+ disk = 'v2'
+ core().exit(CORE_EXIT_UPDATE)
+ vi.advanceTimersByTime(0)
+ core().up()
+ vi.advanceTimersByTime(options.updateProbationMs - 1)
+ // v2, on probation, finds v3 and stages it.
+ disk = 'v3'
+ core().exit(CORE_EXIT_UPDATE)
+ expect(calls).toEqual(['claim'])
+ expect(lines.at(-1)).toBe(`[harnessd] the updated core staged a newer build before it was kept (code ${CORE_EXIT_UPDATE}) — restarting onto that one`)
+ vi.advanceTimersByTime(0)
+ expect(cores).toHaveLength(3)
+ core().up()
+ vi.advanceTimersByTime(options.updateProbationMs)
+ expect(calls).toEqual(['claim', 'confirm'])
+ expect(supervisor.status()).toMatchObject({ state: 'running', restarts: 2, lastExitReason: 'update' })
+ })
+
+ it('judges the newer build a core still starting on an update staged, and rolls that one back if it fails', () => {
+ let disk = 'v1'
+ make({}, { bundle: () => disk }).start()
+ core().up()
+ disk = 'v2'
+ core().exit(CORE_EXIT_UPDATE)
+ vi.advanceTimersByTime(0)
+ core().bind()
+ disk = 'v3'
+ core().exit(CORE_EXIT_UPDATE)
+ expect(calls).toEqual(['claim'])
+ vi.advanceTimersByTime(0)
+ core().exit(1)
+ expect(calls).toEqual(['claim', 'restore'])
+ })
+
+ it('rolls back an update whose core exits for an update without a newer bundle on disk, or one it cannot read', () => {
+ for (const after of ['v2', null]) {
+ calls = []
+ let disk: string | null = 'v1'
+ make({}, { bundle: () => disk }).start()
+ core().up()
+ disk = 'v2'
+ core().exit(CORE_EXIT_UPDATE)
+ vi.advanceTimersByTime(0)
+ core().up()
+ disk = after
+ core().exit(CORE_EXIT_UPDATE)
+ expect(calls, String(after)).toEqual(['claim', 'restore'])
+ }
+ })
+
+ it('judges, from its first core, an update it starts on that no master kept or rolled back', () => {
+ make({}, {}, { unjudgedUpdate: '9.9.9' }).start()
+ core().up()
+ vi.advanceTimersByTime(options.updateProbationMs - 1)
+ expect(calls).toEqual(['claim'])
+ vi.advanceTimersByTime(1)
+ expect(calls).toEqual(['claim', 'confirm'])
+
+ calls = []
+ make({}, {}, { unjudgedUpdate: '9.9.9' }).start()
+ core().exit(3)
+ expect(calls).toEqual(['restore'])
+
+ // A master handed its state by the one it replaced carries that one's judgement instead.
+ calls = []
+ make({}, {}, { unjudgedUpdate: '9.9.9', resume: { restarts: 0, lastExit: null, lastExitReason: null, update: null, claimed: true, reexecs: 1, unproven: 1 } }).start()
+ core().up()
+ vi.advanceTimersByTime(options.updateProbationMs)
+ expect(calls).toEqual([])
+ })
+
it('leaves the update unconfirmed when stopped while on probation', () => {
const supervisor = make()
supervisor.start()
diff --git a/cli/src/harnessd/supervisor.ts b/cli/src/harnessd/supervisor.ts
index 966eca7c2..15b85d1ca 100644
--- a/cli/src/harnessd/supervisor.ts
+++ b/cli/src/harnessd/supervisor.ts
@@ -57,6 +57,12 @@ export interface SupervisorDeps {
reexec?(state: ResumeState, proceed: (outcome: ReexecOutcome) => void): void
/** A core is up: ready, or bound for a protocol 1 core. A re-executed master has proved itself. */
coreUp?(): void
+ /**
+ * The bundle on disk now (its sha256, ./reexec.ts `fingerprint`), or null when it cannot be read: a
+ * core judged on an update that exits for another has staged a newer bundle only if this changed
+ * since it started. Left out, such an exit is the update failing, as it was before.
+ */
+ bundle?(): string | null
}
/**
@@ -89,6 +95,14 @@ export type ReexecOutcome = 'same' | 'kept' | 'refused'
export interface SupervisorIdentity {
version?: string
resume?: ResumeState | null
+ /**
+ * The bundle this master starts on is an update no master kept or rolled back (the version it names,
+ * `selfUpdate.unjudgedUpdate`): the master judging it died first (a crash, a kill, a power cut). Its
+ * first core is on probation, as it would have been. Before, a fresh master ran it unwatched, and a
+ * build whose core crashed at start crash-looped for good (e2e/updateHostile.e2e.ts). Ignored when
+ * `resume` is given: a re-executed master carries its own.
+ */
+ unjudgedUpdate?: string | null
}
export interface SupervisorOptions {
@@ -198,6 +212,8 @@ export class Supervisor {
private readonly masterVersion: string | null
private reexecs = 0
private unproven = 0
+ /** The bundle on disk when the running core was started (`deps.bundle`). */
+ private spawnedOn: string | null = null
constructor(
private readonly deps: SupervisorDeps,
@@ -218,6 +234,8 @@ export class Supervisor {
this.claimed = resume.claimed
this.reexecs = resume.reexecs
this.unproven = resume.unproven
+ } else if (identity.unjudgedUpdate) {
+ this.update = 'pending'
}
}
@@ -312,6 +330,7 @@ export class Supervisor {
}
if (this.lastExit) env.HARNESSD_LAST_EXIT = this.lastExit
if (this.safeMode) env.HARNESSD_SAFE_MODE = this.safeMode
+ this.spawnedOn = this.deps.bundle?.() ?? null
const core = this.deps.spawnCore(env)
this.core = core
core.onMessage((message) => { if (this.core === core && isCoreMessage(message)) this.onMessage(core, message) })
@@ -412,7 +431,13 @@ export class Supervisor {
this.lastExit = exit
this.lastExitReason = reason
this.restarts++
- if (this.update) {
+ // A core still being judged on an update that exits for another has staged a newer bundle: the
+ // build it ran came up far enough to find the next and stage it, and the next is judged on its own.
+ // Read as the update failing, the newer build was rolled back and remembered as bad on every machine
+ // that found it while the one before was on probation (e2e/updateHostile.e2e.ts: a fix published
+ // moments after the release it fixes).
+ const superseded = this.update !== null && reason === 'update' && this.stagedSinceSpawn()
+ if (this.update && !superseded) {
// The core on the new bundle did not come up, or did not stay up: the bundle before it did.
this.update = null
this.deps.restoreUpdate()
@@ -434,7 +459,9 @@ export class Supervisor {
this.update = 'pending'
this.crashes = []
this.safeMode = null
- this.deps.log(`[harnessd] core exited (${exit}) for an update — restarting`)
+ this.deps.log(superseded
+ ? `[harnessd] the updated core staged a newer build before it was kept (${exit}) — restarting onto that one`
+ : `[harnessd] core exited (${exit}) for an update — restarting`)
this.scheduleSpawn(0)
return
}
@@ -460,6 +487,12 @@ export class Supervisor {
this.scheduleSpawn(delay)
}
+ /** Whether the bundle on disk changed since the running core was started (`deps.bundle`). */
+ private stagedSinceSpawn(): boolean {
+ const now = this.deps.bundle?.() ?? null
+ return now !== null && now !== this.spawnedOn
+ }
+
private scheduleSpawn(delay: number): void {
this.setState('restarting')
this.armTimer('restartTimer', () => { this.restartTimer = null; this.next() }, delay)
diff --git a/cli/src/lib/daemonSpawnLock.spec.ts b/cli/src/lib/daemonSpawnLock.spec.ts
index f83aa1960..76a24edae 100644
--- a/cli/src/lib/daemonSpawnLock.spec.ts
+++ b/cli/src/lib/daemonSpawnLock.spec.ts
@@ -149,6 +149,46 @@ describe('daemon spawn lock', () => {
release()
})
+ it('reclaims a lock whose owner record names no one (cut short by a crash or a full disk) once it is debris', async () => {
+ const lock = await loadLock()
+ mkdirSync(lockDir(), { mode: 0o700 })
+ writeFileSync(ownerFile(), '', { mode: 0o600 })
+ // Fresh: someone is between the O_EXCL create and the write.
+ await expect(lock.acquireSpawnLock('start', { waitMs: 250 })).rejects.toMatchObject({ name: 'SpawnLockBusyError', owner: null })
+ const old = new Date(Date.now() - 10_000)
+ const { utimesSync } = await import('fs')
+ utimesSync(lockDir(), old, old)
+ // The record is what was written last: it alone being fresh still means a lock being made.
+ await expect(lock.acquireSpawnLock('start', { waitMs: 250 })).rejects.toMatchObject({ name: 'SpawnLockBusyError', owner: null })
+ utimesSync(ownerFile(), old, old)
+ const release = await lock.acquireSpawnLock('start', { waitMs: 1000 })
+ expect(lock.readSpawnLockOwner()?.pid).toBe(process.pid)
+ release()
+ expect(existsSync(lockDir())).toBe(false)
+ })
+
+ it('leaves no lock behind when its owner record cannot be written, so the next taker is not shut out', async () => {
+ vi.doMock('fs', async (importOriginal) => {
+ const fs = await importOriginal<typeof import('fs')>()
+ return {
+ ...fs,
+ writeFileSync: (...args: Parameters<typeof fs.writeFileSync>) => {
+ if (typeof args[0] === 'number') throw Object.assign(new Error('ENOSPC: no space left on device, write'), { code: 'ENOSPC' })
+ return fs.writeFileSync(...args)
+ },
+ }
+ })
+ try {
+ const lock = await loadLock()
+ await expect(lock.acquireSpawnLock('update', { waitMs: 250 })).rejects.toMatchObject({ code: 'ENOSPC' })
+ expect(existsSync(lockDir())).toBe(false)
+ } finally { vi.doUnmock('fs') }
+ const lock = await loadLock()
+ const release = await lock.acquireSpawnLock('update', { waitMs: 250 })
+ expect(lock.readSpawnLockOwner()?.purpose).toBe('update')
+ release()
+ })
+
it('refuses a lock directory with an unsafe mode rather than reading it', async () => {
const lock = await loadLock()
mkdirSync(lockDir(), { mode: 0o777 })
diff --git a/cli/src/lib/daemonSpawnLock.ts b/cli/src/lib/daemonSpawnLock.ts
index 17a9ede30..967b38749 100644
--- a/cli/src/lib/daemonSpawnLock.ts
+++ b/cli/src/lib/daemonSpawnLock.ts
@@ -58,7 +58,8 @@ export const SPAWN_LOCK_DIR = join(env.ADAPTER_DATA_DIR, 'adapter.spawn.lock')
const OWNER_FILE = 'owner.json'
const POLL_MS = 100
export const SPAWN_LOCK_WAIT_MS = 45_000
-/** A directory with no owner.json is a crash between mkdir and the O_EXCL write — a window of
+/** A directory with no owner.json is a crash between mkdir and the O_EXCL write, and one whose
+ * owner.json names no one is a crash or a full disk between that create and the write: windows of
* microseconds. Anything older than this with no owner is debris, not a lock. */
const OWNERLESS_STALE_MS = 5_000
@@ -171,10 +172,12 @@ function tryCreate(purpose: SpawnLockPurpose): string | null {
secureStateDirectory(env.ADAPTER_DATA_DIR)
const token = randomUUID()
let created = false
+ let opened = false
try {
mkdirSync(SPAWN_LOCK_DIR, { mode: 0o700 })
created = true
const fd = openSync(ownerPath(), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
+ opened = true
try {
const owner: SpawnLockOwner = {
pid: process.pid, ...processLockIdentity(process.pid), token, purpose, since: Date.now(),
@@ -184,7 +187,12 @@ function tryCreate(purpose: SpawnLockPurpose): string | null {
} finally { closeSync(fd) }
return token
} catch (error) {
- if (created) releaseOwnedBy(token)
+ // The owner file is this call's (O_EXCL), so the directory is too, however little of the record
+ // reached the disk. A full disk cut it short on 2026-10-05 (e2e/updateHostile.e2e.ts): left there,
+ // empty, it named no one that could ever let go, and every update, start and stop after it waited
+ // out its 45 s and gave up, long after the space came back.
+ if (opened) rmSync(SPAWN_LOCK_DIR, { recursive: true, force: true })
+ else if (created) releaseOwnedBy(token)
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
return null
}
@@ -219,11 +227,18 @@ function reclaimIfStale(owner: SpawnLockOwner): boolean {
return false
}
+/**
+ * Remove a lock that names no one once it is clearly debris: a directory with no owner record, or one
+ * whose record names no process (empty or cut short: a crash, or a full disk, between the O_EXCL create
+ * and the write). Called only when the record could not be read as an owner. Fresh, either is a lock
+ * being created, and is left alone.
+ */
function reclaimIfOwnerless(): boolean {
try {
const dir = lstatSync(SPAWN_LOCK_DIR)
- try { lstatSync(ownerPath()); return false } catch { /* no owner file */ }
- if (Date.now() - dir.mtimeMs > OWNERLESS_STALE_MS) {
+ let since = dir.mtimeMs
+ try { since = Math.max(since, lstatSync(ownerPath()).mtimeMs) } catch { /* no owner file */ }
+ if (Date.now() - since > OWNERLESS_STALE_MS) {
rmSync(SPAWN_LOCK_DIR, { recursive: true, force: true })
return true
}
diff --git a/cli/src/lib/selfUpdate.spec.ts b/cli/src/lib/selfUpdate.spec.ts
index df2d605fa..f003eec8e 100644
--- a/cli/src/lib/selfUpdate.spec.ts
+++ b/cli/src/lib/selfUpdate.spec.ts
@@ -1,9 +1,12 @@
-import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs'
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { createHash } from 'crypto'
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { canary, confirm, downloadVerified, fetchManifest, isLocalDevBuild, msUntilSlot, rejectedVersions, restore, semverGt, shouldAutoUpdate, stage, startSelfUpdater } from './selfUpdate.js'
+import {
+ REFUSED_RETRY_MAX_MS, canary, confirm, downloadVerified, fetchManifest, isLocalDevBuild, msUntilSlot, rejectedVersions, restore, runCanary, semverGt,
+ settleRolledBack, shouldAutoUpdate, stage, startSelfUpdater, unjudgedUpdate,
+} from './selfUpdate.js'
import { SpawnLockBusyError } from './daemonSpawnLock.js'
let dirs: string[] = []
@@ -301,7 +304,8 @@ describe('a rolled-back version', () => {
})
it('is never staged again by the background updater, which says so once and waits for a newer build', async () => {
- const cli = Buffer.from('#!/usr/bin/env node\nconsole.log("x")\n')
+ // A release says the version it is published as (scripts/upload-cli.sh checks it; so does the canary).
+ const cli = Buffer.from('#!/usr/bin/env node\nconsole.log("9.9.10")\n')
const notify = Buffer.from('export {}\n')
const sha = (b: Buffer): string => createHash('sha256').update(b).digest('hex')
let offered = '9.9.9'
@@ -402,14 +406,14 @@ describe('the updater when things go wrong', () => {
onStaged: (version) => { staged.push(version) },
})
await vi.waitFor(() => expect(errors).toHaveLength(1), { timeout: 5_000 })
- expect(errors[0]).toContain('canary failed for the new build')
+ expect(errors[0]).toBe('[update] 9.9.9 failed its canary (exit 3) — not trying it again for 20 ms')
expect(staged).toEqual([])
expect(readdirSync(dir)).toEqual([])
})
it('waits out a busy spawn lock with the build it already verified, and reports any other failure', async () => {
let downloads = 0
- serve(Buffer.from('#!/usr/bin/env node\nconsole.log("x")\n'), () => { downloads++ })
+ serve(Buffer.from('#!/usr/bin/env node\nconsole.log("9.9.9")\n'), () => { downloads++ })
const logs: string[] = []
vi.spyOn(console, 'log').mockImplementation((line: string) => { logs.push(String(line)) })
vi.spyOn(console, 'error').mockImplementation((line: string) => { logs.push(String(line)) })
@@ -433,3 +437,365 @@ describe('the updater when things go wrong', () => {
expect(logs.filter((line) => line === '[update] check failed (will retry):')).toHaveLength(2)
})
})
+
+describe('staging, all or nothing (e2e/updateHostile.e2e.ts)', () => {
+ const sha = (b: Buffer | string): string => createHash('sha256').update(b).digest('hex')
+ afterEach(() => {
+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true })
+ dirs = []
+ })
+
+ /** An install holding v1, as the last build kept. */
+ const installed = (): string => {
+ const dir = tempDir()
+ writeFileSync(join(dir, 'cli.js'), 'v1')
+ writeFileSync(join(dir, 'notify.mjs'), 'n1')
+ writeFileSync(join(dir, 'package.json'), '{"type":"module"}\n')
+ return dir
+ }
+ const files = (dir: string) => Object.fromEntries(readdirSync(dir).sort().map((name) => {
+ const path = join(dir, name)
+ return [name, statSync(path).isDirectory() ? '<dir>' : readFileSync(path, 'utf8')]
+ }))
+
+ it('backs up with hard links, and notes the update with the sha256 of the cli.js it put in place', () => {
+ const dir = installed()
+ const before = statSync(join(dir, 'cli.js')).ino
+ stage(dir, Buffer.from('v2'), Buffer.from('n2'), '2.0.0')
+ expect(statSync(join(dir, 'cli.js.prev')).ino).toBe(before)
+ expect(files(dir)).toEqual({
+ 'cli.js': 'v2', 'cli.js.prev': 'v1', 'notify.mjs': 'n2', 'notify.mjs.prev': 'n1', 'package.json': '{"type":"module"}\n',
+ 'update-pending.json': expect.stringContaining(`"sha256":"${sha('v2')}"`),
+ })
+ })
+
+ it('leaves the install exactly as it was when a write fails, at any step', () => {
+ for (const blocked of ['cli.js.tmp', 'notify.mjs.tmp', 'update-pending.json.tmp']) {
+ const dir = installed()
+ // A folder where the file would go: the write fails there, as on a full disk.
+ mkdirSync(join(dir, blocked))
+ writeFileSync(join(dir, blocked, 'x'), '')
+ expect(() => stage(dir, Buffer.from('v2'), Buffer.from('n2'), '2.0.0'), blocked).toThrow()
+ expect(files(dir), blocked).toEqual({ 'cli.js': 'v1', 'notify.mjs': 'n1', 'package.json': '{"type":"module"}\n', [blocked]: '<dir>' })
+ }
+ })
+
+ it('mends a package.json emptied by an earlier write, and leaves a sound one untouched', () => {
+ const dir = installed()
+ const sound = statSync(join(dir, 'package.json')).ino
+ stage(dir, Buffer.from('v2'), Buffer.from('n2'), '2.0.0')
+ expect(statSync(join(dir, 'package.json')).ino).toBe(sound)
+ writeFileSync(join(dir, 'package.json'), '')
+ confirm(dir)
+ stage(dir, Buffer.from('v3'), Buffer.from('n3'), '3.0.0')
+ expect(readFileSync(join(dir, 'package.json'), 'utf8')).toBe('{"type":"module"}\n')
+ })
+
+ it('copies the backup whole where the disk has no hard links', async () => {
+ vi.resetModules()
+ vi.doMock('fs', async (importOriginal) => ({ ...await importOriginal<typeof import('fs')>(), linkSync: () => { throw Object.assign(new Error('EPERM'), { code: 'EPERM' }) } }))
+ try {
+ const { stage: stageCopying } = await import('./selfUpdate.js')
+ const dir = installed()
+ const before = statSync(join(dir, 'cli.js')).ino
+ stageCopying(dir, Buffer.from('v2'), Buffer.from('n2'), '2.0.0')
+ expect(readFileSync(join(dir, 'cli.js.prev'), 'utf8')).toBe('v1')
+ expect(statSync(join(dir, 'cli.js.prev')).ino).not.toBe(before)
+ expect(readdirSync(dir).filter((name) => name.endsWith('.tmp'))).toEqual([])
+ } finally {
+ vi.doUnmock('fs')
+ vi.resetModules()
+ }
+ })
+
+ it('keeps the last build kept as the backup while the bundle is an update still being judged, so a rollback goes back to it', () => {
+ const dir = installed()
+ stage(dir, Buffer.from('v2'), Buffer.from('n2'), '2.0.0')
+ // v2, on probation, stages v3 before it is kept.
+ stage(dir, Buffer.from('v3'), Buffer.from('n3'), '3.0.0')
+ expect(readFileSync(join(dir, 'cli.js.prev'), 'utf8')).toBe('v1')
+ expect(readFileSync(join(dir, 'notify.mjs.prev'), 'utf8')).toBe('n1')
+ restore(dir)
+ expect(files(dir)).toEqual({ 'cli.js': 'v1', 'notify.mjs': 'n1', 'package.json': '{"type":"module"}\n', 'update-rejected.json': '["3.0.0"]\n' })
+ })
+
+ it('backs up the bundle on disk when it was kept, or when a pending note does not describe it', () => {
+ const dir = installed()
+ stage(dir, Buffer.from('v2'), Buffer.from('n2'), '2.0.0')
+ confirm(dir)
+ stage(dir, Buffer.from('v3'), Buffer.from('n3'), '3.0.0')
+ expect(readFileSync(join(dir, 'cli.js.prev'), 'utf8')).toBe('v2')
+ // A note from a stage before this one recorded what it put in place: it names no bundle.
+ writeFileSync(join(dir, 'update-pending.json'), '{"version":"3.0.0","at":1}\n')
+ stage(dir, Buffer.from('v4'), Buffer.from('n4'), '4.0.0')
+ expect(readFileSync(join(dir, 'cli.js.prev'), 'utf8')).toBe('v3')
+ // Nor does one whose backups are gone.
+ rmSync(join(dir, 'notify.mjs.prev'))
+ stage(dir, Buffer.from('v5'), Buffer.from('n5'), '5.0.0')
+ expect(readFileSync(join(dir, 'cli.js.prev'), 'utf8')).toBe('v4')
+ })
+
+ it('tells which update the bundle on disk is, while no master has kept or rolled it back', () => {
+ const dir = installed()
+ expect(unjudgedUpdate(dir, sha('v1'))).toBeNull()
+ stage(dir, Buffer.from('v2'), Buffer.from('n2'), '2.0.0')
+ expect(unjudgedUpdate(dir, sha('v2'))).toBe('2.0.0')
+ expect(unjudgedUpdate(dir, sha('v1'))).toBeNull()
+ expect(unjudgedUpdate(dir, null)).toBeNull()
+ confirm(dir)
+ expect(unjudgedUpdate(dir, sha('v2'))).toBeNull()
+ writeFileSync(join(dir, 'update-pending.json'), '{"version":"2.0.0","at":1}\n')
+ expect(unjudgedUpdate(dir, sha('v2'))).toBeNull()
+ })
+})
+
+describe('the canary\'s verdicts', () => {
+ afterEach(() => {
+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true })
+ dirs = []
+ })
+
+ it('tells a build that failed or names another version from a canary that could not be written', () => {
+ const dir = tempDir()
+ expect(runCanary(Buffer.from('console.log("9.9.9")\n'), dir, '9.9.9')).toEqual({ ok: true })
+ expect(runCanary(Buffer.from('console.log("loading…"); console.log("9.9.9")\n'), dir, '9.9.9')).toEqual({ ok: true })
+ expect(runCanary(Buffer.from('console.log("9.9.8")\n'), dir, '9.9.9')).toEqual({ ok: false, problem: 'wrong-version', detail: 'it says it is 9.9.8' })
+ expect(runCanary(Buffer.from(''), dir, '9.9.9')).toEqual({ ok: false, problem: 'wrong-version', detail: 'it says it is nothing' })
+ expect(runCanary(Buffer.from('process.exit(3)\n'), dir, '9.9.9')).toEqual({ ok: false, problem: 'failed', detail: 'exit 3' })
+ expect(runCanary(Buffer.from('process.kill(process.pid, "SIGKILL")\n'), dir)).toEqual({ ok: false, problem: 'failed', detail: 'signal SIGKILL' })
+ expect(canary(Buffer.from('console.log("anything")\n'), dir)).toBe(true)
+ expect(canary(Buffer.from('console.log("9.9.8")\n'), dir, '9.9.9')).toBe(false)
+ const file = join(dir, 'not-a-folder')
+ writeFileSync(file, '')
+ expect(runCanary(Buffer.from('console.log(1)\n'), file, '1')).toMatchObject({ ok: false, problem: 'unwritable' })
+ expect(readdirSync(dir)).toEqual(['not-a-folder'])
+ })
+
+ it('says why a canary that never ran failed', async () => {
+ vi.resetModules()
+ vi.doMock('./nodeRuntime.js', () => ({ managedNodePath: () => '/nonexistent/node' }))
+ try {
+ const { runCanary: runWithoutNode } = await import('./selfUpdate.js')
+ expect(runWithoutNode(Buffer.from('console.log(1)\n'), tempDir(), '1')).toMatchObject({ ok: false, problem: 'failed', detail: expect.stringContaining('ENOENT') })
+ } finally {
+ vi.doUnmock('./nodeRuntime.js')
+ vi.resetModules()
+ }
+ })
+})
+
+describe('a build that fails on its own merits (e2e/updateHostile.e2e.ts)', () => {
+ const sha = (b: Buffer): string => createHash('sha256').update(b).digest('hex')
+ const notify = Buffer.from('export {}\n')
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true })
+ dirs = []
+ })
+
+ /** A manifest naming `cli` (or, with `named`, another sha256 than the bytes served), counting downloads. */
+ function serve(state: { cli: Buffer; named?: string; downloads: number }): void {
+ vi.stubGlobal('fetch', async (url: string) => {
+ if (url.endsWith('/metadata.json')) {
+ return new Response(JSON.stringify({ adapter: {
+ version: '9.9.9',
+ cli: { url: 'https://updates.test/cli.js', sha256: state.named ?? sha(state.cli) },
+ notify: { url: 'https://updates.test/notify.mjs', sha256: sha(notify) },
+ } }))
+ }
+ if (url.endsWith('cli.js')) { state.downloads++; return new Response(state.cli) }
+ return new Response(notify)
+ })
+ }
+ const ticks = (n: number) => new Promise((resolve) => setTimeout(resolve, n * 10 + 5))
+
+ it.each([
+ ['whose bytes do not match its manifest', (state: { cli: Buffer; named?: string }) => { state.named = sha(Buffer.from('other bytes')) }, 'does not match its manifest (sha256 mismatch'],
+ ['that fails its canary', (state: { cli: Buffer; named?: string }) => { state.cli = Buffer.from('process.exit(3)\n') }, 'failed its canary (exit 3)'],
+ ['that says it is another version', (state: { cli: Buffer; named?: string }) => { state.cli = Buffer.from('console.log("9.9.8")\n') }, 'failed its canary (it says it is 9.9.8)'],
+ ])('is not downloaded again at every check: a build %s waits two intervals, then four, eight, …', async (_, breakIt, why) => {
+ const state = { cli: Buffer.from('console.log("9.9.9")\n'), named: undefined as string | undefined, downloads: 0 }
+ breakIt(state)
+ serve(state)
+ const errors: string[] = []
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ vi.spyOn(console, 'error').mockImplementation((line: string) => { errors.push(String(line)) })
+ let clock = 0
+ const staged: string[] = []
+ const poller = startSelfUpdater({
+ currentVersion: '1.0.0', url: 'https://updates.test/metadata.json', key: 'adapter', dir: tempDir(), intervalMs: 10, now: () => clock,
+ onStaged: (version) => { staged.push(version) },
+ })
+ try {
+ await vi.waitFor(() => expect(state.downloads).toBe(1), { timeout: 5_000 })
+ await ticks(5)
+ expect(state.downloads).toBe(1)
+ expect(errors).toEqual([expect.stringContaining(`[update] 9.9.9 ${why}`)])
+ expect(errors[0]).toMatch(/— not trying it again for 20 ms$/)
+ clock = 20
+ await vi.waitFor(() => expect(state.downloads).toBe(2), { timeout: 5_000 })
+ await vi.waitFor(() => expect(errors[1]).toMatch(/— not trying it again for 40 ms$/), { timeout: 5_000 })
+ clock = 59
+ await ticks(5)
+ expect(state.downloads).toBe(2)
+ // Published again, fixed: a new entry in the manifest is tried at once.
+ state.cli = Buffer.from('console.log("9.9.9")\n')
+ state.named = undefined
+ await vi.waitFor(() => expect(staged).toEqual(['9.9.9']), { timeout: 5_000 })
+ expect(state.downloads).toBe(3)
+ } finally { poller.stop() }
+ })
+
+ it('downloads again at the next check, without waiting, when the network dropped the last download', async () => {
+ const cli = Buffer.from('console.log("9.9.9")\n')
+ let attempts = 0
+ vi.stubGlobal('fetch', async (url: string) => {
+ if (url.endsWith('/metadata.json')) {
+ return new Response(JSON.stringify({ adapter: {
+ version: '9.9.9',
+ cli: { url: 'https://updates.test/cli.js', sha256: sha(cli) },
+ notify: { url: 'https://updates.test/notify.mjs', sha256: sha(notify) },
+ } }))
+ }
+ if (url.endsWith('cli.js') && ++attempts <= 2) throw new TypeError('terminated')
+ return new Response(url.endsWith('cli.js') ? cli : notify)
+ })
+ const errors: string[] = []
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ vi.spyOn(console, 'error').mockImplementation((...parts: unknown[]) => { errors.push(parts.join(' ')) })
+ const staged: string[] = []
+ const poller = startSelfUpdater({
+ currentVersion: '1.0.0', url: 'https://updates.test/metadata.json', key: 'adapter', dir: tempDir(), intervalMs: 10, now: () => 0,
+ onStaged: (version) => { staged.push(version) },
+ })
+ try {
+ await vi.waitFor(() => expect(staged).toEqual(['9.9.9']), { timeout: 5_000 })
+ expect(attempts).toBe(3)
+ expect(errors).toEqual(['[update] check failed (will retry): terminated', '[update] check failed (will retry): terminated'])
+ } finally { poller.stop() }
+ })
+
+ it('waits at most an hour, however long the build stays broken', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })
+ try {
+ const state = { cli: Buffer.from('process.exit(3)\n'), downloads: 0 }
+ serve(state)
+ const errors: string[] = []
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ vi.spyOn(console, 'error').mockImplementation((line: string) => { errors.push(String(line)) })
+ // The real interval: ten minutes.
+ const poller = startSelfUpdater({
+ currentVersion: '1.0.0', url: 'https://updates.test/metadata.json', key: 'adapter', dir: tempDir(), intervalMs: 600_000,
+ onStaged: () => {},
+ })
+ for (const [tries, wait] of [[1, '1200 s'], [2, '2400 s'], [3, '3600 s'], [4, '3600 s']] as const) {
+ while (errors.length < tries) await vi.advanceTimersByTimeAsync(600_000)
+ expect(errors[tries - 1]).toMatch(new RegExp(`not trying it again for ${wait}$`))
+ }
+ expect(state.downloads).toBe(4)
+ expect(REFUSED_RETRY_MAX_MS).toBe(3_600_000)
+ poller.stop()
+ } finally { vi.useRealTimers() }
+ })
+
+ it('writes the canary again at the next check when it could not, without downloading the build again', async () => {
+ const state = { cli: Buffer.from('console.log("9.9.9")\n'), downloads: 0 }
+ serve(state)
+ const errors: string[] = []
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ vi.spyOn(console, 'error').mockImplementation((line: string) => { errors.push(String(line)) })
+ const dir = tempDir()
+ // The install folder is not a folder: the canary cannot be written there, as on a full disk.
+ const install = join(dir, 'install')
+ writeFileSync(install, '')
+ const staged: string[] = []
+ const poller = startSelfUpdater({
+ currentVersion: '1.0.0', url: 'https://updates.test/metadata.json', key: 'adapter', dir: install, intervalMs: 10,
+ onStaged: (version) => { staged.push(version) },
+ })
+ try {
+ await vi.waitFor(() => expect(errors.length).toBeGreaterThanOrEqual(2), { timeout: 5_000 })
+ expect(errors[0]).toMatch(/^\[update\] could not write the canary for 9\.9\.9 \(.+\) — trying again next check$/)
+ rmSync(install)
+ await vi.waitFor(() => expect(staged).toEqual(['9.9.9']), { timeout: 5_000 })
+ expect(state.downloads).toBe(1)
+ } finally { poller.stop() }
+ })
+})
+
+describe('a rollback a full disk kept from being remembered (e2e/updateHostile.e2e.ts)', () => {
+ const sha = (b: Buffer): string => createHash('sha256').update(b).digest('hex')
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true })
+ dirs = []
+ })
+
+ /** v2 staged over v1 and rolled back while the rejected list could not be written. */
+ const rolledBackUnremembered = (): string => {
+ const dir = tempDir()
+ writeFileSync(join(dir, 'cli.js'), 'v1')
+ writeFileSync(join(dir, 'notify.mjs'), 'n1')
+ stage(dir, Buffer.from('v2'), Buffer.from('n2'), '2.0.0')
+ // Where the list's temporary file would go, a folder: its write fails, as on a full disk.
+ mkdirSync(join(dir, 'update-rejected.json.tmp'))
+ restore(dir)
+ return dir
+ }
+
+ it('keeps the note of the build that failed, and puts it on the list once it can', () => {
+ const dir = rolledBackUnremembered()
+ expect(readFileSync(join(dir, 'cli.js'), 'utf8')).toBe('v1')
+ expect(rejectedVersions(dir)).toEqual([])
+ // Still no room: named all the same.
+ expect(settleRolledBack(dir)).toBe('2.0.0')
+ expect(existsSync(join(dir, 'update-pending.json'))).toBe(true)
+ rmSync(join(dir, 'update-rejected.json.tmp'), { recursive: true })
+ expect(settleRolledBack(dir)).toBe('2.0.0')
+ expect(rejectedVersions(dir)).toEqual(['2.0.0'])
+ expect(existsSync(join(dir, 'update-pending.json'))).toBe(false)
+ expect(settleRolledBack(dir)).toBeNull()
+ // Already on the list: the note only goes.
+ writeFileSync(join(dir, 'update-pending.json'), JSON.stringify({ version: '2.0.0', sha256: sha(Buffer.from('v2')), at: 1 }))
+ expect(settleRolledBack(dir)).toBe('2.0.0')
+ expect(rejectedVersions(dir)).toEqual(['2.0.0'])
+ // The note of an update still being judged names the bundle on disk; one from before notes named none.
+ stage(dir, Buffer.from('v3'), Buffer.from('n3'), '3.0.0')
+ expect(settleRolledBack(dir)).toBeNull()
+ writeFileSync(join(dir, 'update-pending.json'), '{"version":"3.0.0","at":1}\n')
+ expect(settleRolledBack(dir)).toBeNull()
+ })
+
+ it('is never staged by the background updater meanwhile', async () => {
+ const dir = rolledBackUnremembered()
+ const cli = Buffer.from('console.log("2.0.0")\n')
+ const notify = Buffer.from('export {}\n')
+ let downloads = 0
+ vi.stubGlobal('fetch', async (url: string) => {
+ if (url.endsWith('/metadata.json')) {
+ return new Response(JSON.stringify({ adapter: {
+ version: '2.0.0',
+ cli: { url: 'https://updates.test/cli.js', sha256: sha(cli) },
+ notify: { url: 'https://updates.test/notify.mjs', sha256: sha(notify) },
+ } }))
+ }
+ downloads++
+ return new Response(url.endsWith('cli.js') ? cli : notify)
+ })
+ const logs: string[] = []
+ vi.spyOn(console, 'log').mockImplementation((line: string) => { logs.push(String(line)) })
+ const staged: string[] = []
+ const poller = startSelfUpdater({
+ currentVersion: '1.0.0', url: 'https://updates.test/metadata.json', key: 'adapter', dir, intervalMs: 10,
+ onStaged: (version) => { staged.push(version) },
+ })
+ try {
+ await vi.waitFor(() => expect(logs).toContain('[update] 2.0.0 was rolled back on this machine — waiting for a newer build (`harness update` installs it anyway)'), { timeout: 5_000 })
+ await new Promise((resolve) => setTimeout(resolve, 60))
+ expect(staged).toEqual([])
+ expect(downloads).toBe(0)
+ } finally { poller.stop() }
+ })
+})
diff --git a/cli/src/lib/selfUpdate.ts b/cli/src/lib/selfUpdate.ts
index ac7d1f250..c983cf4da 100644
--- a/cli/src/lib/selfUpdate.ts
+++ b/cli/src/lib/selfUpdate.ts
@@ -14,7 +14,7 @@
*/
import { createHash } from 'crypto'
-import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs'
+import { existsSync, linkSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs'
import { spawnSync } from 'child_process'
import { join } from 'path'
import { SpawnLockBusyError, describeSpawnLockFailure } from './daemonSpawnLock.js'
@@ -46,15 +46,46 @@ function readJson(file: string): unknown {
try { return JSON.parse(readFileSync(file, 'utf8')) } catch { return null }
}
+/** Written whole and renamed into place; a write cut short (a full disk) leaves nothing behind. */
function writeJson(file: string, value: unknown): void {
+ writeWhole(file, `${JSON.stringify(value)}\n`)
+}
+
+function writeWhole(file: string, bytes: string | Buffer): void {
const tmp = `${file}.tmp`
- writeFileSync(tmp, `${JSON.stringify(value)}\n`)
- renameSync(tmp, file)
+ try {
+ writeFileSync(tmp, bytes)
+ renameSync(tmp, file)
+ } catch (error) {
+ try { rmSync(tmp, { force: true }) } catch { /* not a file this call wrote */ }
+ throw error
+ }
+}
+
+const sha256 = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex')
+
+/** The update a stage left to be kept or rolled back: its version, and the sha256 of the cli.js it put in place. */
+interface Pending { version: string; sha256: string | null }
+
+function readPending(dir: string): Pending | null {
+ const pending = readJson(join(dir, PENDING)) as { version?: unknown; sha256?: unknown } | null
+ if (typeof pending?.version !== 'string') return null
+ return { version: pending.version, sha256: typeof pending.sha256 === 'string' ? pending.sha256 : null }
}
function pendingVersion(dir: string): string | null {
- const pending = readJson(join(dir, PENDING)) as { version?: unknown } | null
- return typeof pending?.version === 'string' ? pending.version : null
+ return readPending(dir)?.version ?? null
+}
+
+/**
+ * The version of the update the bundle on disk is, when it is one still waiting to be kept or rolled
+ * back: the pending marker names the cli.js with this sha256 (`fingerprint`, the bytes a master runs).
+ * A master that starts on such a bundle (launchd after a crash, `harness start` after a power cut,
+ * mid-probation) judges it as the master before it would have, instead of running it unwatched.
+ */
+export function unjudgedUpdate(dir: string, fingerprint: string | null): string | null {
+ const pending = readPending(dir)
+ return pending && fingerprint && pending.sha256 === fingerprint ? pending.version : null
}
/** The versions this machine rolled back, oldest first. */
@@ -116,54 +147,136 @@ export async function fetchManifest(url: string, key: string): Promise<UpdateEnt
return { version: entry.version, cli: entry.cli, notify: entry.notify }
}
+/** The whole download arrived, and it is not what the manifest names. */
+export class DigestMismatchError extends Error {}
+
/** Download one file and verify its sha256 in memory; throws on a non-2xx or a digest mismatch. */
export async function downloadVerified(ref: FileRef): Promise<Buffer> {
const res = await fetch(ref.url)
if (!res.ok) throw new Error(`download ${ref.url} → HTTP ${res.status}`)
const buf = Buffer.from(await res.arrayBuffer())
- const got = createHash('sha256').update(buf).digest('hex')
+ const got = sha256(buf)
if (got.toLowerCase() !== ref.sha256.toLowerCase()) {
- throw new Error(`sha256 mismatch for ${ref.url}: expected ${ref.sha256}, got ${got}`)
+ throw new DigestMismatchError(`sha256 mismatch for ${ref.url}: expected ${ref.sha256}, got ${got}`)
}
return buf
}
+/**
+ * What the canary found. `unwritable`: it could not be set up (a full disk, a folder it may not write),
+ * which says nothing about the build; `failed`: the build ran and failed; `wrong-version`: it ran and
+ * said it is another version than the manifest names.
+ */
+export type CanaryResult = { ok: true } | { ok: false; problem: 'unwritable' | 'failed' | 'wrong-version'; detail: string }
+
/** Cheap runnability check: write the new bundle into a temp install-shaped dir and run
- * `node cli.js version`. This catches broken ESM/CJS packaging before the live install is touched. */
-export function canary(cliBuf: Buffer, dir: string): boolean {
+ * `node cli.js version`. This catches broken ESM/CJS packaging before the live install is touched.
+ *
+ * Given the version the manifest names, the build must also say it is that version. A manifest that
+ * named an older build's bytes under a newer version (published by mistake, e2e/updateHostile.e2e.ts)
+ * was otherwise installed, came up, still reported the older version, found the newer one in the
+ * manifest again and installed it again: a restart a minute on every machine until it was fixed. */
+export function runCanary(cliBuf: Buffer, dir: string, version?: string): CanaryResult {
const tmpDir = join(dir, `.canary-${process.pid}-${Date.now()}`)
const tmpCli = join(tmpDir, CLI)
try {
- mkdirSync(tmpDir, { recursive: true })
- writeFileSync(join(tmpDir, PACKAGE), RUNTIME_PACKAGE)
- writeFileSync(tmpCli, cliBuf)
+ try {
+ mkdirSync(tmpDir, { recursive: true })
+ writeFileSync(join(tmpDir, PACKAGE), RUNTIME_PACKAGE)
+ writeFileSync(tmpCli, cliBuf)
+ } catch (error) {
+ return { ok: false, problem: 'unwritable', detail: error instanceof Error ? error.message : String(error) }
+ }
// The interpreter the NEXT daemon will run on — see managedNodePath(). Canarying on this
// process's interpreter would assert about a Node the new build may never be started with.
- const r = spawnSync(managedNodePath(), [tmpCli, 'version'], { timeout: 15_000, stdio: 'ignore' })
- return r.status === 0
- } catch {
- return false
+ const r = spawnSync(managedNodePath(), [tmpCli, 'version'], { timeout: 15_000, stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf8' })
+ if (r.status !== 0) return { ok: false, problem: 'failed', detail: r.error ? r.error.message : r.signal ? `signal ${r.signal}` : `exit ${r.status}` }
+ const lines = r.stdout.trim().split('\n')
+ const said = lines[lines.length - 1]
+ if (version !== undefined && said !== version) return { ok: false, problem: 'wrong-version', detail: `it says it is ${said || 'nothing'}` }
+ return { ok: true }
} finally {
try { rmSync(tmpDir, { recursive: true, force: true }) } catch { /* ignore */ }
}
}
-/** Atomically swap the new bytes into `dir`, backing up the current files to `.prev` for rollback, and
- * note `version` as pending until it is kept or rolled back.
- * (Verify-in-memory first ⇒ we only ever write bytes we already trust; write-tmp+rename ⇒ no torn file.) */
+export function canary(cliBuf: Buffer, dir: string, version?: string): boolean {
+ return runCanary(cliBuf, dir, version).ok
+}
+
+/**
+ * Swap the new bytes into `dir`, backing up the current files to `.prev` for rollback, and note
+ * `version` as pending until it is kept or rolled back. (Verified in memory first, so only bytes we
+ * already trust are ever written.)
+ *
+ * All or nothing, because a full disk found the gaps (e2e/updateHostile.e2e.ts): everything new is
+ * written beside what it replaces first, and only renames, which need no room and cannot tear a file,
+ * touch what the daemon runs. Before, a write that failed left its temporary file (up to a whole
+ * bundle, on a disk already full) behind, package.json was rewritten in place, and a failure after
+ * cli.js was swapped left a mixed bundle with no pending note, which the retry then backed up over the
+ * backup of the build before.
+ *
+ * The backups are hard links where the disk allows them: no second copy of the bundle to find room
+ * for, and never a partial one. While the bundle on disk is itself an update still being judged (a
+ * newer build staged during its probation), the backups already hold the last build that was kept,
+ * and stay: a rollback goes back to a build that proved itself, not to one that never did.
+ */
export function stage(dir: string, cliBuf: Buffer, notifyBuf: Buffer, version?: string): void {
mkdirSync(dir, { recursive: true })
- writeFileSync(join(dir, PACKAGE), RUNTIME_PACKAGE)
- const swap = (name: string, buf: Buffer): void => {
- const target = join(dir, name)
- if (existsSync(target)) copyFileSync(target, `${target}.prev`)
- const tmp = `${target}.tmp`
- writeFileSync(tmp, buf)
- renameSync(tmp, target) // atomic within the same filesystem
+ const path = (name: string): string => join(dir, name)
+ const temporary = (name: string): string => `${path(name)}.tmp`
+ // The files this call wrote, removed again if it fails before the swap.
+ const written: string[] = []
+ const write = (file: string, bytes: string | Buffer): void => {
+ written.push(file)
+ writeFileSync(file, bytes)
+ }
+ const unjudged = (): boolean => {
+ const pending = readPending(dir)
+ return !!pending?.sha256 && existsSync(`${path(CLI)}.prev`) && existsSync(`${path(NOTIFY)}.prev`)
+ && pending.sha256 === fileSha256(path(CLI))
}
- swap(CLI, cliBuf)
- swap(NOTIFY, notifyBuf)
- if (version) writeJson(join(dir, PENDING), { version, at: Date.now() })
+ const renames: Array<[string, string]> = []
+ try {
+ if (readText(path(PACKAGE)) !== RUNTIME_PACKAGE) {
+ write(temporary(PACKAGE), RUNTIME_PACKAGE)
+ renames.push([temporary(PACKAGE), path(PACKAGE)])
+ }
+ write(temporary(CLI), cliBuf)
+ write(temporary(NOTIFY), notifyBuf)
+ renames.push([temporary(CLI), path(CLI)], [temporary(NOTIFY), path(NOTIFY)])
+ if (!unjudged()) {
+ for (const name of [CLI, NOTIFY]) {
+ if (!existsSync(path(name))) continue
+ const backup = `${path(name)}.prev`
+ written.push(backup)
+ rmSync(backup, { force: true })
+ try {
+ linkSync(path(name), backup)
+ } catch {
+ // A filesystem without hard links: a whole copy, renamed into place, never a partial one.
+ write(`${backup}.tmp`, readFileSync(path(name)))
+ renameSync(`${backup}.tmp`, backup)
+ }
+ }
+ }
+ // Before the swap: a process that dies between here and the end leaves an update the next master
+ // finds and judges (`unjudgedUpdate`), not a bundle no one knows is new. Written whole or not at
+ // all, so a marker it would replace is never lost to a failed write.
+ if (version) writeJson(path(PENDING), { version, sha256: sha256(cliBuf), at: Date.now() })
+ } catch (error) {
+ for (const file of written) { try { rmSync(file, { force: true }) } catch { /* not this call's to clear */ } }
+ throw error
+ }
+ for (const [from, to] of renames) renameSync(from, to) // atomic within the same filesystem
+}
+
+function readText(file: string): string | null {
+ try { return readFileSync(file, 'utf8') } catch { return null }
+}
+
+function fileSha256(file: string): string | null {
+ try { return sha256(readFileSync(file)) } catch { return null }
}
/**
@@ -184,6 +297,24 @@ export function restore(dir: string): void {
} catch { /* the rollback itself is what matters */ }
}
+/**
+ * A build a rollback could not remember: a full disk kept `restore` from writing the rejected list, so
+ * its pending note is still there, naming a cli.js no longer on disk. Put it on the list now if it can
+ * be, and return its version either way, so the updater does not stage it again meanwhile: before, it
+ * was staged again once there was room, and crashed the daemon once more (e2e/updateHostile.e2e.ts).
+ * Null when there is no such note.
+ */
+export function settleRolledBack(dir: string): string | null {
+ const pending = readPending(dir)
+ if (!pending?.sha256 || pending.sha256 === fileSha256(join(dir, CLI))) return null
+ try {
+ const listed = rejectedVersions(dir)
+ if (!listed.includes(pending.version)) writeJson(join(dir, REJECTED), [...listed, pending.version].slice(-REJECTED_KEPT))
+ rmSync(join(dir, PENDING), { force: true })
+ } catch { /* still no room: the note stays, and still names it */ }
+ return pending.version
+}
+
/** Drop the `.prev` backups once the new build is confirmed healthy; a version kept is not rejected. */
export function confirm(dir: string): void {
for (const name of [CLI, NOTIFY]) {
@@ -198,6 +329,9 @@ export function confirm(dir: string): void {
export interface Poller { stop(): void }
+/** The longest a build that failed on its own merits waits to be tried again. */
+export const REFUSED_RETRY_MAX_MS = 60 * 60_000
+
/**
* Milliseconds from `nowMs` to the next tick. With a slot, ticks land on the wall-clock instant
* `slotSecond` seconds past each `intervalMs` boundary (`:45` of every minute for the defaults) —
@@ -220,6 +354,14 @@ export function msUntilSlot(nowMs: number, slotSecond: number | undefined, inter
* (fetch/parse/sha/canary/disk) is swallowed and simply retried next tick — the daemon never crashes
* on a bad update.
*
+ * Retried, but not at every tick when the build itself is what failed: bytes that do not match the
+ * manifest, or a build that fails its canary, fail again the same way, and each try is a whole
+ * download. A release published broken was fetched once a minute by every machine until it was
+ * replaced (e2e/updateHostile.e2e.ts counted one a second at a one-second interval). Such a build is
+ * tried again after two intervals, then four, eight, … up to {@link REFUSED_RETRY_MAX_MS}; a new entry in
+ * the manifest is tried at once. What was only this machine's moment (a dropped link, a full disk that
+ * cannot hold the canary) is retried at the next tick, without downloading again what already arrived.
+ *
* Ticks are SCHEDULED, not immediate: the first one lands on the next slot (see {@link msUntilSlot}),
* and each tick books the next from the clock rather than from its own end, so a slow download does
* not drift the slot. `harness start` already staged the newest build before spawning this daemon,
@@ -246,10 +388,13 @@ export function startSelfUpdater(opts: {
let done = false
let timer: NodeJS.Timeout | null = null
const withLock = opts.withLock ?? ((fn) => fn())
- // The bytes of a build we have already downloaded, verified and canaried, kept across ticks: when
- // the lock was busy (a `harness start` or `harness update` mid-flight) the next tick should try the
- // swap again, not the whole download.
- let verified: { version: string; cliBuf: Buffer; notifyBuf: Buffer } | null = null
+ // The bytes of the manifest's build once downloaded and verified, kept across ticks with whether
+ // they passed their canary: when the lock was busy (a `harness start` or `harness update`
+ // mid-flight), or the canary could not be written, the next tick should try again from there, not
+ // from the whole download.
+ let verified: { entry: string; version: string; cliBuf: Buffer; notifyBuf: Buffer; canaried: boolean } | null = null
+ // The manifest's build, when it failed in a way it would fail again, and when it may be tried again.
+ let refused: { entry: string; tries: number; until: number } | null = null
// Said once per version: the check repeats every interval.
let toldRejected: string | null = null
@@ -273,17 +418,44 @@ export function startSelfUpdater(opts: {
try {
const entry = await fetchManifest(opts.url, opts.key)
if (!entry || !shouldAutoUpdate(entry.version, opts.currentVersion)) return
- if (rejectedVersions(opts.dir).includes(entry.version)) {
+ const unremembered = settleRolledBack(opts.dir)
+ if (unremembered === entry.version || rejectedVersions(opts.dir).includes(entry.version)) {
if (toldRejected !== entry.version) console.log(`[update] ${entry.version} was rolled back on this machine — waiting for a newer build (\`harness update\` installs it anyway)`)
toldRejected = entry.version
return
}
- if (verified?.version !== entry.version) {
+ const key = `${entry.version} ${entry.cli.sha256} ${entry.notify.sha256}`
+ if (refused?.entry === key && now() < refused.until) return
+ const refuse = (why: string): void => {
+ const tries = refused?.entry === key ? refused.tries + 1 : 1
+ const wait = Math.min(opts.intervalMs * 2 ** tries, REFUSED_RETRY_MAX_MS)
+ refused = { entry: key, tries, until: now() + wait }
+ verified = null
+ console.error(`[update] ${entry.version} ${why} — not trying it again for ${wait >= 1000 ? `${Math.round(wait / 1000)} s` : `${wait} ms`}`)
+ }
+ if (verified?.entry !== key) {
console.log(`[update] newer build available: ${opts.currentVersion} → ${entry.version}`)
- const cliBuf = await downloadVerified(entry.cli)
- const notifyBuf = await downloadVerified(entry.notify)
- if (!canary(cliBuf, opts.dir)) { console.error('[update] canary failed for the new build — skipping'); return }
- verified = { version: entry.version, cliBuf, notifyBuf }
+ verified = null
+ let cliBuf: Buffer
+ let notifyBuf: Buffer
+ try {
+ cliBuf = await downloadVerified(entry.cli)
+ notifyBuf = await downloadVerified(entry.notify)
+ } catch (error) {
+ if (!(error instanceof DigestMismatchError)) throw error
+ refuse(`does not match its manifest (${error.message})`)
+ return
+ }
+ verified = { entry: key, version: entry.version, cliBuf, notifyBuf, canaried: false }
+ }
+ if (!verified.canaried) {
+ const result = runCanary(verified.cliBuf, opts.dir, entry.version)
+ if (!result.ok && result.problem === 'unwritable') {
+ console.error(`[update] could not write the canary for ${entry.version} (${result.detail}) — trying again next check`)
+ return
+ }
+ if (!result.ok) { refuse(`failed its canary (${result.detail})`); return }
+ verified.canaried = true
}
const ready = verified
// Downloaded and verified OUTSIDE the lock (that can take a while on a slow link and touches
diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.md
index ae81af2e0..8f3a8844c 100644
--- a/docs/design/2026-10-03-harnessd.md
+++ b/docs/design/2026-10-03-harnessd.md
@@ -375,8 +375,10 @@ the parts still to build say so.
monitor does — re-executing with a core running would cost that core its channel. Built
(`harnessd/reexec.ts`): in place, keeping its pid, so launchd, systemd, the pid file and the app's
owner check never see the master change; a probe of the bundle's own master first; a marker that
- rolls back a master that died after re-executing. Next: bundles move to versioned directories
- behind one pointer, so a swap is one rename. A version that was rolled back is not offered again.
+ rolls back a master that died after re-executing. A newer build staged while the last is still on
+ probation is judged on its own, and a master that starts on an update no master finished judging
+ (it died mid-update) judges it. Next: bundles move to versioned directories behind one pointer, so a
+ swap is one rename. A version that was rolled back is not offered again.
- **Something supervises the supervisor.** On macOS a launchd user agent (registered through
`SMAppService`, which asks the user once) and on Linux a systemd user unit run the master in the
foreground and restart it; the desktop app then watches instead of respawning, so there is one
@@ -651,6 +653,65 @@ Done so far:
next start; every core is the master's child throughout. With a released bundle
(`MIGRATION_FROM`): an older master supervises the newer core an update brings until it restarts,
and this master runs an older bundle's core without re-executing on it.
+ - Round 40 (`e2e/updateHostile.e2e.ts`, on real bundles): the update path under hostile conditions,
+ since it is how every fix reaches every machine. A link that drops mid-download, a download cut
+ short, a release published broken, a manifest whose hash or version lies, a newer build published
+ while the last is on probation, an update with both agents mid-turn, a build whose master answers
+ its probe but whose core crashes at start, and a master killed mid-update. After each, the daemon
+ runs a working build under its master, both agents are back and take a turn, nothing is left in the
+ install or the data folder, and a build that failed here is remembered. Defects found and fixed:
+ - A newer build staged while the last was still on probation, or still starting, was taken for that
+ update failing: rolled back, and remembered as bad. A fix published soon after a release was
+ refused that way by every machine still judging the release. The master now judges the newer
+ build on its own when the bundle on disk changed since the core started (`SupervisorDeps.bundle`).
+ - A manifest naming an older build's bytes under a newer version installed it; it came up, still
+ reported the older version, and installed itself again, a restart a minute. The canary now
+ requires the version the manifest names (`scripts/upload-cli.sh` already checks the same).
+ - A build that failed its canary, or whose bytes did not match the manifest, was downloaded again
+ at every check: 13 downloads in 13 seconds at a one-second interval, once a minute on every
+ machine in production. Such a build now waits two intervals, then four, eight, up to an hour; a
+ new entry in the manifest is tried at once, and a dropped link at the next check.
+ - A master killed mid-update (a crash, a kill, a power cut) left the update unjudged: the next
+ start ran it unwatched, and a build whose core crashes at start crash-looped for good, with no
+ updater running to fix it. `update-pending.json` now records the sha256 of the cli.js it put in
+ place, and a fresh master started on that bundle puts its first core on probation.
+
+ With `DISKFULL=1` the install and the data folder share a 96 MB disk image, filled while the build
+ downloads, between the canary and the swap (the test holds the spawn lock the updater waits on),
+ just after the swap, and while a build that crashes is rolled back. More defects, all fixed:
+ - Staging was not all or nothing: a write that failed left its temporary file (up to a whole
+ bundle, on a disk already full) behind, package.json was rewritten in place, and a failure after
+ cli.js was swapped left a mixed bundle with no pending note, which the retry then backed up over
+ the old build's backup. Everything new is now written beside what it replaces first, and only
+ renames touch what runs; backups are hard links, so a swap needs room for one copy, not two.
+ - The spawn lock's owner record, cut short by a full disk, was never reclaimed: every update, start
+ and stop after it waited 45 seconds and gave up, long after the space came back. The writer
+ removes its own lock, and a record that names no one is debris after five seconds.
+ - The master's re-execution marker, unwritable on a full disk, threw out of a promise and would
+ end the master between cores. It keeps its code instead, and judges the new bundle itself.
+ - A canary that could not be written was reported as the build failing; it is now retried at the
+ next check without downloading again. A rollback that could not write the rejected list forgot
+ the build (the rollback frees the room the list needs, so this takes a disk filled again at
+ once, as by a log storm); its pending note now names the build until the list can be written.
+
+ Left, larger:
+ - The manifest is not signed. Its sha256s are only as good as the TLS connection to the manifest
+ host: one that served a matching manifest and bundle would be installed, its canary run first.
+ Signing needs a release key and its public half pinned in the bundle.
+ - A core cannot start while its data folder's disk is full: binding its socket needs a directory
+ entry (`listen ENOSPC`), so it starts in safe mode. During an update the master reads that as the
+ new build failing, rolls back (the rollback frees the room the build before needs) and remembers
+ a good build as bad until the next release. Telling a start that failed for want of room from a
+ bad build would let it be tried again instead.
+ - A handoff whose teardown throws (`restartForUpdate` in `runForeground`) stays on the old build
+ with servers already closed and the new bundle staged, unjudged; under harnessd it should exit
+ 75 regardless. It moves with `runForeground`'s next step.
+ - Downloads have no deadline of their own: a stalled transfer is dropped by undici's 300 s body
+ timeout, and a trickle can hold the check longer.
+ - Bundles in versioned directories behind one pointer (above) would make the swap a single rename.
+ - Unrelated to updating: a turn that ends while the disk is full, on a data folder that never had
+ an `orchestrator` folder, is lost (`line handler error … mkdir …/orchestrator`):
+ `OrchestratorService.roleOf`, asked at every turn's end, creates its state folder to read it.
Next, in order: