From 3045a385fbe767c4c0b050092bfb8c1d802c5571 Mon Sep 17 00:00:00 2001 From: Ho Lim Date: Sun, 26 Apr 2026 16:40:38 -0700 Subject: [PATCH 01/15] perf(onboard): add deadline-based gateway wait --- src/lib/onboard.ts | 54 +++++++++++------- src/lib/wait.ts | 78 ++++++++++++++++++++++++++ test/wait.test.ts | 134 ++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 246 insertions(+), 20 deletions(-) diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 3b98af71abe..a01de56517e 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -77,7 +77,7 @@ const { DEFAULT_CLOUD_MODEL, getProviderSelectionConfig, parseGatewayInference } // Shared constant so getSuggestedPolicyPresets() and setupPoliciesWithSelection() // stay in sync. const LOCAL_INFERENCE_PROVIDERS: string[] = ["ollama-local", "vllm-local"]; -const { sleepSeconds } = require("./wait"); +const { sleepSeconds, waitUntil }: typeof import("./wait") = require("./wait"); const platformUtils: typeof import("./platform") = require("./platform"); const { inferContainerRuntime, isWsl, shouldPatchCoredns } = platformUtils; const { resolveOpenshell } = require("./resolve-openshell"); @@ -3510,24 +3510,40 @@ async function startGatewayWithOptions( const healthPollCount = healthWait.count; const healthPollInterval = healthWait.interval; - for (let i = 0; i < healthPollCount; i++) { - const repairResult = repairGatewayBootstrapSecrets(); - if (repairResult.repaired) { - attachGatewayMetadataIfNeeded({ forceRefresh: true }); - } else if (gatewayClusterHealthcheckPassed()) { - attachGatewayMetadataIfNeeded(); - } - // Ensure the gateway remains selected before each probe. - runCaptureOpenshell(["gateway", "select", GATEWAY_NAME], { ignoreError: true }); - const status = runCaptureOpenshell(["status"], { ignoreError: true }); - const namedInfo = runCaptureOpenshell(["gateway", "info", "-g", GATEWAY_NAME], { - ignoreError: true, - }); - const currentInfo = runCaptureOpenshell(["gateway", "info"], { ignoreError: true }); - if (isGatewayHealthy(status, namedInfo, currentInfo)) { - return; // success - } - if (i < healthPollCount - 1) sleep(healthPollInterval); + const healthPollIntervalMs = Math.max(0, healthPollInterval * 1000); + const healthDeadlineMs = + Date.now() + + Math.max(0, healthPollCount - 1) * healthPollIntervalMs + + (healthPollIntervalMs === 0 ? 1 : 0); + const gatewayBecameHealthy = + healthPollCount > 0 && + waitUntil( + () => { + const repairResult = repairGatewayBootstrapSecrets(); + if (repairResult.repaired) { + attachGatewayMetadataIfNeeded({ forceRefresh: true }); + } else if (gatewayClusterHealthcheckPassed()) { + attachGatewayMetadataIfNeeded(); + } + // Ensure the gateway remains selected before each probe. + runCaptureOpenshell(["gateway", "select", GATEWAY_NAME], { ignoreError: true }); + const status = runCaptureOpenshell(["status"], { ignoreError: true }); + const namedInfo = runCaptureOpenshell(["gateway", "info", "-g", GATEWAY_NAME], { + ignoreError: true, + }); + const currentInfo = runCaptureOpenshell(["gateway", "info"], { ignoreError: true }); + return isGatewayHealthy(status, namedInfo, currentInfo); + }, + { + deadlineMs: healthDeadlineMs, + initialIntervalMs: healthPollIntervalMs, + maxIntervalMs: healthPollIntervalMs, + backoffFactor: 1, + maxAttempts: healthPollCount, + }, + ); + if (gatewayBecameHealthy) { + return; } throw new Error("Gateway failed to start"); diff --git a/src/lib/wait.ts b/src/lib/wait.ts index e942893e83f..c202eb12663 100644 --- a/src/lib/wait.ts +++ b/src/lib/wait.ts @@ -5,6 +5,27 @@ * Synchronous waiting primitives for CLI commands. */ +export type WaitUntilOptions = { + /** Absolute deadline, in milliseconds, using the same clock as `now`. */ + deadlineMs: number; + /** First delay between failed attempts. */ + initialIntervalMs?: number; + /** Maximum delay between failed attempts after backoff. */ + maxIntervalMs?: number; + /** Multiplier applied to the interval after each failed attempt. */ + backoffFactor?: number; + /** Optional cap on condition attempts, including the first immediate check. */ + maxAttempts?: number; + /** Clock used for deadline comparisons. Defaults to Date.now. */ + now?: () => number; + /** Blocking sleep function. Defaults to sleepMs. */ + sleep?: (ms: number) => void; +}; + +const DEFAULT_INITIAL_INTERVAL_MS = 250; +const DEFAULT_MAX_INTERVAL_MS = 5_000; +const DEFAULT_BACKOFF_FACTOR = 1.5; + /** * Synchronously sleep for the given number of milliseconds. * Uses Atomics.wait to block without pegging the CPU. @@ -21,3 +42,60 @@ export function sleepMs(ms: number): void { export function sleepSeconds(seconds: number): void { sleepMs(seconds * 1000); } + +function positiveFiniteOr(value: number | undefined, fallback: number): number { + return value !== undefined && Number.isFinite(value) && value > 0 ? value : fallback; +} + +function nonNegativeFiniteOr(value: number | undefined, fallback: number): number { + return value !== undefined && Number.isFinite(value) && value >= 0 ? value : fallback; +} + +/** + * Poll a synchronous condition until it succeeds or the absolute deadline passes. + */ +export function waitUntil(condition: () => boolean, options: WaitUntilOptions): boolean { + const deadlineMs = Number(options.deadlineMs); + if (!Number.isFinite(deadlineMs)) { + throw new TypeError("waitUntil requires a finite deadlineMs"); + } + + const now = options.now ?? Date.now; + const sleeper = options.sleep ?? sleepMs; + const maxIntervalMs = nonNegativeFiniteOr(options.maxIntervalMs, DEFAULT_MAX_INTERVAL_MS); + let intervalMs = Math.min( + nonNegativeFiniteOr(options.initialIntervalMs, DEFAULT_INITIAL_INTERVAL_MS), + maxIntervalMs, + ); + const backoffFactor = Math.max( + 1, + positiveFiniteOr(options.backoffFactor, DEFAULT_BACKOFF_FACTOR), + ); + const maxAttempts = + options.maxAttempts !== undefined && Number.isFinite(options.maxAttempts) + ? Math.max(0, Math.floor(options.maxAttempts)) + : Number.POSITIVE_INFINITY; + + let attempts = 0; + for (;;) { + if (attempts >= maxAttempts) { + return false; + } + attempts += 1; + + if (condition()) { + return true; + } + if (attempts >= maxAttempts) { + return false; + } + + const currentMs = now(); + if (!Number.isFinite(currentMs) || currentMs >= deadlineMs) { + return false; + } + + sleeper(Math.min(intervalMs, deadlineMs - currentMs)); + intervalMs = Math.min(maxIntervalMs, intervalMs * backoffFactor); + } +} diff --git a/test/wait.test.ts b/test/wait.test.ts index b6308746821..1fb8d9a153d 100644 --- a/test/wait.test.ts +++ b/test/wait.test.ts @@ -3,7 +3,7 @@ import assert from "node:assert"; import { describe, expect, it } from "vitest"; -import { sleepMs, sleepSeconds } from "../src/lib/wait.js"; +import { sleepMs, sleepSeconds, waitUntil } from "../src/lib/wait.js"; describe("wait utility", () => { it("sleepMs blocks for approximately the requested time", () => { @@ -38,4 +38,136 @@ describe("wait utility", () => { const duration = end - start; assert.ok(duration < 50, `duration ${duration}ms > 50ms`); }); + + it("waitUntil returns immediately when the condition is already true", () => { + const sleeps: number[] = []; + let attempts = 0; + + const result = waitUntil( + () => { + attempts += 1; + return true; + }, + { + deadlineMs: 100, + now: () => 0, + sleep: (ms) => sleeps.push(ms), + }, + ); + + expect(result).toBe(true); + expect(attempts).toBe(1); + expect(sleeps).toEqual([]); + }); + + it("waitUntil retries until the condition succeeds", () => { + const sleeps: number[] = []; + let attempts = 0; + let nowMs = 0; + + const result = waitUntil( + () => { + attempts += 1; + return attempts >= 3; + }, + { + deadlineMs: 100, + initialIntervalMs: 10, + maxIntervalMs: 10, + backoffFactor: 1, + now: () => nowMs, + sleep: (ms) => { + sleeps.push(ms); + nowMs += ms; + }, + }, + ); + + expect(result).toBe(true); + expect(attempts).toBe(3); + expect(sleeps).toEqual([10, 10]); + }); + + it("waitUntil returns false after the deadline passes", () => { + const sleeps: number[] = []; + let attempts = 0; + let nowMs = 0; + + const result = waitUntil( + () => { + attempts += 1; + return false; + }, + { + deadlineMs: 25, + initialIntervalMs: 10, + maxIntervalMs: 10, + backoffFactor: 1, + now: () => nowMs, + sleep: (ms) => { + sleeps.push(ms); + nowMs += ms; + }, + }, + ); + + expect(result).toBe(false); + expect(attempts).toBe(4); + expect(sleeps).toEqual([10, 10, 5]); + }); + + it("waitUntil applies interval backoff up to the configured max interval", () => { + const sleeps: number[] = []; + let attempts = 0; + let nowMs = 0; + + const result = waitUntil( + () => { + attempts += 1; + return attempts >= 5; + }, + { + deadlineMs: 100, + initialIntervalMs: 5, + maxIntervalMs: 20, + backoffFactor: 2, + now: () => nowMs, + sleep: (ms) => { + sleeps.push(ms); + nowMs += ms; + }, + }, + ); + + expect(result).toBe(true); + expect(sleeps).toEqual([5, 10, 20, 20]); + }); + + it("waitUntil can cap attempts while allowing zero-length intervals", () => { + const sleeps: number[] = []; + let attempts = 0; + let nowMs = 0; + + const result = waitUntil( + () => { + attempts += 1; + return false; + }, + { + deadlineMs: 1, + initialIntervalMs: 0, + maxIntervalMs: 0, + maxAttempts: 3, + now: () => nowMs, + sleep: (ms) => { + sleeps.push(ms); + nowMs += ms; + }, + }, + ); + + expect(result).toBe(false); + expect(attempts).toBe(3); + expect(sleeps).toEqual([0, 0]); + }); }); From f2e7b768e2df88a7d2efd42891cf4a84685b0a71 Mon Sep 17 00:00:00 2001 From: Ho Lim <166576253+HOYALIM@users.noreply.github.com> Date: Sun, 26 Apr 2026 17:10:19 -0700 Subject: [PATCH 02/15] Update src/lib/onboard.ts Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/lib/onboard.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index a01de56517e..7c4ea6e43db 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -3511,10 +3511,10 @@ async function startGatewayWithOptions( const healthPollCount = healthWait.count; const healthPollInterval = healthWait.interval; const healthPollIntervalMs = Math.max(0, healthPollInterval * 1000); - const healthDeadlineMs = - Date.now() + - Math.max(0, healthPollCount - 1) * healthPollIntervalMs + - (healthPollIntervalMs === 0 ? 1 : 0); + // Keep the deadline effectively unbounded so slow probe/repair commands do not + // consume the entire time budget before maxAttempts is reached. maxAttempts + // remains the mechanism that enforces the configured poll count. + const healthDeadlineMs = Number.MAX_SAFE_INTEGER; const gatewayBecameHealthy = healthPollCount > 0 && waitUntil( From 4568f14eda3e4add38cbf05cc45e2b6d9bd6a0b8 Mon Sep 17 00:00:00 2001 From: Ho Lim Date: Sun, 26 Apr 2026 17:14:12 -0700 Subject: [PATCH 03/15] fix(wait): address polling review feedback --- src/lib/wait.ts | 34 ++++++++++++++++++++------- test/wait.test.ts | 60 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 8 deletions(-) diff --git a/src/lib/wait.ts b/src/lib/wait.ts index c202eb12663..653a93841c4 100644 --- a/src/lib/wait.ts +++ b/src/lib/wait.ts @@ -7,7 +7,7 @@ export type WaitUntilOptions = { /** Absolute deadline, in milliseconds, using the same clock as `now`. */ - deadlineMs: number; + deadlineMs?: number; /** First delay between failed attempts. */ initialIntervalMs?: number; /** Maximum delay between failed attempts after backoff. */ @@ -25,6 +25,7 @@ export type WaitUntilOptions = { const DEFAULT_INITIAL_INTERVAL_MS = 250; const DEFAULT_MAX_INTERVAL_MS = 5_000; const DEFAULT_BACKOFF_FACTOR = 1.5; +const MIN_UNCAPPED_SLEEP_MS = 1; /** * Synchronously sleep for the given number of milliseconds. @@ -43,23 +44,26 @@ export function sleepSeconds(seconds: number): void { sleepMs(seconds * 1000); } +/** + * Return a positive finite number, or a fallback when the option is absent or invalid. + */ function positiveFiniteOr(value: number | undefined, fallback: number): number { return value !== undefined && Number.isFinite(value) && value > 0 ? value : fallback; } +/** + * Return a non-negative finite number, or a fallback when the option is absent or invalid. + */ function nonNegativeFiniteOr(value: number | undefined, fallback: number): number { return value !== undefined && Number.isFinite(value) && value >= 0 ? value : fallback; } /** - * Poll a synchronous condition until it succeeds or the absolute deadline passes. + * Poll a synchronous condition until it succeeds, the deadline passes, or attempts run out. + * + * Callers must provide either a finite deadline or a finite maxAttempts cap. */ export function waitUntil(condition: () => boolean, options: WaitUntilOptions): boolean { - const deadlineMs = Number(options.deadlineMs); - if (!Number.isFinite(deadlineMs)) { - throw new TypeError("waitUntil requires a finite deadlineMs"); - } - const now = options.now ?? Date.now; const sleeper = options.sleep ?? sleepMs; const maxIntervalMs = nonNegativeFiniteOr(options.maxIntervalMs, DEFAULT_MAX_INTERVAL_MS); @@ -75,6 +79,16 @@ export function waitUntil(condition: () => boolean, options: WaitUntilOptions): options.maxAttempts !== undefined && Number.isFinite(options.maxAttempts) ? Math.max(0, Math.floor(options.maxAttempts)) : Number.POSITIVE_INFINITY; + const hasAttemptCap = Number.isFinite(maxAttempts); + + const deadlineMs = + options.deadlineMs === undefined ? Number.POSITIVE_INFINITY : Number(options.deadlineMs); + if (Number.isNaN(deadlineMs) || deadlineMs === Number.NEGATIVE_INFINITY) { + throw new TypeError("waitUntil requires a valid deadlineMs"); + } + if (deadlineMs === Number.POSITIVE_INFINITY && !hasAttemptCap) { + throw new TypeError("waitUntil requires deadlineMs or maxAttempts"); + } let attempts = 0; for (;;) { @@ -95,7 +109,11 @@ export function waitUntil(condition: () => boolean, options: WaitUntilOptions): return false; } - sleeper(Math.min(intervalMs, deadlineMs - currentMs)); + const remainingMs = deadlineMs - currentMs; + const requestedSleepMs = Math.min(intervalMs, remainingMs); + const sleepDurationMs = + !hasAttemptCap && requestedSleepMs <= 0 ? MIN_UNCAPPED_SLEEP_MS : requestedSleepMs; + sleeper(Math.min(sleepDurationMs, remainingMs)); intervalMs = Math.min(maxIntervalMs, intervalMs * backoffFactor); } } diff --git a/test/wait.test.ts b/test/wait.test.ts index 1fb8d9a153d..e7bd28bf237 100644 --- a/test/wait.test.ts +++ b/test/wait.test.ts @@ -60,6 +60,16 @@ describe("wait utility", () => { expect(sleeps).toEqual([]); }); + it("waitUntil throws when deadlineMs is non-finite and no attempt cap is provided", () => { + expect(() => + waitUntil(() => false, { + deadlineMs: Number.NaN, + now: () => 0, + sleep: () => {}, + }), + ).toThrow(TypeError); + }); + it("waitUntil retries until the condition succeeds", () => { const sleeps: number[] = []; let attempts = 0; @@ -170,4 +180,54 @@ describe("wait utility", () => { expect(attempts).toBe(3); expect(sleeps).toEqual([0, 0]); }); + + it("waitUntil can rely on maxAttempts without a deadline", () => { + const sleeps: number[] = []; + let attempts = 0; + + const result = waitUntil( + () => { + attempts += 1; + return false; + }, + { + initialIntervalMs: 0, + maxIntervalMs: 0, + maxAttempts: 3, + now: () => 0, + sleep: (ms) => sleeps.push(ms), + }, + ); + + expect(result).toBe(false); + expect(attempts).toBe(3); + expect(sleeps).toEqual([0, 0]); + }); + + it("waitUntil yields between unbounded zero-interval attempts", () => { + const sleeps: number[] = []; + let attempts = 0; + let nowMs = 0; + + const result = waitUntil( + () => { + attempts += 1; + return false; + }, + { + deadlineMs: 3, + initialIntervalMs: 0, + maxIntervalMs: 0, + now: () => nowMs, + sleep: (ms) => { + sleeps.push(ms); + nowMs += ms; + }, + }, + ); + + expect(result).toBe(false); + expect(attempts).toBe(4); + expect(sleeps).toEqual([1, 1, 1]); + }); }); From 6d0daabd43578e58647a128359bd2aebdc141cdc Mon Sep 17 00:00:00 2001 From: Ho Lim Date: Sun, 26 Apr 2026 17:22:42 -0700 Subject: [PATCH 04/15] fix(wait): check deadline before retry probe --- src/lib/wait.ts | 11 +++++++---- test/wait.test.ts | 4 ++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/lib/wait.ts b/src/lib/wait.ts index 653a93841c4..73ee662a842 100644 --- a/src/lib/wait.ts +++ b/src/lib/wait.ts @@ -92,6 +92,13 @@ export function waitUntil(condition: () => boolean, options: WaitUntilOptions): let attempts = 0; for (;;) { + if (attempts > 0) { + const currentMs = now(); + if (!Number.isFinite(currentMs) || currentMs >= deadlineMs) { + return false; + } + } + if (attempts >= maxAttempts) { return false; } @@ -105,10 +112,6 @@ export function waitUntil(condition: () => boolean, options: WaitUntilOptions): } const currentMs = now(); - if (!Number.isFinite(currentMs) || currentMs >= deadlineMs) { - return false; - } - const remainingMs = deadlineMs - currentMs; const requestedSleepMs = Math.min(intervalMs, remainingMs); const sleepDurationMs = diff --git a/test/wait.test.ts b/test/wait.test.ts index e7bd28bf237..7170cc43fb9 100644 --- a/test/wait.test.ts +++ b/test/wait.test.ts @@ -122,7 +122,7 @@ describe("wait utility", () => { ); expect(result).toBe(false); - expect(attempts).toBe(4); + expect(attempts).toBe(3); expect(sleeps).toEqual([10, 10, 5]); }); @@ -227,7 +227,7 @@ describe("wait utility", () => { ); expect(result).toBe(false); - expect(attempts).toBe(4); + expect(attempts).toBe(3); expect(sleeps).toEqual([1, 1, 1]); }); }); From 8cee17dd5ce3afd818781b5588668a0dcdc8f8c2 Mon Sep 17 00:00:00 2001 From: Ho Lim Date: Sun, 26 Apr 2026 17:28:00 -0700 Subject: [PATCH 05/15] fix(wait): honor expired deadline before probing --- src/lib/wait.ts | 9 +++------ test/wait.test.ts | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/lib/wait.ts b/src/lib/wait.ts index 73ee662a842..2f2e45bc871 100644 --- a/src/lib/wait.ts +++ b/src/lib/wait.ts @@ -92,11 +92,9 @@ export function waitUntil(condition: () => boolean, options: WaitUntilOptions): let attempts = 0; for (;;) { - if (attempts > 0) { - const currentMs = now(); - if (!Number.isFinite(currentMs) || currentMs >= deadlineMs) { - return false; - } + const currentMs = now(); + if (!Number.isFinite(currentMs) || currentMs >= deadlineMs) { + return false; } if (attempts >= maxAttempts) { @@ -111,7 +109,6 @@ export function waitUntil(condition: () => boolean, options: WaitUntilOptions): return false; } - const currentMs = now(); const remainingMs = deadlineMs - currentMs; const requestedSleepMs = Math.min(intervalMs, remainingMs); const sleepDurationMs = diff --git a/test/wait.test.ts b/test/wait.test.ts index 7170cc43fb9..886d3f50b5c 100644 --- a/test/wait.test.ts +++ b/test/wait.test.ts @@ -60,6 +60,27 @@ describe("wait utility", () => { expect(sleeps).toEqual([]); }); + it("waitUntil does not probe when the deadline is already expired", () => { + const sleeps: number[] = []; + let attempts = 0; + + const result = waitUntil( + () => { + attempts += 1; + return true; + }, + { + deadlineMs: 10, + now: () => 10, + sleep: (ms) => sleeps.push(ms), + }, + ); + + expect(result).toBe(false); + expect(attempts).toBe(0); + expect(sleeps).toEqual([]); + }); + it("waitUntil throws when deadlineMs is non-finite and no attempt cap is provided", () => { expect(() => waitUntil(() => false, { From 5a709c414b721a0c0c95d75937c7b1acc28c419e Mon Sep 17 00:00:00 2001 From: Ho Lim <166576253+HOYALIM@users.noreply.github.com> Date: Sun, 26 Apr 2026 17:32:39 -0700 Subject: [PATCH 06/15] Update src/lib/wait.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --- src/lib/wait.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/lib/wait.ts b/src/lib/wait.ts index 2f2e45bc871..b65118b994f 100644 --- a/src/lib/wait.ts +++ b/src/lib/wait.ts @@ -109,7 +109,11 @@ export function waitUntil(condition: () => boolean, options: WaitUntilOptions): return false; } - const remainingMs = deadlineMs - currentMs; + const postConditionMs = now(); + if (!Number.isFinite(postConditionMs) || postConditionMs >= deadlineMs) { + return false; + } + const remainingMs = deadlineMs - postConditionMs; const requestedSleepMs = Math.min(intervalMs, remainingMs); const sleepDurationMs = !hasAttemptCap && requestedSleepMs <= 0 ? MIN_UNCAPPED_SLEEP_MS : requestedSleepMs; From 4beebb41f82372f5195d3ff09e525f483158b97f Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Fri, 12 Jun 2026 00:52:46 -0700 Subject: [PATCH 07/15] refactor(onboard): extract gateway health wait --- src/lib/onboard.ts | 53 ++++++++-------------- src/lib/onboard/gateway-health-wait.ts | 61 ++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 35 deletions(-) create mode 100644 src/lib/onboard/gateway-health-wait.ts diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 6c7f289b401..4b82dfb7d63 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -299,7 +299,7 @@ const { inferenceCompat: LooseObject | null; }; }; -const { sleepSeconds, waitUntil, waitUntilAsync } = require("./core/wait"); +const { sleepSeconds, waitUntil } = require("./core/wait"); const platformUtils: typeof import("./platform") = require("./platform"); const { isWsl, shouldPatchCoredns } = platformUtils; const { @@ -308,6 +308,9 @@ const { rejectUnsupportedWindowsHostOllama, shouldFrontOllamaWithProxy, }: typeof import("./onboard/local-inference-topology") = require("./onboard/local-inference-topology"); +const { + waitForGatewayHealth, +}: typeof import("./onboard/gateway-health-wait") = require("./onboard/gateway-health-wait"); const { resolveOpenshell } = require("./adapters/openshell/resolve"); const credentials: typeof import("./credentials/store") = require("./credentials/store"); const { @@ -2037,40 +2040,20 @@ async function startGatewayWithOptions( ); } - const healthPollCount = healthWait.count; - const healthPollInterval = healthWait.interval; - const healthPollIntervalMs = Math.max(0, healthPollInterval * 1000); - const gatewayBecameHealthy = - healthPollCount > 0 && - (await waitUntilAsync( - async () => { - const repairResult = repairGatewayBootstrapSecrets(); - if (repairResult.repaired) { - attachGatewayMetadataIfNeeded({ forceRefresh: true }); - } else if (gatewayClusterHealthcheckPassed()) { - attachGatewayMetadataIfNeeded(); - } - // Ensure the gateway remains selected before each probe. - runCaptureOpenshell(["gateway", "select", GATEWAY_NAME], { ignoreError: true }); - const status = runCaptureOpenshell(["status"], { ignoreError: true }); - const namedInfo = runCaptureOpenshell(["gateway", "info", "-g", GATEWAY_NAME], { - ignoreError: true, - }); - const currentInfo = runCaptureOpenshell(["gateway", "info"], { ignoreError: true }); - if (!isGatewayHealthy(status, namedInfo, currentInfo)) { - return false; - } - return await isGatewayHttpReady(); - }, - { - initialIntervalMs: healthPollIntervalMs, - maxIntervalMs: healthPollIntervalMs, - backoffFactor: 1, - maxAttempts: healthPollCount, - sleep: (ms: number) => sleepSeconds(ms / 1000), - }, - )); - if (gatewayBecameHealthy) { + if ( + await waitForGatewayHealth({ + attachGatewayMetadataIfNeeded, + gatewayClusterHealthcheckPassed, + gatewayName: GATEWAY_NAME, + healthPollCount: healthWait.count, + healthPollIntervalSeconds: healthWait.interval, + isGatewayHealthy, + isGatewayHttpReady, + repairGatewayBootstrapSecrets, + runCaptureOpenshell, + sleepSeconds, + }) + ) { return; } diff --git a/src/lib/onboard/gateway-health-wait.ts b/src/lib/onboard/gateway-health-wait.ts new file mode 100644 index 00000000000..bd019cc43f8 --- /dev/null +++ b/src/lib/onboard/gateway-health-wait.ts @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { waitUntilAsync } from "../core/wait"; + +type RunCaptureOpenshell = (args: string[], opts?: { ignoreError?: boolean }) => string; + +export interface GatewayHealthWaitOptions { + attachGatewayMetadataIfNeeded: (options?: { forceRefresh?: boolean }) => void; + gatewayClusterHealthcheckPassed: () => boolean; + gatewayName: string; + healthPollCount: number; + healthPollIntervalSeconds: number; + isGatewayHealthy: (status: string, namedInfo: string, currentInfo: string) => boolean; + isGatewayHttpReady: () => Promise; + repairGatewayBootstrapSecrets: () => { repaired: boolean }; + runCaptureOpenshell: RunCaptureOpenshell; + sleepSeconds: (seconds: number) => void; +} + +export async function waitForGatewayHealth({ + attachGatewayMetadataIfNeeded, + gatewayClusterHealthcheckPassed, + gatewayName, + healthPollCount, + healthPollIntervalSeconds, + isGatewayHealthy, + isGatewayHttpReady, + repairGatewayBootstrapSecrets, + runCaptureOpenshell, + sleepSeconds, +}: GatewayHealthWaitOptions): Promise { + const healthPollIntervalMs = Math.max(0, healthPollIntervalSeconds * 1000); + return ( + healthPollCount > 0 && + (await waitUntilAsync( + async () => { + const repairResult = repairGatewayBootstrapSecrets(); + if (repairResult.repaired) { + attachGatewayMetadataIfNeeded({ forceRefresh: true }); + } else if (gatewayClusterHealthcheckPassed()) { + attachGatewayMetadataIfNeeded(); + } + runCaptureOpenshell(["gateway", "select", gatewayName], { ignoreError: true }); + const status = runCaptureOpenshell(["status"], { ignoreError: true }); + const namedInfo = runCaptureOpenshell(["gateway", "info", "-g", gatewayName], { + ignoreError: true, + }); + const currentInfo = runCaptureOpenshell(["gateway", "info"], { ignoreError: true }); + return isGatewayHealthy(status, namedInfo, currentInfo) && (await isGatewayHttpReady()); + }, + { + initialIntervalMs: healthPollIntervalMs, + maxIntervalMs: healthPollIntervalMs, + backoffFactor: 1, + maxAttempts: healthPollCount, + sleep: (ms) => sleepSeconds(ms / 1000), + }, + )) + ); +} From 2dc26d14aa918296aa84de3fde9fa46600229319 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Fri, 12 Jun 2026 01:08:09 -0700 Subject: [PATCH 08/15] test(onboard): cover gateway health wait helper --- src/lib/onboard/gateway-health-wait.test.ts | 140 ++++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 src/lib/onboard/gateway-health-wait.test.ts diff --git a/src/lib/onboard/gateway-health-wait.test.ts b/src/lib/onboard/gateway-health-wait.test.ts new file mode 100644 index 00000000000..96b5f37b1c4 --- /dev/null +++ b/src/lib/onboard/gateway-health-wait.test.ts @@ -0,0 +1,140 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { type GatewayHealthWaitOptions, waitForGatewayHealth } from "./gateway-health-wait"; + +function buildOptions(overrides: Partial = {}): GatewayHealthWaitOptions { + return { + attachGatewayMetadataIfNeeded: vi.fn(), + gatewayClusterHealthcheckPassed: vi.fn(() => false), + gatewayName: "nemoclaw", + healthPollCount: 1, + healthPollIntervalSeconds: 2, + isGatewayHealthy: vi.fn(() => true), + isGatewayHttpReady: vi.fn(async () => true), + repairGatewayBootstrapSecrets: vi.fn(() => ({ repaired: false })), + runCaptureOpenshell: vi.fn((args: string[]) => { + if (args[0] === "status") return "status"; + if (args[0] === "gateway" && args[1] === "info" && args[2] === "-g") return "named"; + if (args[0] === "gateway" && args[1] === "info") return "current"; + return ""; + }), + sleepSeconds: vi.fn(), + ...overrides, + }; +} + +describe("waitForGatewayHealth", () => { + beforeEach(() => { + vi.restoreAllMocks(); + }); + + it("returns true only after OpenShell metadata and HTTP readiness are healthy", async () => { + const isGatewayHealthy = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true); + const isGatewayHttpReady = vi.fn(async () => true); + const options = buildOptions({ + healthPollCount: 2, + isGatewayHealthy, + isGatewayHttpReady, + }); + + await expect(waitForGatewayHealth(options)).resolves.toBe(true); + + expect(isGatewayHealthy).toHaveBeenCalledTimes(2); + expect(isGatewayHttpReady).toHaveBeenCalledTimes(1); + expect(options.sleepSeconds).toHaveBeenCalledTimes(1); + expect(options.sleepSeconds).toHaveBeenCalledWith(2); + }); + + it("returns false when HTTP readiness never follows healthy metadata", async () => { + const options = buildOptions({ + healthPollCount: 2, + isGatewayHttpReady: vi.fn(async () => false), + }); + + await expect(waitForGatewayHealth(options)).resolves.toBe(false); + + expect(options.isGatewayHealthy).toHaveBeenCalledTimes(2); + expect(options.isGatewayHttpReady).toHaveBeenCalledTimes(2); + expect(options.sleepSeconds).toHaveBeenCalledTimes(1); + }); + + it("force-refreshes metadata after bootstrap secret repair", async () => { + const options = buildOptions({ + gatewayClusterHealthcheckPassed: vi.fn(() => true), + repairGatewayBootstrapSecrets: vi.fn(() => ({ repaired: true })), + }); + + await expect(waitForGatewayHealth(options)).resolves.toBe(true); + + expect(options.attachGatewayMetadataIfNeeded).toHaveBeenCalledOnce(); + expect(options.attachGatewayMetadataIfNeeded).toHaveBeenCalledWith({ forceRefresh: true }); + expect(options.gatewayClusterHealthcheckPassed).not.toHaveBeenCalled(); + }); + + it("attaches metadata without force when cluster healthcheck passes without repair", async () => { + const options = buildOptions({ + gatewayClusterHealthcheckPassed: vi.fn(() => true), + }); + + await expect(waitForGatewayHealth(options)).resolves.toBe(true); + + expect(options.attachGatewayMetadataIfNeeded).toHaveBeenCalledOnce(); + expect(options.attachGatewayMetadataIfNeeded).toHaveBeenCalledWith(); + }); + + it("stops after healthPollCount attempts without sleeping after the final failed probe", async () => { + const options = buildOptions({ + healthPollCount: 3, + isGatewayHealthy: vi.fn(() => false), + }); + + await expect(waitForGatewayHealth(options)).resolves.toBe(false); + + expect(options.isGatewayHealthy).toHaveBeenCalledTimes(3); + expect(options.isGatewayHttpReady).not.toHaveBeenCalled(); + expect(options.sleepSeconds).toHaveBeenCalledTimes(2); + expect(options.sleepSeconds).toHaveBeenNthCalledWith(1, 2); + expect(options.sleepSeconds).toHaveBeenNthCalledWith(2, 2); + }); + + it("returns false without probing when healthPollCount is zero", async () => { + const options = buildOptions({ healthPollCount: 0 }); + + await expect(waitForGatewayHealth(options)).resolves.toBe(false); + + expect(options.repairGatewayBootstrapSecrets).not.toHaveBeenCalled(); + expect(options.attachGatewayMetadataIfNeeded).not.toHaveBeenCalled(); + expect(options.runCaptureOpenshell).not.toHaveBeenCalled(); + expect(options.isGatewayHealthy).not.toHaveBeenCalled(); + expect(options.isGatewayHttpReady).not.toHaveBeenCalled(); + expect(options.sleepSeconds).not.toHaveBeenCalled(); + }); + + it("reselects the gateway and probes status, named info, and active info in order", async () => { + const runCaptureOpenshell = vi.fn((args: string[]) => { + if (args[0] === "status") return "status"; + if (args[0] === "gateway" && args[1] === "info" && args[2] === "-g") return "named"; + if (args[0] === "gateway" && args[1] === "info") return "current"; + return ""; + }); + const isGatewayHealthy = vi.fn(() => true); + const options = buildOptions({ isGatewayHealthy, runCaptureOpenshell }); + + await expect(waitForGatewayHealth(options)).resolves.toBe(true); + + expect(runCaptureOpenshell).toHaveBeenNthCalledWith(1, ["gateway", "select", "nemoclaw"], { + ignoreError: true, + }); + expect(runCaptureOpenshell).toHaveBeenNthCalledWith(2, ["status"], { ignoreError: true }); + expect(runCaptureOpenshell).toHaveBeenNthCalledWith(3, ["gateway", "info", "-g", "nemoclaw"], { + ignoreError: true, + }); + expect(runCaptureOpenshell).toHaveBeenNthCalledWith(4, ["gateway", "info"], { + ignoreError: true, + }); + expect(isGatewayHealthy).toHaveBeenCalledWith("status", "named", "current"); + }); +}); From fc479f676ea7be88718922459cd7f2ad1cb2102a Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Fri, 12 Jun 2026 01:28:03 -0700 Subject: [PATCH 09/15] fix(wait): avoid blocking async default sleep --- src/lib/core/wait.ts | 19 ++++++++++++++----- test/wait.test.ts | 33 ++++++++++++++++++++++++++++++++- 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/src/lib/core/wait.ts b/src/lib/core/wait.ts index 9c44bcfd585..bc78a902867 100644 --- a/src/lib/core/wait.ts +++ b/src/lib/core/wait.ts @@ -21,7 +21,7 @@ export type WaitUntilOptions = { maxAttempts?: number; /** Clock used for deadline comparisons. Defaults to Date.now. */ now?: () => number; - /** Blocking sleep function. Defaults to sleepMs. */ + /** Sleep function. Defaults to sleepMs for waitUntil and sleepMsAsync for waitUntilAsync. */ sleep?: (ms: number) => void; }; @@ -33,7 +33,7 @@ type NormalizedWaitUntilOptions = { maxAttempts: number; hasAttemptCap: boolean; now: () => number; - sleep: (ms: number) => void; + sleep: (ms: number) => void | Promise; }; const DEFAULT_TIMEOUT_SECONDS = 10; @@ -66,6 +66,14 @@ export function sleepMs(ms: number): void { Atomics.wait(buffer, 0, 0, ms); } +/** + * Asynchronously sleep for the given number of milliseconds. + */ +export function sleepMsAsync(ms: number): Promise { + if (ms <= 0 || !Number.isFinite(ms)) return Promise.resolve(); + return new Promise((resolve) => setTimeout(resolve, ms)); +} + /** * Synchronously sleep for the given number of seconds. */ @@ -84,6 +92,7 @@ function nonNegativeFiniteOr(value: number | undefined, fallback: number): numbe function normalizeWaitUntilOptions( optionsOrTimeout?: WaitUntilOptions | number, pollIntervalMs = DEFAULT_INITIAL_INTERVAL_MS, + defaultSleep: (ms: number) => void | Promise = sleepMs, ): NormalizedWaitUntilOptions { if (typeof optionsOrTimeout === "number" || optionsOrTimeout === undefined) { const now = Date.now; @@ -103,7 +112,7 @@ function normalizeWaitUntilOptions( maxAttempts: Number.POSITIVE_INFINITY, hasAttemptCap: false, now, - sleep: sleepMs, + sleep: defaultSleep, }; } @@ -143,7 +152,7 @@ function normalizeWaitUntilOptions( maxAttempts, hasAttemptCap, now, - sleep: optionsOrTimeout.sleep ?? sleepMs, + sleep: optionsOrTimeout.sleep ?? defaultSleep, }; } @@ -225,7 +234,7 @@ export async function waitUntilAsync( optionsOrTimeout?: WaitUntilOptions | number, pollIntervalMs?: number, ): Promise { - const options = normalizeWaitUntilOptions(optionsOrTimeout, pollIntervalMs); + const options = normalizeWaitUntilOptions(optionsOrTimeout, pollIntervalMs, sleepMsAsync); let attempts = 0; let intervalMs = options.intervalMs; diff --git a/test/wait.test.ts b/test/wait.test.ts index 546ac2c3599..c382dc4034d 100644 --- a/test/wait.test.ts +++ b/test/wait.test.ts @@ -3,7 +3,7 @@ import assert from "node:assert"; import { createServer, type AddressInfo } from "node:net"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { buildLoopbackProbeEnv, sleepMs, @@ -286,6 +286,37 @@ describe("wait utility", () => { expect(attempts).toBe(3); expect(sleeps).toEqual([5, 5]); }); + + it("waitUntilAsync uses a nonblocking default sleeper", async () => { + vi.useFakeTimers(); + try { + let attempts = 0; + + const resultPromise = waitUntilAsync( + () => { + attempts += 1; + return attempts >= 2; + }, + { + initialIntervalMs: 10, + maxIntervalMs: 10, + maxAttempts: 2, + }, + ); + + await Promise.resolve(); + expect(attempts).toBe(1); + + await vi.advanceTimersByTimeAsync(9); + expect(attempts).toBe(1); + + await vi.advanceTimersByTimeAsync(1); + await expect(resultPromise).resolves.toBe(true); + expect(attempts).toBe(2); + } finally { + vi.useRealTimers(); + } + }); }); describe("buildLoopbackProbeEnv (#4181)", () => { From 4d96f941785342a571e4647b3f4b23673936d605 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Fri, 12 Jun 2026 08:37:01 -0700 Subject: [PATCH 10/15] refactor(wait): migrate local adapter health wait --- .../inference/local-adapter-lifecycle.test.ts | 35 +++++++++++++++++++ src/lib/inference/local-adapter-lifecycle.ts | 13 ++++--- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/src/lib/inference/local-adapter-lifecycle.test.ts b/src/lib/inference/local-adapter-lifecycle.test.ts index d3206ca0a5f..2803bcec934 100644 --- a/src/lib/inference/local-adapter-lifecycle.test.ts +++ b/src/lib/inference/local-adapter-lifecycle.test.ts @@ -18,6 +18,7 @@ import { probeLocalAdapterHealth, readLocalAdapterJsonFile, readLocalAdapterTextFile, + waitForLocalAdapterHealth, writeLocalAdapterJsonFile, writeLocalAdapterSecretFile, } from "../../../dist/lib/inference/local-adapter-lifecycle"; @@ -151,3 +152,37 @@ describe("ensureLocalAdapterStateDir", () => { expect(stat.mode & 0o777).toBe(0o700); }); }); + +describe("waitForLocalAdapterHealth", () => { + it("retries async health probes until the adapter responds", async () => { + let calls = 0; + + await expect( + waitForLocalAdapterHealth( + async () => { + calls += 1; + return calls >= 3; + }, + { attempts: 5, intervalMs: 1 }, + ), + ).resolves.toBe(true); + + expect(calls).toBe(3); + }); + + it("returns false after the configured attempt budget is exhausted", async () => { + let calls = 0; + + await expect( + waitForLocalAdapterHealth( + async () => { + calls += 1; + return false; + }, + { attempts: 2, intervalMs: 1 }, + ), + ).resolves.toBe(false); + + expect(calls).toBe(2); + }); +}); diff --git a/src/lib/inference/local-adapter-lifecycle.ts b/src/lib/inference/local-adapter-lifecycle.ts index 05cb6a10725..5c028dc1d0d 100644 --- a/src/lib/inference/local-adapter-lifecycle.ts +++ b/src/lib/inference/local-adapter-lifecycle.ts @@ -8,6 +8,8 @@ import http from "node:http"; import os from "node:os"; import path from "node:path"; +import { waitUntilAsync } from "../core/wait"; + export type JsonObject = Record; export type RunCaptureFn = ( @@ -195,9 +197,10 @@ export async function waitForLocalAdapterHealth( ): Promise { const attempts = options.attempts || 20; const intervalMs = options.intervalMs || 100; - for (let attempt = 0; attempt < attempts; attempt++) { - if (await probe()) return true; - await new Promise((resolve) => setTimeout(resolve, intervalMs)); - } - return false; + return waitUntilAsync(probe, { + initialIntervalMs: intervalMs, + maxIntervalMs: intervalMs, + backoffFactor: 1, + maxAttempts: attempts, + }); } From 713a9e44c69af70656b4069a7e78ae8fe0b59180 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Fri, 12 Jun 2026 08:38:47 -0700 Subject: [PATCH 11/15] refactor(wait): migrate gateway http readiness wait --- src/lib/onboard/gateway-http-readiness.ts | 28 +++++++++++++++-------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/lib/onboard/gateway-http-readiness.ts b/src/lib/onboard/gateway-http-readiness.ts index b48b7882896..3f936fbbd43 100644 --- a/src/lib/onboard/gateway-http-readiness.ts +++ b/src/lib/onboard/gateway-http-readiness.ts @@ -15,7 +15,7 @@ import http2 from "node:http2"; import { getGatewayHttpEndpoint } from "../core/gateway-address"; import { GATEWAY_PORT } from "../core/ports"; -import { sleepSeconds } from "../core/wait"; +import { sleepSeconds, waitUntilAsync } from "../core/wait"; import { addTraceEvent, withTraceSpan } from "../trace"; import { envInt } from "./env"; @@ -252,16 +252,24 @@ export async function waitForGatewayHttpReady( } }; - if (await safeProbe()) { - addTraceEvent("ready", { attempt: 1 }); - return true; - } - for (let attempt = 1; attempt < maxAttempts; attempt++) { - sleeper(intervalSeconds); - if (await safeProbe()) { - addTraceEvent("ready", { attempt: attempt + 1 }); + let attempt = 0; + const ready = await waitUntilAsync( + async () => { + attempt += 1; + if (!(await safeProbe())) return false; + addTraceEvent("ready", { attempt }); return true; - } + }, + { + initialIntervalMs: intervalSeconds * 1000, + maxIntervalMs: intervalSeconds * 1000, + backoffFactor: 1, + maxAttempts, + sleep: (ms) => sleeper(ms / 1000), + }, + ); + if (ready) { + return true; } addTraceEvent("not_ready", { attempts: maxAttempts }); return false; From 6e8096f3f61831a94367498676b2b3dca3bbb295 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Fri, 12 Jun 2026 08:41:59 -0700 Subject: [PATCH 12/15] refactor(wait): migrate docker driver gateway service wait --- .../onboard/docker-driver-gateway-service.ts | 49 ++++++++++++------- 1 file changed, 30 insertions(+), 19 deletions(-) diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index b7fb92dfdf0..75e5ed20ee1 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -5,7 +5,7 @@ import { spawnSync, type SpawnSyncOptions } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; -import { sleepSeconds } from "../core/wait"; +import { sleepSeconds, waitUntilAsync } from "../core/wait"; import { isGatewayHealthy } from "../state/gateway"; import { envInt } from "./env"; import { isDockerDriverGatewayHttpReady } from "./gateway-http-readiness"; @@ -323,25 +323,36 @@ export async function startPackageManagedDockerDriverGateway({ const pollCount = healthPollCount ?? envInt("NEMOCLAW_HEALTH_POLL_COUNT", 30); const pollInterval = healthPollInterval ?? envInt("NEMOCLAW_HEALTH_POLL_INTERVAL", 2); - for (let i = 0; i < pollCount; i += 1) { - if (!registerDockerDriverGatewayEndpoint()) { - if (i < pollCount - 1) sleepSecondsImpl(pollInterval); - continue; - } - const status = runCaptureOpenshell(["status"], { ignoreError: true }); - const namedInfo = runCaptureOpenshell(["gateway", "info", "-g", gatewayName], { - ignoreError: true, + const pollIntervalMs = Math.max(0, pollInterval * 1000); + const healthy = + pollCount > 0 && + (await waitUntilAsync( + async () => { + if (!registerDockerDriverGatewayEndpoint()) return false; + const status = runCaptureOpenshell(["status"], { ignoreError: true }); + const namedInfo = runCaptureOpenshell(["gateway", "info", "-g", gatewayName], { + ignoreError: true, + }); + const currentInfo = runCaptureOpenshell(["gateway", "info"], { ignoreError: true }); + return ( + isGatewayHealthy(status, namedInfo, currentInfo) && (await isDockerDriverGatewayReady()) + ); + }, + { + initialIntervalMs: pollIntervalMs, + maxIntervalMs: pollIntervalMs, + backoffFactor: 1, + maxAttempts: pollCount, + sleep: (ms) => sleepSecondsImpl(ms / 1000), + }, + )); + if (healthy) { + clearDockerDriverGatewayRuntimeFiles(); + await verifySandboxBridgeGatewayReachableOrExit(exitOnFailure, { + skip: skipSandboxBridgeReachability, }); - const currentInfo = runCaptureOpenshell(["gateway", "info"], { ignoreError: true }); - if (isGatewayHealthy(status, namedInfo, currentInfo) && (await isDockerDriverGatewayReady())) { - clearDockerDriverGatewayRuntimeFiles(); - await verifySandboxBridgeGatewayReachableOrExit(exitOnFailure, { - skip: skipSandboxBridgeReachability, - }); - console.log(" ✓ OpenShell gateway user service is healthy"); - return true; - } - if (i < pollCount - 1) sleepSecondsImpl(pollInterval); + console.log(" ✓ OpenShell gateway user service is healthy"); + return true; } const message = "OpenShell gateway user service started but did not become healthy."; From ff5807db208f171525d4ee4c14c8f80dcf983223 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Fri, 12 Jun 2026 08:45:41 -0700 Subject: [PATCH 13/15] refactor(wait): migrate sandbox recovery gateway wait --- src/lib/actions/sandbox/process-recovery.ts | 18 +++--- test/process-recovery.test.ts | 67 +++++++++++++++++++++ 2 files changed, 75 insertions(+), 10 deletions(-) diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index 441a083369b..5cae60baafd 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -17,7 +17,7 @@ import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; import * as agentRuntime from "../../agent/runtime"; import { G, R } from "../../cli/terminal-style"; import { DASHBOARD_PORT } from "../../core/ports"; -import { sleepSeconds } from "../../core/wait"; +import { sleepSeconds, waitUntil } from "../../core/wait"; import { ROOT, shellQuote } from "../../runner"; import * as registry from "../../state/registry"; import { parseForwardList } from "../../state/sandbox-session"; @@ -321,15 +321,13 @@ function waitForRecoveredSandboxGateway(sandboxName: string): boolean { ? Math.max(1, Math.floor(timeoutSeconds / intervalSeconds) + 1) : Math.max(1, Math.floor(timeoutSeconds) + 1); - for (let attempt = 0; attempt < attempts; attempt += 1) { - if (isSandboxGatewayRunning(sandboxName) === true) { - return true; - } - if (attempt < attempts - 1) { - sleepSeconds(intervalSeconds); - } - } - return false; + return waitUntil(() => isSandboxGatewayRunning(sandboxName) === true, { + initialIntervalMs: intervalSeconds * 1000, + maxIntervalMs: intervalSeconds * 1000, + backoffFactor: 1, + maxAttempts: attempts, + sleep: (ms) => sleepSeconds(ms / 1000), + }); } /** diff --git a/test/process-recovery.test.ts b/test/process-recovery.test.ts index f2b81e10d8a..971c1c24299 100644 --- a/test/process-recovery.test.ts +++ b/test/process-recovery.test.ts @@ -230,4 +230,71 @@ beta 127.0.0.1 18789 12345 running`; ), ).toBe(false); }); + + it("waits for a recovered sandbox gateway before declaring recovery", () => { + const openshellRuntime = requireDist("../dist/lib/adapters/openshell/runtime.js"); + const agentRuntime = requireDist("../dist/lib/agent/runtime.js"); + const registry = requireDist("../dist/lib/state/registry.js"); + const childProcess = requireDist("node:child_process"); + const runningForward = `SANDBOX BIND PORT PID STATUS +beta 127.0.0.1 18789 12345 running`; + const previousWaitSeconds = process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS; + const previousPollInterval = process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS; + let healthProbeCalls = 0; + + process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = "2"; + process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "0"; + + try { + vi.spyOn(childProcess, "spawnSync").mockImplementation( + (_command: unknown, rawArgs: unknown) => { + const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; + const shellCommand = String(args.at(-1) ?? ""); + if (shellCommand.includes("HTTP_CODE=$(curl")) { + healthProbeCalls += 1; + const status = healthProbeCalls >= 3 ? "RUNNING" : "STOPPED"; + return { + status: 0, + stdout: `__NEMOCLAW_SANDBOX_EXEC_STARTED__\n${status}\n`, + stderr: "", + } as never; + } + return { + status: 0, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nGATEWAY_PID=123\n", + stderr: "", + } as never; + }, + ); + vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue(null); + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "beta", + agent: "openclaw", + dashboardPort: 18789, + }); + vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ + status: 0, + output: runningForward, + }); + + expect( + withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("beta", { quiet: true })), + ).toEqual({ + checked: true, + wasRunning: false, + recovered: true, + forwardRecovered: true, + }); + expect(healthProbeCalls).toBe(3); + } finally { + if (previousWaitSeconds === undefined) + delete process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS; + else process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = previousWaitSeconds; + if (previousPollInterval === undefined) { + delete process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS; + } else { + process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = previousPollInterval; + } + } + }); }); From 5c9d128a122ce8f32cb2192923198207c7a4cabb Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Fri, 12 Jun 2026 08:47:23 -0700 Subject: [PATCH 14/15] refactor(wait): migrate host gateway exit wait --- src/lib/onboard/host-gateway-process.test.ts | 36 ++++++++++++++++++++ src/lib/onboard/host-gateway-process.ts | 15 ++++---- 2 files changed, 45 insertions(+), 6 deletions(-) diff --git a/src/lib/onboard/host-gateway-process.test.ts b/src/lib/onboard/host-gateway-process.test.ts index e031d8bc71c..b77892c4f30 100644 --- a/src/lib/onboard/host-gateway-process.test.ts +++ b/src/lib/onboard/host-gateway-process.test.ts @@ -87,6 +87,42 @@ describe("stopHostGatewayProcesses", () => { expect(log).toHaveBeenCalledWith("Stopped host openshell-gateway process 9999887"); }); + it("polls for host gateway exit before escalating to SIGKILL", () => { + const pid = 9999333; + const signals: Array = []; + let pidChecks = 0; + const responses = new Map RunResult)>([ + ["pgrep -f ^(/[^ ]*/)?openshell-gateway( |$)", ok(`${pid}\n`)], + [`ps -p ${pid} -o user=`, ok("tester\n")], + [`ps -p ${pid} -o args=`, ok("/home/test/.local/bin/openshell-gateway --port 8080\n")], + [ + `ps -p ${pid} -o pid=`, + () => { + pidChecks += 1; + return pidChecks >= 3 ? notFound() : ok(`${pid}\n`); + }, + ], + ]); + const { run } = makeRun(responses); + const kill = vi.fn((_pid, signal) => { + signals.push(signal); + return true; + }); + + const result = stopHostGatewayProcesses( + { run, kill, env: { USER: "tester" }, commandExists: () => true, log: vi.fn() }, + { + pollIntervalMs: 0, + stateDir: fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-host-gateway-")), + termWaitMs: 20, + }, + ); + + expect(result.stopped).toEqual([pid]); + expect(signals).toEqual(["SIGTERM"]); + expect(pidChecks).toBe(3); + }); + it("accepts the docker-compat parent PID whose argv0 is docker", () => { const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-host-gateway-")); const pidFile = path.join(stateDir, "openshell-gateway.pid"); diff --git a/src/lib/onboard/host-gateway-process.ts b/src/lib/onboard/host-gateway-process.ts index 8f74d6c74ce..2fcd6589697 100644 --- a/src/lib/onboard/host-gateway-process.ts +++ b/src/lib/onboard/host-gateway-process.ts @@ -6,7 +6,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { sleepMs } from "../core/wait"; +import { waitUntil } from "../core/wait"; import { clearDockerDriverGatewayRuntimeMarker } from "./docker-driver-gateway-runtime-marker"; import { hostGatewayCmdlineMatches as sharedHostGatewayCmdlineMatches } from "./gateway-process-identity"; @@ -163,11 +163,14 @@ function waitForExit( pollIntervalMs: number, ): boolean { const deadline = Date.now() + timeoutMs; - while (Date.now() < deadline) { - if (!pidExists(pid, deps)) return true; - sleepMs(pollIntervalMs); - } - return !pidExists(pid, deps); + return ( + waitUntil(() => !pidExists(pid, deps), { + deadlineMs: deadline, + initialIntervalMs: pollIntervalMs, + maxIntervalMs: pollIntervalMs, + backoffFactor: 1, + }) || !pidExists(pid, deps) + ); } function clearRuntimeFiles(pidFile: string, stateDir: string): void { From ff86b84871617e01eef01522fca38dfa00f3200b Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Fri, 12 Jun 2026 08:49:02 -0700 Subject: [PATCH 15/15] refactor(wait): migrate stale gateway exit wait --- src/lib/onboard/stale-gateway-cleanup.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/lib/onboard/stale-gateway-cleanup.ts b/src/lib/onboard/stale-gateway-cleanup.ts index 233b72f18fa..741fc3104a2 100644 --- a/src/lib/onboard/stale-gateway-cleanup.ts +++ b/src/lib/onboard/stale-gateway-cleanup.ts @@ -23,7 +23,7 @@ import { spawnSync, type SpawnSyncOptions } from "node:child_process"; import os from "node:os"; import { DASHBOARD_PORT_RANGE_END, DASHBOARD_PORT_RANGE_START } from "../core/ports"; -import { sleepMs } from "../core/wait"; +import { waitUntil } from "../core/wait"; export interface RunResult { status: number | null; @@ -138,11 +138,14 @@ function pidExists(pid: number, deps: StaleGatewayDeps): boolean { function waitForExit(pid: number, deps: StaleGatewayDeps, timeoutMs: number): boolean { const deadline = Date.now() + timeoutMs; - while (Date.now() < deadline) { - if (!pidExists(pid, deps)) return true; - sleepMs(50); - } - return !pidExists(pid, deps); + return ( + waitUntil(() => !pidExists(pid, deps), { + deadlineMs: deadline, + initialIntervalMs: 50, + maxIntervalMs: 50, + backoffFactor: 1, + }) || !pidExists(pid, deps) + ); } function pidCmdlineMatches(pid: number, deps: StaleGatewayDeps): boolean {