Skip to content

The agent that grows with you

fix(desktop): await pooled backend teardown

giga corpc07171209a47
diff --git a/apps/desktop/electron/backend-lifecycle.test.ts b/apps/desktop/electron/backend-lifecycle.test.ts
new file mode 100644
index 00000000000..e91823fda2b
--- /dev/null
+++ b/apps/desktop/electron/backend-lifecycle.test.ts
@@ -0,0 +1,49 @@
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import path from 'node:path'
+import test from 'node:test'
+import { fileURLToPath } from 'node:url'
+
+const source = fs
+ .readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), 'main.ts'), 'utf8')
+ .replace(/\r\n/g, '\n')
+
+test('pool backend teardown waits for bounded exit before dropping lifecycle state', () => {
+ const start = source.indexOf('async function stopPoolBackend(profile)')
+ assert.notEqual(start, -1)
+ const snippet = source.slice(start, start + 1200)
+
+ assert.match(snippet, /poolStops\.get\(profile\)/)
+ assert.match(snippet, /stopBackendChild\(entry\.process\)/)
+ assert.match(snippet, /await waitForBackendExit\(entry\.process\)/)
+ assert.match(snippet, /backendPool\.delete\(profile\)/)
+ assert.ok(
+ snippet.indexOf('await waitForBackendExit(entry.process)') < snippet.indexOf('backendPool.delete(profile)'),
+ 'pool state must remain owned until the child exits or is escalated'
+ )
+})
+
+test('repeated pool cleanup reuses one in-flight teardown', () => {
+ const start = source.indexOf('async function stopPoolBackend(profile)')
+ const snippet = source.slice(start, start + 1200)
+
+ assert.match(snippet, /if \(stopping\) \{\s*return stopping\s*\}/)
+ assert.match(snippet, /poolStops\.set\(profile, stop\)/)
+ assert.match(snippet, /poolStops\.delete\(profile\)/)
+
+ const ensure = source.slice(source.indexOf('async function ensureBackend(profile)'), source.indexOf('async function ensureBackend(profile)') + 700)
+ assert.match(ensure, /const stopping = poolStops\.get\(key\)/)
+ assert.match(ensure, /if \(stopping\) \{\s*await stopping\s*\}/)
+})
+
+test('desktop quit waits for primary and pool backend teardown exactly once', () => {
+ const start = source.indexOf("app.on('before-quit'")
+ assert.notEqual(start, -1)
+ const snippet = source.slice(start, start + 1800)
+
+ assert.match(snippet, /event\.preventDefault\(\)/)
+ assert.match(snippet, /if \(backendQuitPromise\)/)
+ assert.match(snippet, /waitForBackendExit\(dying\)/)
+ assert.match(snippet, /stopAllPoolBackends\(\)/)
+ assert.match(snippet, /backendQuitReady = true\s*app\.quit\(\)/)
+})
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 892f34b2599..eaa30f2851c 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -236,6 +236,7 @@ import {
undialedSshRouteSeeds
} from './plugin-profile-routes'
import { selectPoolEvictions } from './pool-eviction'
+import { createPoolStopper } from './pool-stop'
import { poolTouchKeys } from './pool-touch-scope'
import { createKeepAwake } from './power-save'
import { FirstRunSetupResetError, runPrimaryBackendStartup } from './primary-backend-startup'
@@ -9532,6 +9533,21 @@ async function ensureBackend(profile) {
: connection
}
+ const stopping = poolStopper.inFlight(key)
+
+ if (stopping) {
+ await stopping
+ }
+
+ // A backend for this key may still be dying (idle reap, LRU eviction, a
+ // just-finished delete). Wait for its bounded exit before reusing or
+ // spawning, so two children never share one profile's HERMES_HOME.
+ const stopping = poolStopper.inFlight(key)
+
+ if (stopping) {
+ await stopping
+ }
+
const existing = backendPool.get(key)
if (existing) {
@@ -9605,6 +9621,12 @@ async function ensureRegistryBackend(connectionId, profile) {
return ensureBackend(profile)
}
+ const stoppingLocal = poolStopper.inFlight(localRoute.poolKey)
+
+ if (stoppingLocal) {
+ await stoppingLocal
+ }
+
const existingLocal = backendPool.get(localRoute.poolKey)
if (existingLocal) {
@@ -10024,49 +10046,42 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; po
}
}
-function stopPoolBackend(profile) {
- const entry = backendPool.get(profile)
-
- if (!entry) {
- return
- }
+// Bounded, deduplicated pool teardown (see pool-stop.ts): every stop path —
+// idle reaper, LRU eviction, profile delete/rename, quit — shares one
+// in-flight stop per key and retains the process handle until the bounded
+// SIGTERM -> SIGKILL escalation in waitForBackendExit() resolves. Previously
+// SIGTERM + immediate entry delete dropped the handle and a slow child
+// survived detached under PID 1.
+const poolStopper = createPoolStopper({
+ pool: backendPool,
+ stopChild: child => stopBackendChild(child),
+ waitForExit: child => waitForBackendExit(child)
+})
- backendPool.delete(profile)
- stopBackendChild(entry.process)
+function stopPoolBackend(profile) {
+ return poolStopper.stop(profile)
}
async function teardownPoolBackendAndWait(profile) {
- const entries = localProfilePoolKeys(profile)
- .map(key => ({ entry: backendPool.get(key), key }))
- .filter(item => item.entry)
-
- for (const { entry, key } of entries) {
- backendPool.delete(key)
- stopBackendChild(entry.process)
- }
-
- await Promise.all(entries.map(({ entry }) => waitForBackendExit(entry.process)))
+ await Promise.all(localProfilePoolKeys(profile).map(key => poolStopper.stop(key)))
}
function stopAllPoolBackends() {
- for (const profile of [...backendPool.keys()]) {
- stopPoolBackend(profile)
- }
+ return poolStopper.stopAll()
}
const backendShutdown = createBackendShutdownCoordinator(async () => {
const primary = backendConnectionState.invalidate()
- const pooled = [...backendPool.values()].map(entry => entry.process).filter(Boolean)
stopBackendChild(primary)
- stopAllPoolBackends()
+ const pooledStops = stopAllPoolBackends()
if (poolIdleReaper) {
clearInterval(poolIdleReaper)
poolIdleReaper = null
}
- await Promise.all([waitForBackendExit(primary), ...pooled.map(child => waitForBackendExit(child))])
+ await Promise.all([waitForBackendExit(primary), pooledStops])
})
async function exitAfterBackendShutdown(code) {
diff --git a/apps/desktop/electron/pool-stop.ts b/apps/desktop/electron/pool-stop.ts
new file mode 100644
index 00000000000..767a65e1748
--- /dev/null
+++ b/apps/desktop/electron/pool-stop.ts
@@ -0,0 +1,86 @@
+/**
+ * pool-stop.ts
+ *
+ * Bounded, deduplicated teardown for pooled profile backends.
+ *
+ * Idle reaping, LRU eviction, profile deletion, and app quit can all ask to
+ * stop the same pooled backend, and historically each caller SIGTERM'd the
+ * child and immediately deleted the pool entry. A child that did not exit
+ * promptly lost its only handle and survived detached under PID 1 — a live
+ * installation accumulated 41 orphaned profile backends this way.
+ *
+ * createPoolStopper() gives every caller the same contract instead:
+ * - the pool entry is evicted immediately (no router hands out a dying
+ * backend), but the stop promise keeps the process handle until the
+ * bounded SIGTERM -> SIGKILL escalation in waitForExit resolves;
+ * - concurrent stop requests for one key share the single in-flight stop;
+ * - spawn paths can await inFlight(key) so a fresh child never overlaps a
+ * dying one on the same HERMES_HOME.
+ *
+ * Extracted into a dependency-free module (same pattern as backend-child.ts /
+ * pool-eviction.ts) so the dedup and handle-retention semantics are asserted
+ * directly instead of grepping main.ts source text.
+ */
+
+export interface PoolStopEntry {
+ process?: unknown
+}
+
+export interface PoolStopperDeps {
+ /** The live backend pool. Entries are evicted synchronously on stop. */
+ pool: Map<string, PoolStopEntry>
+ /** Signal the child (tree/group kill per platform). Synchronous. */
+ stopChild: (child: unknown) => void
+ /** Bounded wait: resolves when the child exits, escalating to SIGKILL. */
+ waitForExit: (child: unknown) => Promise<void>
+}
+
+export interface PoolStopper {
+ /** The in-flight stop for a key, if any — await before respawning it. */
+ inFlight: (key: string) => Promise<void> | undefined
+ /** Stop one pooled backend; concurrent calls share the same promise. */
+ stop: (key: string) => Promise<void>
+ /** Stop every pooled backend currently in the pool. */
+ stopAll: () => Promise<void>
+}
+
+export function createPoolStopper(deps: PoolStopperDeps): PoolStopper {
+ const stops = new Map<string, Promise<void>>()
+
+ function stop(key: string): Promise<void> {
+ const inFlight = stops.get(key)
+
+ if (inFlight) {
+ return inFlight
+ }
+
+ const entry = deps.pool.get(key)
+
+ if (!entry) {
+ return Promise.resolve()
+ }
+
+ // Evict now: routing must not hand out a dying backend. The stop promise
+ // below retains the process handle until the bounded exit completes.
+ deps.pool.delete(key)
+
+ const stopping = (async () => {
+ deps.stopChild(entry.process)
+ await deps.waitForExit(entry.process)
+ })().finally(() => {
+ stops.delete(key)
+ })
+
+ stops.set(key, stopping)
+
+ return stopping
+ }
+
+ return {
+ inFlight: key => stops.get(key),
+ stop,
+ stopAll: async () => {
+ await Promise.all([...deps.pool.keys()].map(stop))
+ }
+ }
+}