The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): bound background profile hydration retries
KoNit-K68e48331349c
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex e280da3368d..684178c4ac0 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -292,6 +292,9 @@ import {import { evictPoolEntries } from './pool-eviction'import { clampPoolLimits, parsePoolLimits, POOL_LIMITS_DEFAULTS } from './pool-limits'import {+ BackgroundSlotRetryBackoff,+ BackgroundSlotRetryDeferredError,+ isBackgroundSlotRetryDeferred,isBackgroundSlotWaitTimeout,LocalBackendSpawnCoordinator,type LocalBackendSpawnPriority,@@ -1524,6 +1527,7 @@ let poolLimits = readPersistedPoolLimits()// above is soft — it spares keepalive-fresh entries). Follows the live// preference: setPoolLimits() pushes a new max into the coordinator.const localBackendSpawnCoordinator = new LocalBackendSpawnCoordinator(poolLimits.maxBackends)+const backgroundSlotRetryBackoff = new BackgroundSlotRetryBackoff()// How long a spawn may wait for a free local slot. Must stay under the// renderer's BACKEND_BOOT_WAIT_TIMEOUT_MS (45s, src/lib/with-timeout.ts) so// the queued ticket fails before the renderer does and the user sees why.@@ -1571,12 +1575,16 @@ function assertNotPassiveSpawn(passive: boolean, poolKey: string): void {}}-// Land a spawn failure in desktop.log. A background slot-wait timeout is-// routine under a saturated pool (the next hydration pass retries), so it is-// logged as such instead of as a backend-start failure.+// Land a spawn failure in desktop.log. Background slot waits back off per+// profile under a saturated pool, so a roster refresh cannot create a retry+// storm while a user-triggered foreground open still gets its reserved slot.function logPoolSpawnFailure(label: string, error: unknown): void {+ if (isBackgroundSlotRetryDeferred(error)) {+ return+ }+if (isBackgroundSlotWaitTimeout(error)) {- rememberLog(`Profile backend ${label} slot wait timed out (background); will retry on the next hydration`)+ rememberLog(`Profile backend ${label} slot wait timed out (background); retry is backing off`)} else {rememberLog(`Hermes backend for profile ${label} failed to start: ${error instanceof Error ? error.message : String(error)}`@@ -12498,6 +12506,17 @@ async function runPoolBackendStart(profile, entry, opts: { forceLocal?: boolean;assertPoolEntryStillOwned(poolKey, entry)+ // A deleted profile must not occupy a queued pool slot while a stale roster+ // hydration is waiting. Keep the final boundary below as well to fence a+ // delete that races an already-granted request.+ assertLocalProfileCanStart(profile, profileDeletionGate, key =>+ directoryExists(path.join(HERMES_HOME, 'profiles', key))+ )++ if (spawnPriority === 'background' && !backgroundSlotRetryBackoff.canAttempt(poolKey)) {+ throw new BackgroundSlotRetryDeferredError(profile)+ }+const spawnRequest = localBackendSpawnCoordinator.request(poolKey, {timeoutMs: POOL_SLOT_WAIT_MS,priority: spawnPriority@@ -12517,6 +12536,12 @@ async function runPoolBackendStart(profile, entry, opts: { forceLocal?: boolean;try {entry.releaseLocalBackendSlot = await spawnRequest.acquired+ backgroundSlotRetryBackoff.clear(poolKey)+ } catch (error) {+ if (isBackgroundSlotWaitTimeout(error)) {+ backgroundSlotRetryBackoff.recordFailure(poolKey)+ }+ throw error} finally {localBackendLifecycle.signal.removeEventListener('abort', cancelRequest)}diff --git a/apps/desktop/electron/pool-spawn-coordinator.test.ts b/apps/desktop/electron/pool-spawn-coordinator.test.tsindex 31240e8a600..22c7e844b71 100644--- a/apps/desktop/electron/pool-spawn-coordinator.test.ts+++ b/apps/desktop/electron/pool-spawn-coordinator.test.ts@@ -7,6 +7,7 @@ import { fileURLToPath } from 'node:url'import { test } from 'vitest'import {+ BackgroundSlotRetryBackoff,LocalBackendSlotWaitTimeoutError,LocalBackendSpawnCoordinator,releaseLocalBackendSlotAfterExit@@ -24,6 +25,20 @@ const deferred = () => {const flush = () => new Promise<void>(resolve => setImmediate(resolve))+test('background slot failures back off per profile and clear after a later success', () => {+ const retries = new BackgroundSlotRetryBackoff({ baseDelayMs: 1_000, maxDelayMs: 8_000 })++ assert.equal(retries.canAttempt('over-cap', 0), true)+ assert.equal(retries.recordFailure('over-cap', 0), 1_000)+ assert.equal(retries.canAttempt('over-cap', 999), false)+ assert.equal(retries.canAttempt('over-cap', 1_000), true)+ assert.equal(retries.recordFailure('over-cap', 1_000), 2_000)+ assert.equal(retries.canAttempt('other-profile', 1_001), true)++ retries.clear('over-cap')+ assert.equal(retries.canAttempt('over-cap', 1_001), true)+})+test('100 concurrent local requests never hold more than the configured slots', async () => {const limit = 12const coordinator = new LocalBackendSpawnCoordinator(limit)diff --git a/apps/desktop/electron/pool-spawn-coordinator.ts b/apps/desktop/electron/pool-spawn-coordinator.tsindex 5f80af332d3..1f7be04c6a3 100644--- a/apps/desktop/electron/pool-spawn-coordinator.ts+++ b/apps/desktop/electron/pool-spawn-coordinator.ts@@ -42,6 +42,57 @@ export function isBackgroundSlotWaitTimeout(error: unknown): boolean {return error instanceof LocalBackendSlotWaitTimeoutError && error.silent}+/** A retry deferment is expected background control flow, not a start failure. */+export class BackgroundSlotRetryDeferredError extends Error {+ constructor(key: string) {+ super(`Local backend start for "${key}" is backing off after slot saturation.`)+ this.name = 'BackgroundSlotRetryDeferredError'+ }+}++export function isBackgroundSlotRetryDeferred(error: unknown): boolean {+ return error instanceof BackgroundSlotRetryDeferredError+}++/**+ * Per-profile cooldown for background hydration after a pool-slot timeout.+ *+ * A full local pool is commonly structural (more profiles than the configured+ * cap), so retrying every roster refresh creates a permanent timeout and log+ * storm. Foreground opens bypass this guard; a successful slot acquisition+ * clears it. Keeping this state outside the coordinator preserves its role as+ * a fair slot allocator rather than teaching it about hydration policy.+ */+export class BackgroundSlotRetryBackoff {+ #failures = new Map<string, { nextRetryAt: number; attempts: number }>()+ readonly #baseDelayMs: number+ readonly #maxDelayMs: number++ constructor({ baseDelayMs = 60_000, maxDelayMs = 15 * 60_000 } = {}) {+ if (!Number.isFinite(baseDelayMs) || baseDelayMs < 1 || !Number.isFinite(maxDelayMs) || maxDelayMs < baseDelayMs) {+ throw new RangeError('Background slot retry delays must be positive and ordered.')+ }++ this.#baseDelayMs = baseDelayMs+ this.#maxDelayMs = maxDelayMs+ }++ canAttempt(key: string, now = Date.now()): boolean {+ return (this.#failures.get(key)?.nextRetryAt ?? 0) <= now+ }++ recordFailure(key: string, now = Date.now()): number {+ const attempts = (this.#failures.get(key)?.attempts ?? 0) + 1+ const delay = Math.min(this.#baseDelayMs * 2 ** (attempts - 1), this.#maxDelayMs)+ this.#failures.set(key, { attempts, nextRetryAt: now + delay })+ return delay+ }++ clear(key: string): void {+ this.#failures.delete(key)+ }+}+export async function releaseLocalBackendSlotAfterExit(release: ReleaseLocalBackendSlot,waitForExit: () => Promise<void>diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex d95f8182a69..d747a48a10c 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -101,8 +101,13 @@ def _start_desktop_cron_ticker(stop_event: "threading.Event", interval: int = 60_check_gateway_running, _served_by_running_multiplexer, profiles_to_serve)# Same served set as the multiplexer: default + every live profile under profiles/.- profile_homes = list(profiles_to_serve(multiplex=True))- if profile_homes:+ # The ticker re-enumerates this callable every cycle. Passing a+ # startup snapshot leaves deleted profiles in the scheduler until+ # restart, which both writes their removed stores and keeps stale+ # profiles alive in Desktop's background work.+ profile_homes = lambda: list(profiles_to_serve(multiplex=True))+ initial_profile_homes = profile_homes()+ if initial_profile_homes:# Even one profile needs the per-tick gateway gate; otherwise# Desktop races its dedicated gateway for the same cron store.start_kwargs["profile_homes"] = profile_homes@@ -115,11 +120,11 @@ def _start_desktop_cron_ticker(stop_event: "threading.Event", interval: int = 60or (name != "default" and _served_by_running_multiplexer(name)))from hermes_logging import enable_profile_log_routing- enable_profile_log_routing(profile_homes)+ enable_profile_log_routing(initial_profile_homes)_log.info("Desktop cron scheduler will tick %d profile(s): %s",- len(profile_homes),- [name for name, _home in profile_homes],+ len(initial_profile_homes),+ [name for name, _home in initial_profile_homes],)except Exception:# Fail open to the single-store ticker so the active profile keeps firing.diff --git a/tests/hermes_cli/test_desktop_cron_ticker_profiles.py b/tests/hermes_cli/test_desktop_cron_ticker_profiles.pyindex d112f28d3ca..e4b1f58bae0 100644--- a/tests/hermes_cli/test_desktop_cron_ticker_profiles.py+++ b/tests/hermes_cli/test_desktop_cron_ticker_profiles.py@@ -67,7 +67,12 @@ def test_multi_profile_homes_passed_to_builtin(monkeypatch, _providers, tmp_pathassert builtin.start_kwargs is not Noneassert builtin.start_kwargs["interval"] == 7- assert builtin.start_kwargs["profile_homes"] == homes+ profile_homes = builtin.start_kwargs["profile_homes"]+ assert callable(profile_homes)+ assert profile_homes() == homes++ homes.pop()+ assert profile_homes() == homes@pytest.mark.parametrize("gateway_running", [True, False])@@ -155,7 +160,9 @@ def test_desktop_ticker_serves_every_profile_and_yields_to_owning_gateway(monkeyws._start_desktop_cron_ticker(threading.Event(), interval=0)- assert [name for name, _ in builtin.start_kwargs["profile_homes"]] == [+ profile_homes = builtin.start_kwargs["profile_homes"]+ assert callable(profile_homes)+ assert [name for name, _ in profile_homes()] == ["default", "guest", "solo", "worker"]gate = builtin.start_kwargs["profile_gate"]assert gate("default", root) is True