Skip to content

The agent that grows with you

fix: Desktop SSH readers clear a dead v2 update claim instead of stranding it

Teknium49fc76fe9222
diff --git a/apps/desktop/electron/managed-ssh-update.test.ts b/apps/desktop/electron/managed-ssh-update.test.ts
index f80b1324a7a..64ef4b9d110 100644
--- a/apps/desktop/electron/managed-ssh-update.test.ts
+++ b/apps/desktop/electron/managed-ssh-update.test.ts
@@ -607,6 +607,42 @@ test.runIf(process.platform !== 'win32')(
}
)
+test.runIf(process.platform !== 'win32')(
+ 'managed observer judges a v2 claim by its owner and delegate, not as malformed',
+ async () => {
+ const home = await mkdtemp(path.join(os.tmpdir(), 'hermes-managed-v2-marker-'))
+ const marker = path.join(home, '.hermes-update-in-progress')
+
+ const target = {
+ ssh: { exec: async () => '' },
+ platform: 'Linux',
+ hermesPath: '/opt/hermes/hermes',
+ hermesHome: home
+ }
+
+ const observe = async () =>
+ parseRemoteUpdateObservation(
+ (await exec(buildRemoteUpdateObservationCommand(target as any, CORRELATION), { shell: 'sh' })).stdout,
+ CORRELATION
+ )
+
+ const exited = (await exec(`sh -c 'echo $$'`)).stdout.trim()
+ // The updater's v2 claim: pid, started_at, creation-time line (A2), then tagged lines.
+ const deadClaim = `${exited}\n${Math.floor(Date.now() / 1000)}\nct:1700000000.125\n`
+
+ try {
+ await writeFile(marker, deadClaim)
+ assert.equal((await observe()).marker, 'dead', 'a dead v2 claim is dead, never malformed')
+ await writeFile(marker, `${deadClaim}delegate:${process.pid} ct:1700000001.500\n`)
+ const delegated = await observe()
+ assert.equal(delegated.marker, 'live', 'a live delegate keeps the update live')
+ assert.equal(delegated.markerPid, process.pid)
+ } finally {
+ await rm(home, { force: true, recursive: true })
+ }
+ }
+)
+
test.runIf(process.platform !== 'win32')(
'managed observer unwraps a named profile home for the install-wide marker',
async () => {
diff --git a/apps/desktop/electron/managed-ssh-update.ts b/apps/desktop/electron/managed-ssh-update.ts
index 808ee04525c..4a25c1e3b0f 100644
--- a/apps/desktop/electron/managed-ssh-update.ts
+++ b/apps/desktop/electron/managed-ssh-update.ts
@@ -345,7 +345,6 @@ marker_path=install_root/'.hermes-update-in-progress'
status_path=home/('.update_exit_code.'+correlation)
ready_path=home/('.update_coordinator_ready.'+correlation)
intent_path=home/('.update_launch_intent.'+correlation)
-marker_re=re.compile(rb'([1-9][0-9]*)\r?\n([0-9]+)(?:\r?\n)?\Z')
def pid_alive(pid):
if os.name!='nt':
@@ -408,15 +407,20 @@ def marker_state():
try:raw=marker_path.read_bytes()
except FileNotFoundError:return {'state':'absent'}
except OSError:return {'state':'unavailable'}
- match=marker_re.fullmatch(raw)
- if not match:return {'state':'malformed'}
- try:
- pid=int(match.group(1));lease=int(match.group(2))
- if pid<1 or pid>4294967295 or lease>9007199254740991:raise ValueError()
- except ValueError:return {'state':'malformed'}
- live=pid_alive(pid)
- if live is None:return {'state':'unavailable','pid':pid}
- return {'state':'live' if live else 'dead','pid':pid}
+ # v1 is "<pid>\n<started_at>\n"; v2 adds a creation-time line 3 and tagged lines 4+
+ # (the first well-formed "delegate:<pid> ct:<ct>" names a second live holder).
+ lines=[line[:-1] if line.endswith(b'\r') else line for line in raw.split(b'\n')]
+ if lines[-1]==b'':lines.pop()
+ if len(lines)<2 or not re.fullmatch(rb'[1-9][0-9]*',lines[0]) or not re.fullmatch(rb'[0-9]+',lines[1]):
+ return {'state':'malformed'}
+ delegates=[re.fullmatch(rb'delegate:([1-9][0-9]*) ct:[0-9]+(?:\.[0-9]+)?',line) for line in lines[3:]]
+ holders=[int(lines[0])]+[int(match.group(1)) for match in delegates if match][:1]
+ if any(pid>4294967295 for pid in holders) or int(lines[1])>9007199254740991:return {'state':'malformed'}
+ for pid in holders:
+ live=pid_alive(pid)
+ if live is None:return {'state':'unavailable','pid':pid}
+ if live:return {'state':'live','pid':pid}
+ return {'state':'dead','pid':holders[0]}
def terminal_code():
try:raw=status_path.read_bytes()
diff --git a/apps/desktop/electron/remote-lifecycle-v2-marker.test.ts b/apps/desktop/electron/remote-lifecycle-v2-marker.test.ts
new file mode 100644
index 00000000000..198ab69568e
--- /dev/null
+++ b/apps/desktop/electron/remote-lifecycle-v2-marker.test.ts
@@ -0,0 +1,62 @@
+import assert from 'node:assert/strict'
+import { exec as execCallback, spawn } from 'node:child_process'
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { promisify } from 'node:util'
+
+import { test } from 'vitest'
+
+import { assertRemoteInstallUpdateClear } from './remote-lifecycle'
+
+const exec = promisify(execCallback)
+
+// The real client-supplied relaunch program, run locally against v2 claims (the SSH hop is the
+// only thing elided): the updater writes a creation-time line 3 and the hand-off scripts tagged
+// lines 4+, which older two-line readers judged UNCERTAIN forever.
+test.runIf(process.platform === 'linux')(
+ 'POSIX relaunch gate clears a dead v2 claim but keeps one a live delegate or held mutex still guards',
+ async () => {
+ const home = await mkdtemp(path.join(os.tmpdir(), 'hermes-v2-marker-'))
+ const marker = path.join(home, '.hermes-update-in-progress')
+ const shell = (await exec('command -v bash')).stdout.trim()
+ const ssh = { exec: async (command: string) => (await exec(command, { shell })).stdout }
+ const exited = spawn(process.execPath, ['-e', ''])
+ await new Promise(resolve => exited.once('exit', resolve))
+ // The updater's v2 claim: pid, started_at, creation-time line (A2), then tagged lines.
+ const deadClaim = `${exited.pid}\n${Math.floor(Date.now() / 1000)}\nct:1700000000.125\n`
+ const delegate = spawn('sleep', ['30'], { argv0: 'hermes-update', stdio: 'ignore' })
+ let mutexHolder: ReturnType<typeof spawn> | undefined
+
+ const refused = (error: any) => error.kind === 'update-in-progress'
+
+ try {
+ await writeFile(marker, deadClaim)
+ await assertRemoteInstallUpdateClear(ssh, home)
+ await assert.rejects(readFile(marker), 'a confirmed-dead v2 claim is cleared, not left UNCERTAIN')
+
+ const delegated = `${deadClaim}run:abc\ndelegate:${delegate.pid} ct:1700000001.500\n`
+ await writeFile(marker, delegated)
+ await assert.rejects(() => assertRemoteInstallUpdateClear(ssh, home), refused)
+ assert.equal(await readFile(marker, 'utf8'), delegated, 'a live delegate keeps the claim')
+
+ mutexHolder = spawn(
+ 'python3',
+ [
+ '-c',
+ 'import fcntl,sys,time;fd=open(sys.argv[1],"a");fcntl.flock(fd,fcntl.LOCK_EX);print(1,flush=True);time.sleep(30)',
+ `${marker}.lock`
+ ],
+ { stdio: ['ignore', 'pipe', 'ignore'] }
+ )
+ await new Promise(resolve => mutexHolder!.stdout!.once('data', resolve))
+ await writeFile(marker, deadClaim)
+ await assert.rejects(() => assertRemoteInstallUpdateClear(ssh, home), refused)
+ assert.equal(await readFile(marker, 'utf8'), deadClaim, 'no delete while an updater holds the marker mutex')
+ } finally {
+ delegate.kill()
+ mutexHolder?.kill()
+ await rm(home, { force: true, recursive: true })
+ }
+ }
+)
diff --git a/apps/desktop/electron/remote-lifecycle.ts b/apps/desktop/electron/remote-lifecycle.ts
index 5b43d7a6e8e..c51cb08778a 100644
--- a/apps/desktop/electron/remote-lifecycle.ts
+++ b/apps/desktop/electron/remote-lifecycle.ts
@@ -320,50 +320,70 @@ async function probeRemoteHermesHome(ssh) {
}
const REMOTE_UPDATE_MARKER_PROBE = String.raw`
-import errno,os,re,sys
+import errno,fcntl,os,re,sys
from pathlib import Path
home=Path(os.path.expanduser(sys.argv[1]))
if home.parent.name=='profiles':home=home.parent.parent
marker=home/'.hermes-update-in-progress'
+def uncertain():
+ print('UNCERTAIN');raise SystemExit
def clear():
- try:marker.unlink()
- except FileNotFoundError:pass
- except OSError:pass
+ # Delete only under the updaters' marker mutex and only the bytes judged dead:
+ # a claim published since our read is a fresh claim, never ours to remove.
+ try:
+ try:fd=os.open(str(marker)+'.lock',os.O_RDWR|os.O_CREAT,0o644)
+ except PermissionError:fd=os.open(str(marker)+'.lock',os.O_RDONLY)
+ except OSError:uncertain()
+ try:
+ try:fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB)
+ except OSError:uncertain()
+ try:
+ with marker.open('rb') as stream:
+ if stream.read(257)!=raw:uncertain()
+ marker.unlink()
+ except FileNotFoundError:pass
+ except OSError:uncertain()
+ finally:os.close(fd)
print('CLEAR');raise SystemExit
try:
with marker.open('rb') as stream:raw=stream.read(257)
except FileNotFoundError:
print('CLEAR');raise SystemExit
except OSError:
- print('UNCERTAIN');raise SystemExit
+ uncertain()
if len(raw)>256:
- print('UNCERTAIN');raise SystemExit
-match=re.fullmatch(rb'([1-9][0-9]*)\r?\n([0-9]+)(?:\r?\n)?',raw)
-if not match:
- print('UNCERTAIN');raise SystemExit
-try:
- owner=int(match.group(1));lease=int(match.group(2))
- if owner<1 or owner>4294967295 or lease>9007199254740991:raise ValueError()
-except ValueError:
- print('UNCERTAIN');raise SystemExit
-try:
- os.kill(owner,0)
-except ProcessLookupError:
- clear()
-except PermissionError:
- print('LIVE:'+str(owner));raise SystemExit
-except OSError as error:
- if error.errno==errno.ESRCH:clear()
- elif error.errno==errno.EPERM:print('LIVE:'+str(owner));raise SystemExit
- else:print('UNCERTAIN');raise SystemExit
-try:
- cmd=open('/proc/%d/cmdline'%owner,'rb').read().replace(b'\0',b' ')
-except OSError:
- cmd=b''
-if cmd and b'update' not in cmd:
- clear()
-print('LIVE:'+str(owner))
+ uncertain()
+# v1 is "<pid>\n<started_at>\n"; v2 adds a creation-time line 3 and tagged lines 4+
+# (the first well-formed "delegate:<pid> ct:<ct>" names a second live holder).
+lines=[line[:-1] if line.endswith(b'\r') else line for line in raw.split(b'\n')]
+if lines[-1]==b'':lines.pop()
+if len(lines)<2 or not re.fullmatch(rb'[1-9][0-9]*',lines[0]) or not re.fullmatch(rb'[0-9]+',lines[1]):
+ uncertain()
+delegates=[re.fullmatch(rb'delegate:([1-9][0-9]*) ct:[0-9]+(?:\.[0-9]+)?',line) for line in lines[3:]]
+holders=[int(lines[0])]+[int(match.group(1)) for match in delegates if match][:1]
+if any(pid>4294967295 for pid in holders) or int(lines[1])>9007199254740991:
+ uncertain()
+def live(pid):
+ try:
+ os.kill(pid,0)
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True
+ except OSError as error:
+ if error.errno==errno.ESRCH:return False
+ if error.errno==errno.EPERM:return True
+ uncertain()
+ try:
+ cmd=open('/proc/%d/cmdline'%pid,'rb').read().replace(b'\0',b' ')
+ except OSError:
+ cmd=b''
+ return not cmd or b'update' in cmd
+for pid in holders:
+ if live(pid):
+ print('LIVE:'+str(pid));raise SystemExit
+clear()
`
/**