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.

Review fixes: tmux revival on Linux, master re-exec stop and services, round 40 interplay (#814)

Dee6426a3d9fd07
diff --git a/cli/src/harnessd/master.spec.ts b/cli/src/harnessd/master.spec.ts
index 49db5673e..d515fb072 100644
--- a/cli/src/harnessd/master.spec.ts
+++ b/cli/src/harnessd/master.spec.ts
@@ -562,6 +562,30 @@ describe('runMaster', () => {
} finally { log.mockRestore() }
})
+ it('asks whether the bundle on disk after a recovery is unjudged, not the bundle it started from', async () => {
+ // A re-execution that never came up is rolled back at start; with no room to remember the build,
+ // its pending note stays and names the bundle this master started from. That is not the bundle its
+ // first core runs: the build before, put back, is no update to judge.
+ const lines: string[] = []
+ const log = vi.spyOn(console, 'log').mockImplementation((line: string) => { lines.push(line) })
+ try {
+ const script = bundle('')
+ const startedFrom = fingerprint(script)!
+ writeMarker(marker(), { pid: DEAD_PID, from: 'the one before', to: startedFrom, at: 1 })
+ const asked: Array<string | null> = []
+ const master = start(script, {
+ restoreUpdate: () => { writeFileSync(script, readFileSync(script, 'utf8') + '\n// the build before\n') },
+ unjudgedUpdate: (onDisk: string | null) => { asked.push(onDisk); return onDisk === startedFrom ? '2.0.0' : null },
+ })
+ await until('the master to re-execute on the bundle restored', () => master.execs.length > 0)
+ expect(asked).toEqual([fingerprint(script)])
+ expect(asked[0]).not.toBe(startedFrom)
+ expect(lines.some((line) => line.includes('an update no master kept or rolled back'))).toBe(false)
+ expect(decodeResume(master.execs[0].env[RESUME_ENV])?.update).toBeNull()
+ await master.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)`)
@@ -572,6 +596,57 @@ describe('runMaster', () => {
await master.stop()
})
+ it('starts its services once it carries on, never while it replaces itself before its first core', async () => {
+ // A rollback found at start moves this master onto the bundle restored before it starts anything.
+ // Its services were started beside that move: they ran through the probe and were cut off by the
+ // exec, children no one reaps, and a probe that refused the bundle started them a second time.
+ const started = (lines: string[]) => lines.filter((line) => line.includes('[harnessd] service search started'))
+ const lines: string[] = []
+ const log = vi.spyOn(console, 'log').mockImplementation((line: string) => { lines.push(line) })
+ const env = { ...process.env, HARNESSD_INITIAL_BACKOFF_MS: '10', HARNESSD_SERVICES: 'search' }
+ const restore = (file: string) => () => { writeFileSync(file, readFileSync(file, 'utf8') + '\n// the build before\n') }
+ try {
+ const script = bundle('')
+ writeMarker(marker(), { pid: DEAD_PID, from: 'the one before', to: fingerprint(script)!, at: 1 })
+ let atExec: string[] | null = null
+ const moving = start(script, { env, restoreUpdate: restore(script), execve: () => { atExec = started(lines) } })
+ await until('the master to re-execute on the bundle restored', () => atExec !== null)
+ expect(atExec).toEqual([])
+ await moving.stop()
+
+ // The bundle restored refuses its probe: this master carries on as itself, with each service once.
+ lines.length = 0
+ const refusing = bundle('', `console.error('Unknown command: ' + process.argv[2]); process.exit(1)`)
+ writeMarker(marker(), { pid: DEAD_PID, from: 'the one before', to: fingerprint(refusing)!, at: 1 })
+ const staying = start(refusing, { env, restoreUpdate: restore(refusing) })
+ await until('a core on the bundle restored', () => staying.supervisor.status().state === 'running')
+ expect(started(lines)).toHaveLength(1)
+ await staying.stop()
+ } finally { log.mockRestore() }
+ })
+
+ it('takes its own marker with it when it is stopped before its first core is up, and leaves another\'s', async () => {
+ // Stopped between its exec and its first core, a re-executed master left its marker, and the next
+ // start took that for a re-execution that never came up: a good update rolled back, its version
+ // rejected (recoverFailedReexec, selfUpdate.restore).
+ const script = join(dir, 'unbound.cjs')
+ writeFileSync(script, `setInterval(() => {}, 1000); process.on('SIGTERM', () => process.exit(0))`)
+ const resume = encodeResume({ restarts: 1, lastExit: 'code 75', lastExitReason: 'update', update: 'pending', claimed: true, reexecs: 1, unproven: 1 })
+ writeMarker(marker(), { pid: process.pid, from: 'the one before', to: fingerprint(script)!, at: 1 })
+ const own = start(script, { env: { ...process.env, [RESUME_ENV]: resume } })
+ await until('its core', () => own.supervisor.status().corePid !== null)
+ await own.stop()
+ expect(readMarker(marker())).toBeNull()
+ expect(own.calls).toEqual([])
+
+ const another = { pid: process.ppid, from: 'the one before', to: fingerprint(script)!, at: 1 }
+ writeMarker(marker(), another)
+ const beside = start(script)
+ await until('its core', () => beside.supervisor.status().corePid !== null)
+ await beside.stop()
+ expect(readMarker(marker())).toEqual(another)
+ })
+
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 648d567c4..04109cbc5 100644
--- a/cli/src/harnessd/master.ts
+++ b/cli/src/harnessd/master.ts
@@ -249,8 +249,12 @@ export function runMaster(config: MasterConfig): Supervisor {
})
}
// 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
+ // power cut): this master judges it. A re-executed master was handed its own. Asked of the bundle on
+ // disk now, which the first core runs, not of this master's own: a recovery just above may have put
+ // the build before back, and when its rollback could not write the rejected list the pending note
+ // still names this master's bundle. Asked of that, the restored build's first core was put on trial,
+ // and keeping it would have dropped the note that remembers the failed one (selfUpdate.settleRolledBack).
+ const unjudged = resume ? null : config.unjudgedUpdate?.(bundle()) ?? 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
@@ -299,6 +303,10 @@ export function runMaster(config: MasterConfig): Supervisor {
exit: (code) => {
stopping = true
reexec?.cancel()
+ // A master stopped before its first core came up has not failed to come up: its own marker goes
+ // with it. Left behind by a stop, a sign-out or a shutdown in the seconds after a re-execution, it
+ // made the next start roll a good update back and reject its version (recoverFailedReexec).
+ if (markerFile && readMarker(markerFile)?.pid === process.pid) removeMarker(markerFile)
services.stop(() => {
stopTrimming()
exit(code)
@@ -321,7 +329,12 @@ export function runMaster(config: MasterConfig): Supervisor {
}
supervisor.start()
// Not waiting on the core: a service reaches it through its socket, and retries until it answers.
- services.start()
+ // Nor while this master is replacing itself before its first core, as it does when a re-execution
+ // before it never came up and the previous bundle was put back (recoverFailedReexec): started here,
+ // the services ran through the probe and were cut off by the exec, children no one reaps, or ran
+ // twice once a refused probe started them again. Whoever goes on starts them: this master if it
+ // carries on as itself, the new one if it does not.
+ if (!reexec?.replacing()) services.start()
return supervisor
}
diff --git a/cli/src/harnessd/reexec.spec.ts b/cli/src/harnessd/reexec.spec.ts
index c1d67bf6b..fcb89795f 100644
--- a/cli/src/harnessd/reexec.spec.ts
+++ b/cli/src/harnessd/reexec.spec.ts
@@ -1,5 +1,5 @@
import { EventEmitter } from 'node:events'
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type { ChildProcess } from 'node:child_process'
@@ -72,6 +72,17 @@ describe('the marker', () => {
}
})
+ it('leaves no temporary file behind when it cannot be written', () => {
+ // Something that is not a marker where it would go: the rename fails, as a write on a full disk does.
+ const file = join(dir, 'harnessd-reexec.json')
+ mkdirSync(join(file, 'in-the-way'), { recursive: true })
+ expect(() => writeMarker(file, { pid: 42, from: 'a', to: 'b', at: 1 })).toThrow()
+ expect(readdirSync(dir)).toEqual(['harnessd-reexec.json'])
+ // Nor does it fail over a temporary file it cannot clear.
+ mkdirSync(join(dir, 'harnessd-reexec.json.43.tmp', 'in-the-way'), { recursive: true })
+ expect(() => writeMarker(file, { pid: 43, from: 'a', to: 'b', at: 1 })).toThrow()
+ })
+
it('is removed even when something odd sits where it was, without throwing', () => {
const odd = join(dir, 'harnessd-reexec.json')
mkdirSync(odd)
@@ -229,6 +240,21 @@ describe('re-executing', () => {
expect(outcomes).toEqual([])
})
+ it('is replacing this master from the moment it stops its children until it carries on as itself', async () => {
+ const { reexec, replacing } = make()
+ onDisk = 'old'
+ reexec(state(), (outcome) => outcomes.push(outcome))
+ expect(replacing()).toBe(false)
+ onDisk = 'new'
+ reexec(state(), (outcome) => outcomes.push(outcome))
+ expect(replacing()).toBe(true)
+ stopped[0]()
+ expect(replacing()).toBe(true)
+ await settle({ ok: false, detail: 'no' })
+ expect(replacing()).toBe(false)
+ expect(outcomes).toEqual(['same', 'refused'])
+ })
+
it('carries on as itself when the probe fails or the exec does, with its children back', async () => {
const refused = make()
refused.reexec(state(), (outcome) => outcomes.push(outcome))
diff --git a/cli/src/harnessd/reexec.ts b/cli/src/harnessd/reexec.ts
index 828809e7e..215f375df 100644
--- a/cli/src/harnessd/reexec.ts
+++ b/cli/src/harnessd/reexec.ts
@@ -82,8 +82,15 @@ export interface ReexecMarker {
export function writeMarker(file: string, marker: ReexecMarker): void {
const temp = `${file}.${marker.pid}.tmp`
- writeFileSync(temp, `${JSON.stringify(marker)}\n`)
- renameSync(temp, file)
+ try {
+ writeFileSync(temp, `${JSON.stringify(marker)}\n`)
+ renameSync(temp, file)
+ } catch (error) {
+ // A write cut short (a full disk) is the caller's to handle (`createReexec` keeps its master); what
+ // it left in the data folder is this function's to clear.
+ try { rmSync(temp, { force: true }) } catch { /* not a file this call wrote */ }
+ throw error
+ }
}
export function readMarker(file: string): ReexecMarker | null {
@@ -195,9 +202,12 @@ export interface ReexecDeps {
export function createReexec(deps: ReexecDeps): {
reexec(state: ResumeState, proceed: (outcome: ReexecOutcome) => void): void
cancel(): void
+ /** On its way to replacing this master: from stopping its children until it carries on as itself. */
+ replacing(): boolean
} {
let warned = false
let probe: { cancel(): void } | null = null
+ let replacing = false
return {
reexec: (state, proceed) => {
const next = deps.current()
@@ -218,10 +228,12 @@ export function createReexec(deps: ReexecDeps): {
const args = [...deps.execArgv, deps.scriptPath]
// Called only once the master is known not to be stopping: its children come back, and its core.
const carryOn = (outcome: ReexecOutcome) => {
+ replacing = false
deps.startChildren()
proceed(outcome)
}
deps.log('[harnessd] the bundle on disk is not this master\'s code — re-executing on it')
+ replacing = true
deps.stopChildren(() => {
if (deps.stopping()) return
const running = deps.probe([...args, PROBE_COMMAND], env)
@@ -257,5 +269,6 @@ export function createReexec(deps: ReexecDeps): {
})
},
cancel: () => { probe?.cancel(); probe = null },
+ replacing: () => replacing,
}
}
diff --git a/cli/src/lib/tmux.socketRevival.spec.ts b/cli/src/lib/tmux.socketRevival.spec.ts
index 89a5c2d6a..54db446f7 100644
--- a/cli/src/lib/tmux.socketRevival.spec.ts
+++ b/cli/src/lib/tmux.socketRevival.spec.ts
@@ -60,6 +60,19 @@ describe('a tmux server whose socket was removed while it ran', () => {
expect(console.log).toHaveBeenCalledWith('[terminal] tmux\'s socket was removed while its server (pid 4242) still ran — asked it to make a new one')
})
+ it('knows a server by the name Linux gives it as well as by its executable, and never signals a client', async () => {
+ // Linux reports the server as `tmux: server` (tmux sets it with prctl, compat/setproctitle.c); macOS
+ // by its path. Matched on `tmux` alone, no socket was ever made again on Linux.
+ await rememberTmuxServer()
+ tmux.comm = 'tmux: server'
+ expect(await reviveRemovedTmuxSocket()).toBe(true)
+ tmux.comm = '/opt/homebrew/bin/tmux'
+ expect(await reviveRemovedTmuxSocket()).toBe(true)
+ tmux.comm = 'tmux: client'
+ expect(await reviveRemovedTmuxSocket()).toBe(false)
+ expect(signals).toEqual([[4242, 'SIGUSR1'], [4242, 'SIGUSR1']])
+ })
+
it('signals nothing with no server remembered, one that has exited, or a pid now running something else', async () => {
expect(await reviveRemovedTmuxSocket()).toBe(false)
await rememberTmuxServer()
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index da3b8431d..a3713faca 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -488,12 +488,19 @@ export function isNoTmuxServerError(error: string): boolean {
/** The tmux server the last inventory was read from (`rememberTmuxServer`); null until one was. */
let knownServer: number | null = null
-/** Whether `pid` is a running process named tmux: never a pid since reused by something else. */
+/**
+ * Whether `pid` is a running tmux server: never a pid since reused by something else. macOS names it by
+ * its executable (`/opt/homebrew/bin/tmux`). Linux names it as tmux names itself, `tmux: server`
+ * (`prctl(PR_SET_NAME)` in tmux's compat/setproctitle.c), so a check for `tmux` alone never revived a
+ * socket on Linux, where systemd-tmpfiles is the cleaner that removes it. A client (`tmux: client`) is
+ * not the server.
+ */
function isTmuxProcess(pid: number): Promise<boolean> {
try { process.kill(pid, 0) } catch { return Promise.resolve(false) }
return new Promise((resolve) => {
run('ps', ['-o', 'comm=', '-p', String(pid)], { timeout: 2_000, env: psEnv() }, (err, stdout) => {
- resolve(!err && basename(String(stdout ?? '').trim()) === 'tmux')
+ const name = basename(String(stdout ?? '').trim())
+ resolve(!err && (name === 'tmux' || name === 'tmux: server'))
})
})
}