Skip to content

The agent that grows with you

fix(desktop): cap concurrent local profile backend spawns

Kryptonatore924615bb1d3
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 4c86f7a8ca9..2efc129649a 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -281,6 +281,11 @@ import {
undialedSshRouteSeeds
} from './plugin-profile-routes'
import { selectPoolEvictions } from './pool-eviction'
+import {
+ type LocalBackendSpawnRequest,
+ LocalBackendSpawnCoordinator,
+ releaseLocalBackendSlotAfterExit
+} from './pool-spawn-coordinator'
import { createPoolStopper } from './pool-stop'
import { poolTouchKeys } from './pool-touch-scope'
import { createKeepAwake } from './power-save'
@@ -1411,6 +1416,7 @@ const profileDeletionGate = new ProfileDeletionGate()
// exist while a non-primary profile is actively being chatted through.
const POOL_MAX_BACKENDS = Math.max(1, Number(process.env.HERMES_DESKTOP_POOL_MAX) || 3)
const POOL_IDLE_MS = Math.max(60_000, Number(process.env.HERMES_DESKTOP_POOL_IDLE_MS) || 10 * 60_000)
+const localBackendSpawnCoordinator = new LocalBackendSpawnCoordinator(POOL_MAX_BACKENDS)
// A backend touched within this window has a live renderer socket (the keepalive
// pings every 60s for every open profile). LRU eviction must spare these — a
@@ -11269,7 +11275,10 @@ async function ensureBackend(profile) {
token: null,
connectionPromise: null,
lastActiveAt: Date.now(),
- remoteBaseUrl: null
+ remoteBaseUrl: null,
+ releaseLocalBackendSlot: null,
+ localBackendSlotKey: null,
+ localBackendSpawnRequest: null
}
entry.connectionPromise = spawnPoolBackend(key, entry).catch(async error => {
@@ -11280,12 +11289,7 @@ async function ensureBackend(profile) {
`Hermes backend for profile "${key}" failed to start: ${error instanceof Error ? error.message : String(error)}`
)
- if (backendPool.get(key) === entry) {
- backendPool.delete(key)
- }
-
- stopBackendChild(entry.process)
- await waitForBackendExit(entry.process)
+ await teardownFailedLocalBackend(key, entry)
throw error
})
backendPool.set(key, entry)
@@ -11437,7 +11441,10 @@ async function ensureRegistryBackend(connectionId, profile, managedUpdateCorrela
token: null,
connectionPromise: null,
lastActiveAt: Date.now(),
- remoteBaseUrl: null
+ remoteBaseUrl: null,
+ releaseLocalBackendSlot: null,
+ localBackendSlotKey: null,
+ localBackendSpawnRequest: null
}
localEntry.connectionPromise = spawnPoolBackend(profileKey, localEntry, {
@@ -11450,12 +11457,7 @@ async function ensureRegistryBackend(connectionId, profile, managedUpdateCorrela
`Hermes backend for profile "${profileKey}" (forced-local) failed to start: ${error instanceof Error ? error.message : String(error)}`
)
- if (backendPool.get(localRoute.poolKey) === localEntry) {
- backendPool.delete(localRoute.poolKey)
- }
-
- stopBackendChild(localEntry.process)
- await waitForBackendExit(localEntry.process)
+ await teardownFailedLocalBackend(localRoute.poolKey, localEntry)
throw error
})
backendPool.set(localRoute.poolKey, localEntry)
@@ -12188,6 +12190,67 @@ function startPoolIdleReaper() {
}
}
+function releaseLocalBackendSlot(entry: any) {
+ if (!entry) {
+ return
+ }
+
+ const release = entry.releaseLocalBackendSlot
+ const request = entry.localBackendSpawnRequest as LocalBackendSpawnRequest | null
+ entry.releaseLocalBackendSlot = null
+ entry.localBackendSlotKey = null
+ entry.localBackendSpawnRequest = null
+
+ if (release) {
+ release()
+ } else {
+ request?.cancel()
+ }
+}
+
+function assertPoolEntryStillOwned(poolKey: string, entry: any) {
+ if (backendPool.get(poolKey) !== entry) {
+ releaseLocalBackendSlot(entry)
+ throw new Error(`Profile backend start for "${poolKey}" was cancelled before spawn.`)
+ }
+}
+
+const failedLocalBackendTeardowns = new WeakMap<object, Promise<void>>()
+
+function teardownFailedLocalBackend(poolKey: string, entry: any): Promise<void> {
+ const existing = failedLocalBackendTeardowns.get(entry)
+
+ if (existing) {
+ return existing
+ }
+
+ if (backendPool.get(poolKey) === entry) {
+ backendPool.delete(poolKey)
+ }
+
+ const child = entry.process
+ const teardown = releaseLocalBackendSlotAfterExit(
+ () => releaseLocalBackendSlot(entry),
+ async () => {
+ stopBackendChild(child)
+ await waitForBackendExit(child)
+
+ if (child && child.exitCode === null && child.signalCode === null) {
+ throw new Error(
+ `Profile backend for "${poolKey}" did not exit; keeping the local slot occupied.`
+ )
+ }
+
+ releaseBackendChild(child)
+ }
+ )
+
+ // Keep the settled promise in the WeakMap for the lifetime of this entry.
+ // Error + exit + outer catch may all request cleanup; none may run it twice.
+ failedLocalBackendTeardowns.set(entry, teardown)
+ return teardown
+}
+
// Spawn an additional dashboard backend pinned to a named profile. Mirrors the
// local-spawn portion of startHermes() but without the boot-progress UI,
// bootstrap, or remote handling (those belong to the primary backend only).
@@ -12225,6 +12288,17 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; po
}
}
+ const spawnRequest = localBackendSpawnCoordinator.request(poolKey, { timeoutMs: POOL_IDLE_MS })
+ entry.localBackendSlotKey = poolKey
+ entry.localBackendSpawnRequest = spawnRequest
+ entry.releaseLocalBackendSlot = await spawnRequest.acquired
+
+ if (entry.localBackendSpawnRequest === spawnRequest) {
+ entry.localBackendSpawnRequest = null
+ }
+
+ assertPoolEntryStillOwned(poolKey, entry)
+
const token = crypto.randomBytes(32).toString('base64url')
// Same update mutual exclusion as the primary window's waitForLocalStart
@@ -12268,12 +12342,12 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; po
assertLocalProfileCanStart(profile, profileDeletionGate, key =>
directoryExists(path.join(HERMES_HOME, 'profiles', key))
)
-
rememberLog(`Starting Hermes backend for profile "${profile}" via ${backend.label}`)
const parentStartMarker = await desktopParentStartMarker()
const backendNonce = crypto.randomBytes(16).toString('hex')
const parentIdentityEnv = parentWatchdogEnv(process.pid, parentStartMarker, backendNonce)
+ assertPoolEntryStillOwned(poolKey, entry)
const child = spawn(
backend.command,
@@ -12328,6 +12402,7 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; po
// surface as an unhandled rejection before the Promise.race below attaches.
portAnnouncement.catch(() => {})
await claimBackendChild(child, `${backend.command} ${backend.args.join(' ')}`, profile, backendNonce, outputTail)
+ assertPoolEntryStillOwned(poolKey, entry)
child.stdout.on('data', rememberLog)
child.stderr.on('data', rememberLog)
@@ -12341,14 +12416,21 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; po
child.once('error', error => {
rememberLog(`Hermes backend for profile "${profile}" failed to start: ${error.message}`)
- releaseBackendChild(child)
- backendPool.delete(poolKey)
+ void teardownFailedLocalBackend(poolKey, entry).catch(cleanupError => {
+ rememberLog(
+ `Hermes backend for profile "${profile}" cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`
+ )
+ })
rejectStart?.(error)
})
child.once('exit', (code, signal) => {
rememberLog(`Hermes backend for profile "${profile}" exited (${signal || code})`)
+ releaseLocalBackendSlot(entry)
releaseBackendChild(child)
- backendPool.delete(poolKey)
+
+ if (backendPool.get(poolKey) === entry) {
+ backendPool.delete(poolKey)
+ }
if (!ready) {
rejectStart?.(
@@ -12416,16 +12498,20 @@ const poolStopper = createPoolStopper({
waitForExit: child => waitForBackendExit(child)
})
-function stopPoolBackend(profile) {
- return poolStopper.stop(profile)
+async function stopPoolBackend(profile: string) {
+ const entry = backendPool.get(profile)
+ await poolStopper.stop(profile)
+ releaseLocalBackendSlot(entry)
}
async function teardownPoolBackendAndWait(profile) {
- await Promise.all(localProfilePoolKeys(profile).map(key => poolStopper.stop(key)))
+ await Promise.all(localProfilePoolKeys(profile).map(key => stopPoolBackend(key)))
}
-function stopAllPoolBackends() {
- return poolStopper.stopAll()
+async function stopAllPoolBackends() {
+ const entries = [...backendPool.values()]
+ await poolStopper.stopAll()
+ entries.forEach(releaseLocalBackendSlot)
}
const backendShutdown = createBackendShutdownCoordinator(async () => {
diff --git a/apps/desktop/electron/pool-spawn-coordinator.test.ts b/apps/desktop/electron/pool-spawn-coordinator.test.ts
new file mode 100644
index 00000000000..2c448142afe
--- /dev/null
+++ b/apps/desktop/electron/pool-spawn-coordinator.test.ts
@@ -0,0 +1,256 @@
+import assert from 'node:assert/strict'
+import { spawn } from 'node:child_process'
+
+import { test } from 'vitest'
+
+import {
+ LocalBackendSpawnCoordinator,
+ releaseLocalBackendSlotAfterExit
+} from './pool-spawn-coordinator'
+
+const deferred = () => {
+ let resolve!: () => void
+ const promise = new Promise<void>(done => {
+ resolve = done
+ })
+ return { promise, resolve }
+}
+
+const flush = () => new Promise<void>(resolve => setImmediate(resolve))
+
+test('100 concurrent local requests never hold more than the configured slots', async () => {
+ const limit = 12
+ const coordinator = new LocalBackendSpawnCoordinator(limit)
+ const gates = Array.from({ length: 100 }, deferred)
+ let active = 0
+ let maxActive = 0
+
+ const tasks = gates.map(async (gate, index) => {
+ const release = await coordinator.acquire(`profile-${index}`)
+ active += 1
+ maxActive = Math.max(maxActive, active)
+
+ await gate.promise
+
+ active -= 1
+ release()
+ })
+
+ await flush()
+ assert.equal(active, limit)
+ assert.equal(coordinator.activeCount, limit)
+ assert.equal(coordinator.queuedCount, 100 - limit)
+
+ for (let start = 0; start < gates.length; start += limit) {
+ for (const gate of gates.slice(start, start + limit)) {
+ gate.resolve()
+ }
+ await flush()
+ }
+
+ await Promise.all(tasks)
+ assert.equal(maxActive, limit)
+ assert.equal(coordinator.activeCount, 0)
+ assert.equal(coordinator.queuedCount, 0)
+})
+
+test('a queued start can be cancelled without waiting for an active backend', async () => {
+ const coordinator = new LocalBackendSpawnCoordinator(1)
+ const releaseFirst = await coordinator.acquire('first')
+ const queued = coordinator.request('cancelled')
+
+ assert.equal(coordinator.queuedCount, 1)
+ assert.equal(queued.cancel(), true)
+ await assert.rejects(queued.acquired, /cancelled while queued/)
+ assert.equal(coordinator.activeCount, 1)
+ assert.equal(coordinator.queuedCount, 0)
+
+ releaseFirst()
+ assert.equal(coordinator.activeCount, 0)
+})
+
+test('cancelling an old same-key request never rejects a newer waiter', async () => {
+ const coordinator = new LocalBackendSpawnCoordinator(1)
+ const blocker = coordinator.request('blocker')
+ const releaseBlocker = await blocker.acquired
+ const old = coordinator.request('same-profile')
+
+ releaseBlocker()
+ const newer = coordinator.request('same-profile')
+
+ assert.equal(old.cancel(), false, 'the old request was already granted')
+ assert.equal(coordinator.queuedCount, 1, 'the newer same-key waiter must remain queued')
+
+ const releaseOld = await old.acquired
+ releaseOld()
+ const releaseNewer = await newer.acquired
+ releaseNewer()
+
+ assert.equal(coordinator.activeCount, 0)
+ assert.equal(coordinator.queuedCount, 0)
+})
+
+test('a queued start times out with a clear error and frees its queue position', async () => {
+ const coordinator = new LocalBackendSpawnCoordinator(1)
+ const releaseFirst = await coordinator.acquire('first')
+ const queued = coordinator.request('timed-out', { timeoutMs: 10 })
+
+ await assert.rejects(queued.acquired, /timed out while waiting for a free slot/)
+ assert.equal(coordinator.activeCount, 1)
+ assert.equal(coordinator.queuedCount, 0)
+
+ releaseFirst()
+ assert.equal(coordinator.activeCount, 0)
+})
+
+test('100 real child processes never exceed twelve simultaneous local slots', async () => {
+ const limit = 12
+ const coordinator = new LocalBackendSpawnCoordinator(limit)
+ const livePids = new Set<number>()
+ const seenPids = new Set<number>()
+ let maxLive = 0
+
+ await Promise.all(
+ Array.from({ length: 100 }, async (_, index) => {
+ const release = await coordinator.acquire(`real-profile-${index}`)
+
+ try {
+ const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 40)'], {
+ stdio: 'ignore'
+ })
+ assert.ok(child.pid)
+ livePids.add(child.pid)
+ seenPids.add(child.pid)
+ maxLive = Math.max(maxLive, livePids.size)
+
+ await new Promise<void>((resolve, reject) => {
+ child.once('error', reject)
+ child.once('exit', code => {
+ if (code === 0) {
+ resolve()
+ } else {
+ reject(new Error(`child ${child.pid} exited with ${code}`))
+ }
+ })
+ })
+
+ livePids.delete(child.pid)
+ } finally {
+ release()
+ }
+ })
+ )
+
+ assert.equal(seenPids.size, 100)
+ assert.equal(maxLive, limit)
+ assert.equal(livePids.size, 0)
+ assert.equal(coordinator.activeCount, 0)
+ assert.equal(coordinator.queuedCount, 0)
+})
+
+test('failed start keeps its slot until the child has actually exited', async () => {
+ const coordinator = new LocalBackendSpawnCoordinator(1)
+ const childExit = deferred()
+ const releaseFailed = await coordinator.acquire('failed')
+ let successorEntered = false
+ const successor = coordinator.acquire('successor').then(release => {
+ successorEntered = true
+ return release
+ })
+
+ const cleanup = releaseLocalBackendSlotAfterExit(releaseFailed, () => childExit.promise)
+ await flush()
+
+ assert.equal(successorEntered, false)
+ assert.equal(coordinator.activeCount, 1)
+ assert.equal(coordinator.queuedCount, 1)
+
+ childExit.resolve()
+ await cleanup
+ const releaseSuccessor = await successor
+
+ assert.equal(successorEntered, true)
+ assert.equal(coordinator.activeCount, 1)
+ assert.equal(coordinator.queuedCount, 0)
+
+ releaseSuccessor()
+ assert.equal(coordinator.activeCount, 0)
+})
+
+test('a rejected wait keeps the slot occupied', async () => {
+ const coordinator = new LocalBackendSpawnCoordinator(1)
+ const releaseFailed = await coordinator.acquire('failed')
+ let successorEntered = false
+ const successor = coordinator.acquire('successor').then(release => {
+ successorEntered = true
+ return release
+ })
+
+ const cleanup = releaseLocalBackendSlotAfterExit(releaseFailed, async () => {
+ throw new Error('exit unproven')
+ })
+
+ await assert.rejects(cleanup, /exit unproven/)
+ await flush()
+
+ assert.equal(successorEntered, false)
+ assert.equal(coordinator.activeCount, 1)
+ assert.equal(coordinator.queuedCount, 1)
+
+ releaseFailed()
+ const releaseSuccessor = await successor
+ assert.equal(successorEntered, true)
+ releaseSuccessor()
+ assert.equal(coordinator.activeCount, 0)
+ assert.equal(coordinator.queuedCount, 0)
+})
+
+test('an invalid timeout never enqueues a waiter', async () => {
+ const coordinator = new LocalBackendSpawnCoordinator(1)
+ const releaseFirst = await coordinator.acquire('first')
+
+ assert.throws(
+ () => coordinator.request('invalid', { timeoutMs: 0 }),
+ /timeout must be a positive number/
+ )
+ assert.throws(
+ () => coordinator.request('invalid', { timeoutMs: Number.NaN }),
+ /timeout must be a positive number/
+ )
+ assert.throws(
+ () => coordinator.request('invalid', { timeoutMs: -5 }),
+ /timeout must be a positive number/
+ )
+
+ assert.equal(coordinator.activeCount, 1)
+ assert.equal(coordinator.queuedCount, 0)
+
+ releaseFirst()
+ assert.equal(coordinator.activeCount, 0)
+})
+
+test('a failed or repeated cleanup releases exactly one slot', async () => {
+ const coordinator = new LocalBackendSpawnCoordinator(1)
+ const releaseFirst = await coordinator.acquire('first')
+ let secondEntered = false
+ const second = coordinator.acquire('second').then(release => {
+ secondEntered = true
+ return release
+ })
+
+ await flush()
+ assert.equal(secondEntered, false)
+ assert.equal(coordinator.activeCount, 1)
+ assert.equal(coordinator.queuedCount, 1)
+
+ releaseFirst()
+ releaseFirst()
+ const releaseSecond = await second
+
+ assert.equal(secondEntered, true)
+ assert.equal(coordinator.activeCount, 1)
+ assert.equal(coordinator.queuedCount, 0)
+
+ releaseSecond()
+ assert.equal(coordinator.activeCount, 0)
+})
diff --git a/apps/desktop/electron/pool-spawn-coordinator.ts b/apps/desktop/electron/pool-spawn-coordinator.ts
new file mode 100644
index 00000000000..e847981ccfb
--- /dev/null
+++ b/apps/desktop/electron/pool-spawn-coordinator.ts
@@ -0,0 +1,128 @@
+export type ReleaseLocalBackendSlot = () => void
+
+export type LocalBackendSpawnRequest = {
+ acquired: Promise<ReleaseLocalBackendSlot>
+ cancel: () => boolean
+}
+
+type Waiter = {
+ key: string
+ resolve: (release: ReleaseLocalBackendSlot) => void
+ reject: (error: Error) => void
+ timer: ReturnType<typeof setTimeout> | null
+}
+
+export async function releaseLocalBackendSlotAfterExit(
+ release: ReleaseLocalBackendSlot,
+ waitForExit: () => Promise<void>
+): Promise<void> {
+ await waitForExit()
+ release()
+}
+
+/**
+ * Bounds the number of local profile backends that are starting or running.
+ *
+ * A lease is acquired immediately before local start work and is held until
+ * the child exits or the start fails. Remote descriptors never call request().
+ */
+export class LocalBackendSpawnCoordinator {
+ readonly #limit: number
+ #active = 0
+ #queue: Waiter[] = []
+
+ constructor(limit: number) {
+ if (!Number.isInteger(limit) || limit < 1) {
+ throw new RangeError('Local backend spawn limit must be a positive integer.')
+ }
+
+ this.#limit = limit
+ }
+
+ get activeCount(): number {
+ return this.#active
+ }
+
+ get queuedCount(): number {
+ return this.#queue.length
+ }
+
+ request(key: string, options: { timeoutMs?: number } = {}): LocalBackendSpawnRequest {
+ if (options.timeoutMs !== undefined && (!Number.isFinite(options.timeoutMs) || options.timeoutMs < 1)) {
+ throw new RangeError('Local backend spawn timeout must be a positive number.')
+ }
+
+ if (this.#active < this.#limit) {
+ return {
+ acquired: Promise.resolve(this.#grant()),
+ cancel: () => false
+ }
+ }
+
+ let waiter!: Waiter
+ const acquired = new Promise<ReleaseLocalBackendSlot>((resolve, reject) => {
+ waiter = { key, resolve, reject, timer: null }
+ this.#queue.push(waiter)
+
+ if (options.timeoutMs !== undefined) {
+ waiter.timer = setTimeout(() => {
+ this.#rejectWaiter(
+ waiter,
+ new Error(`Local backend start for "${key}" timed out while waiting for a free slot.`)
+ )
+ }, options.timeoutMs)
+ waiter.timer.unref?.()
+ }
+ })
+
+ return {
+ acquired,
+ cancel: () =>
+ this.#rejectWaiter(waiter, new Error(`Local backend start for "${key}" was cancelled while queued.`))
+ }
+ }
+
+ acquire(key: string): Promise<ReleaseLocalBackendSlot> {
+ return this.request(key).acquired
+ }
+
+ #rejectWaiter(waiter: Waiter, error: Error): boolean {
+ const index = this.#queue.indexOf(waiter)
+
+ if (index === -1) {
+ return false
+ }
+
+ this.#queue.splice(index, 1)
+ this.#clearTimer(waiter)
+ waiter.reject(error)
+ return true
+ }
+
+ #clearTimer(waiter: Waiter): void {
+ if (waiter.timer) {
+ clearTimeout(waiter.timer)
+ waiter.timer = null
+ }
+ }
+
+ #grant(): ReleaseLocalBackendSlot {
+ this.#active += 1
+ let released = false
+
+ return () => {
+ if (released) {
+ return
+ }
+
+ released = true
+ this.#active -= 1
+ const next = this.#queue.shift()
+
+ if (next) {
+ this.#clearTimer(next)
+ next.resolve(this.#grant())
+ }
+ }
+ }
+}