diff --git a/.github/workflows/nightly-e2e.yaml b/.github/workflows/nightly-e2e.yaml index a8f018c9b44..d186ea2c885 100644 --- a/.github/workflows/nightly-e2e.yaml +++ b/.github/workflows/nightly-e2e.yaml @@ -959,8 +959,8 @@ jobs: GITHUB_TOKEN: ${{ github.token }} TELEGRAM_BOT_TOKEN_A: "test-fake-token-A-rotation-e2e" TELEGRAM_BOT_TOKEN_B: "test-fake-token-B-rotation-e2e" - DISCORD_BOT_TOKEN_A: "test-fake-discord-A-rotation-e2e" - DISCORD_BOT_TOKEN_B: "test-fake-discord-B-rotation-e2e" + DISCORD_BOT_TOKEN_A: "discord-a" + DISCORD_BOT_TOKEN_B: "discord-b" SLACK_BOT_TOKEN_A: "xoxb-fake-A-rotation-e2e" SLACK_BOT_TOKEN_B: "xoxb-fake-B-rotation-e2e" SLACK_APP_TOKEN_A: "xapp-fake-A-rotation-e2e" 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/src/lib/core/wait.ts b/src/lib/core/wait.ts index 1bd720a5b2c..bc78a902867 100644 --- a/src/lib/core/wait.ts +++ b/src/lib/core/wait.ts @@ -8,6 +8,40 @@ import { buildValidatedCurlCommandArgs } from "../adapters/http/curl-args"; import { withLocalNoProxy } from "../subprocess-env.js"; +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; + /** Sleep function. Defaults to sleepMs for waitUntil and sleepMsAsync for waitUntilAsync. */ + sleep?: (ms: number) => void; +}; + +type NormalizedWaitUntilOptions = { + deadlineMs: number; + intervalMs: number; + maxIntervalMs: number; + backoffFactor: number; + maxAttempts: number; + hasAttemptCap: boolean; + now: () => number; + sleep: (ms: number) => void | Promise; +}; + +const DEFAULT_TIMEOUT_SECONDS = 10; +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; + /** * Build a curl-friendly env that injects NO_PROXY for loopback hosts so that * probes against localhost-bound services (Ollama, gateway, dashboard, etc.) @@ -32,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. */ @@ -39,20 +81,191 @@ 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; +} + +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; + const timeoutSeconds = + optionsOrTimeout === undefined + ? DEFAULT_TIMEOUT_SECONDS + : nonNegativeFiniteOr(optionsOrTimeout, DEFAULT_TIMEOUT_SECONDS); + const currentMs = now(); + const pollMs = nonNegativeFiniteOr(pollIntervalMs, DEFAULT_INITIAL_INTERVAL_MS); + return { + deadlineMs: Number.isFinite(currentMs) + ? currentMs + timeoutSeconds * 1000 + : Number.NEGATIVE_INFINITY, + intervalMs: pollMs, + maxIntervalMs: pollMs, + backoffFactor: 1, + maxAttempts: Number.POSITIVE_INFINITY, + hasAttemptCap: false, + now, + sleep: defaultSleep, + }; + } + + const now = optionsOrTimeout.now ?? Date.now; + const maxIntervalMs = nonNegativeFiniteOr( + optionsOrTimeout.maxIntervalMs, + DEFAULT_MAX_INTERVAL_MS, + ); + const maxAttempts = + optionsOrTimeout.maxAttempts !== undefined && Number.isFinite(optionsOrTimeout.maxAttempts) + ? Math.max(0, Math.floor(optionsOrTimeout.maxAttempts)) + : Number.POSITIVE_INFINITY; + const hasAttemptCap = Number.isFinite(maxAttempts); + const deadlineMs = + optionsOrTimeout.deadlineMs === undefined + ? Number.POSITIVE_INFINITY + : Number(optionsOrTimeout.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"); + } + + return { + deadlineMs, + intervalMs: Math.min( + nonNegativeFiniteOr(optionsOrTimeout.initialIntervalMs, DEFAULT_INITIAL_INTERVAL_MS), + maxIntervalMs, + ), + maxIntervalMs, + backoffFactor: Math.max( + 1, + positiveFiniteOr(optionsOrTimeout.backoffFactor, DEFAULT_BACKOFF_FACTOR), + ), + maxAttempts, + hasAttemptCap, + now, + sleep: optionsOrTimeout.sleep ?? defaultSleep, + }; +} + +function boundedSleepDurationMs( + intervalMs: number, + remainingMs: number, + hasAttemptCap: boolean, +): number { + const requestedSleepMs = Math.min(intervalMs, remainingMs); + const sleepDurationMs = + !hasAttemptCap && requestedSleepMs <= 0 ? MIN_UNCAPPED_SLEEP_MS : requestedSleepMs; + return Math.min(sleepDurationMs, remainingMs); +} + /** * Synchronously wait until a condition is met. */ +export function waitUntil(conditionFn: () => boolean): boolean; +export function waitUntil(conditionFn: () => boolean, options: WaitUntilOptions): boolean; export function waitUntil( conditionFn: () => boolean, - timeoutSeconds = 10, - pollIntervalMs = 250, + timeoutSeconds?: number, + pollIntervalMs?: number, +): boolean; +export function waitUntil( + conditionFn: () => boolean, + optionsOrTimeout?: WaitUntilOptions | number, + pollIntervalMs?: number, ): boolean { - const start = Date.now(); - while (Date.now() - start < timeoutSeconds * 1000) { + const options = normalizeWaitUntilOptions(optionsOrTimeout, pollIntervalMs); + let attempts = 0; + let intervalMs = options.intervalMs; + + for (;;) { + const currentMs = options.now(); + if (!Number.isFinite(currentMs) || currentMs >= options.deadlineMs) { + return false; + } + if (attempts >= options.maxAttempts) { + return false; + } + attempts += 1; + if (conditionFn()) return true; - sleepMs(pollIntervalMs); + if (attempts >= options.maxAttempts) { + return false; + } + + const postConditionMs = options.now(); + if (!Number.isFinite(postConditionMs) || postConditionMs >= options.deadlineMs) { + return false; + } + options.sleep( + boundedSleepDurationMs( + intervalMs, + options.deadlineMs - postConditionMs, + options.hasAttemptCap, + ), + ); + intervalMs = Math.min(options.maxIntervalMs, intervalMs * options.backoffFactor); + } +} + +/** + * Asynchronously wait until a condition is met. + */ +export function waitUntilAsync(conditionFn: () => boolean | Promise): Promise; +export function waitUntilAsync( + conditionFn: () => boolean | Promise, + options: WaitUntilOptions, +): Promise; +export function waitUntilAsync( + conditionFn: () => boolean | Promise, + timeoutSeconds?: number, + pollIntervalMs?: number, +): Promise; +export async function waitUntilAsync( + conditionFn: () => boolean | Promise, + optionsOrTimeout?: WaitUntilOptions | number, + pollIntervalMs?: number, +): Promise { + const options = normalizeWaitUntilOptions(optionsOrTimeout, pollIntervalMs, sleepMsAsync); + let attempts = 0; + let intervalMs = options.intervalMs; + + for (;;) { + const currentMs = options.now(); + if (!Number.isFinite(currentMs) || currentMs >= options.deadlineMs) { + return false; + } + if (attempts >= options.maxAttempts) { + return false; + } + attempts += 1; + + if (await conditionFn()) return true; + if (attempts >= options.maxAttempts) { + return false; + } + + const postConditionMs = options.now(); + if (!Number.isFinite(postConditionMs) || postConditionMs >= options.deadlineMs) { + return false; + } + await options.sleep( + boundedSleepDurationMs( + intervalMs, + options.deadlineMs - postConditionMs, + options.hasAttemptCap, + ), + ); + intervalMs = Math.min(options.maxIntervalMs, intervalMs * options.backoffFactor); } - return false; } // One-shot TCP reachability probe, evaluated in a short-lived Node subprocess. 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, + }); } diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 8deb3969762..4b82dfb7d63 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -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,31 +2040,21 @@ 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 }); - // Require BOTH the openshell CLI metadata to report healthy AND the - // host HTTP endpoint to be serving — the CLI metadata can report - // healthy from the previous run while the upstream is still warming - // up after a Docker daemon restart, leading to "Connection refused" - // in step 4. See #3258. - if (isGatewayHealthy(status, namedInfo, currentInfo) && (await isGatewayHttpReady())) { - return; // success - } - if (i < healthPollCount - 1) sleepSeconds(healthPollInterval); + if ( + await waitForGatewayHealth({ + attachGatewayMetadataIfNeeded, + gatewayClusterHealthcheckPassed, + gatewayName: GATEWAY_NAME, + healthPollCount: healthWait.count, + healthPollIntervalSeconds: healthWait.interval, + isGatewayHealthy, + isGatewayHttpReady, + repairGatewayBootstrapSecrets, + runCaptureOpenshell, + sleepSeconds, + }) + ) { + return; } throw new Error("Gateway failed to start"); 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."; 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"); + }); +}); 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), + }, + )) + ); +} 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; 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 { 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 { diff --git a/src/lib/sandbox/channels.ts b/src/lib/sandbox/channels.ts index 7316989546c..0446cde797b 100644 --- a/src/lib/sandbox/channels.ts +++ b/src/lib/sandbox/channels.ts @@ -114,7 +114,7 @@ export const KNOWN_CHANNELS: Record = { appTokenHelp: "Slack API → Your Apps → Basic Information → App-Level Tokens (xapp-...).", appTokenLabel: "Slack App Token (Socket Mode)", appTokenFormat: /^xapp-[A-Za-z0-9_-]+$/, - appTokenFormatHint: "Slack app tokens start with 'xapp-' (e.g. xapp-1-A0000-12345-abcdef).", + appTokenFormatHint: "Slack app tokens start with 'xapp-'.", userIdEnvKey: "SLACK_ALLOWED_USERS", userIdHelp: "In Slack, open each allowed human user's profile -> More -> Copy member ID. Enter one or more comma-separated member IDs, not the app or bot user ID. Member IDs look like U01ABC2DEF3.", 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; + } + } + }); }); diff --git a/test/wait.test.ts b/test/wait.test.ts index 97187978195..c382dc4034d 100644 --- a/test/wait.test.ts +++ b/test/wait.test.ts @@ -3,8 +3,15 @@ import assert from "node:assert"; import { createServer, type AddressInfo } from "node:net"; -import { afterEach, describe, it } from "vitest"; -import { buildLoopbackProbeEnv, sleepMs, sleepSeconds, waitForPort } from "../src/lib/core/wait.js"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + buildLoopbackProbeEnv, + sleepMs, + sleepSeconds, + waitForPort, + waitUntil, + waitUntilAsync, +} from "../src/lib/core/wait.js"; describe("wait utility", () => { it("sleepMs blocks for approximately the requested time", () => { @@ -39,6 +46,277 @@ 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 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, { + deadlineMs: Number.NaN, + now: () => 0, + sleep: () => {}, + }), + ).toThrow(TypeError); + }); + + 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(3); + 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]); + }); + + 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(3); + expect(sleeps).toEqual([1, 1, 1]); + }); + + it("waitUntilAsync retries until the async condition succeeds", async () => { + const sleeps: number[] = []; + let attempts = 0; + let nowMs = 0; + + const result = await waitUntilAsync( + async () => { + attempts += 1; + return attempts >= 3; + }, + { + initialIntervalMs: 5, + maxIntervalMs: 5, + maxAttempts: 4, + now: () => nowMs, + sleep: (ms) => { + sleeps.push(ms); + nowMs += ms; + }, + }, + ); + + expect(result).toBe(true); + 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)", () => {