Skip to content

fix: clean final gateway failure state after diagnostics - #3018

Merged
ericksoa merged 2 commits into
mainfrom
fix/final-gateway-failure-cleanup
May 6, 2026
Merged

ericksoa merged 2 commits into
mainfrom
fix/final-gateway-failure-cleanup

Conversation

@ericksoa

@ericksoa ericksoa commented May 5, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Preserve final gateway-start diagnostics first, then run destroyGateway() before exiting the exhausted-retry path.
  • Keep intermediate retry cleanup behavior unchanged.
  • Print accurate best-effort manual recovery commands for the nemoclaw gateway if cleanup still needs help.
  • Add focused regression coverage for diagnostics-before-cleanup ordering.

Tests

  • npm run build:cli
  • npm run typecheck:cli
  • npx vitest run test/gateway-final-failure-cleanup.test.ts test/gateway-cleanup.test.ts

Supersedes #2280. Addresses the remaining cleanup gap from #17.

Summary by CodeRabbit

  • Bug Fixes

    • Improved gateway startup failure handling with clearer multi-attempt messaging, automated diagnostic collection (with sensitive data redaction), and standardized cleanup and manual remediation guidance.
  • Tests

    • Added tests covering gateway startup failure flows, diagnostic collection (including fallback when diagnostics fail), cleanup execution, and verification of error output and remediation instructions.

@coderabbitai

coderabbitai Bot commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: a08fb330-0be0-4c9c-9e3b-318a62794cfe

📥 Commits

Reviewing files that changed from the base of the PR and between 288eead and bb694d3.

📒 Files selected for processing (1)
  • src/lib/onboard.ts

📝 Walkthrough

Walkthrough

A new exported helper, handleFinalGatewayStartFailure(), centralizes gateway startup failure handling: it collects/redacts diagnostics, performs best-effort gateway cleanup, prints standardized troubleshooting instructions, and exits via a configurable exit hook. Startup retry logic now delegates to this helper when retries are exhausted.

Changes

Gateway Failure Handler Extraction

Layer / File(s) Summary
Type Definition
src/lib/onboard.ts
Adds FinalGatewayStartFailureOptions describing retries, collectDiagnostics?, cleanupGateway?, exitProcess?, and printError?.
Core Implementation
src/lib/onboard.ts
Adds handleFinalGatewayStartFailure() that: prints attempt/failure messaging, invokes collectDiagnostics() and strips ANSI, calls cleanupGateway() (defaults to destroyGateway()), prints manual remediation/doctor commands, and calls exitProcess(1) (defaults to process.exit).
Integration
src/lib/onboard.ts
Replaces inline final-startup-failure logic in startGatewayWithOptions() with handleFinalGatewayStartFailure({ retries }) when retries are exhausted and exitOnFailure is enabled.
Module Export
src/lib/onboard.ts
Adds handleFinalGatewayStartFailure to module.exports for external access.
Tests
test/gateway-final-failure-cleanup.test.ts
Adds two Vitest cases asserting sequence: diagnostics collection, cleanup, then exit; and that failures in collectDiagnostics still allow cleanup and emit diagnostic-guidance text.

Sequence Diagram

sequenceDiagram
  participant Start as startGatewayWithOptions
  participant Handler as handleFinalGatewayStartFailure
  participant Doctor as "openshell doctor (logs)"
  participant Gateway as cleanupGateway / destroyGateway
  participant Logger as printError
  participant Process as exitProcess

  Start->>Handler: call with { retries }
  Handler->>Logger: print failure header & attempt info
  Handler->>Doctor: collectDiagnostics()
  Doctor-->>Handler: diagnostics (or throws)
  Handler->>Gateway: cleanupGateway() (best-effort)
  Gateway-->>Handler: cleanup result (or error)
  Handler->>Logger: print redacted diagnostics + remediation commands
  Handler->>Process: exitProcess(1)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐰 I hopped through logs when the gateway failed to rise,
I nibbled clues, wiped ANSI from tired eyes,
I cleaned the burrow, left clear next-step commands,
A tidy exit, pawprints neat in the sands.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: refactoring gateway failure handling to run diagnostics before cleanup, which is the core intent of the PR.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/final-gateway-failure-cleanup

Comment @coderabbitai help to get the list of available commands and usage tips.

@ericksoa ericksoa self-assigned this May 5, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/lib/onboard.ts`:
- Around line 2594-2597: The diagnostics probe assigned to collectDiagnostics
can hang and block the final failure path in handleFinalGatewayStartFailure;
wrap the runCaptureOpenshell(["doctor", "logs", "--name", GATEWAY_NAME], {
ignoreError: true }) call in a bounded timeout (e.g., Promise.race with a
setTimeout rejection/resolution or use an existing runWithTimeout helper) so the
probe is abandoned after a short configurable interval, returning/throwing a
timeout result that lets handleFinalGatewayStartFailure continue to call
destroyGateway() and exitProcess(1); update collectDiagnostics to return the
timed wrapper and include a descriptive timeout error or fallback value so
downstream logic handles it safely.
- Around line 2635-2640: Update the fallback recovery printouts to be portable
and use the CLI helper: replace the GNU-specific `xargs -r` invocation with a
POSIX-friendly form such as `xargs -I {} docker volume rm {}` so macOS/BSD xargs
works, and replace the hardcoded `nemoclaw` with the existing cliName() helper;
modify the printError calls that reference GATEWAY_NAME and the CLI invocation
(the lines building the docker volume removal command and the `nemoclaw onboard
--resume` line) to use `GATEWAY_NAME` and `cliName()` respectively.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: d09e91c8-0efc-4c23-bf36-c8270e961280

📥 Commits

Reviewing files that changed from the base of the PR and between b7db7c6 and 288eead.

📒 Files selected for processing (2)
  • src/lib/onboard.ts
  • test/gateway-final-failure-cleanup.test.ts

Comment thread src/lib/onboard.ts Resolved
Comment thread src/lib/onboard.ts
Comment on lines +2635 to +2640
printError(" If gateway cleanup did not complete, run:");
printError(` openshell gateway destroy -g ${GATEWAY_NAME}`);
printError(
` docker volume ls -q --filter "name=openshell-cluster-${GATEWAY_NAME}" | xargs -r docker volume rm`,
);
printError(` nemoclaw onboard --resume`);

@coderabbitai coderabbitai Bot May 5, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Make the printed recovery commands portable and brand-aware.

Line 2638 uses GNU-only xargs -r, which fails on macOS, and Line 2640 hardcodes nemoclaw instead of the existing cliName() helper. Since this is the fallback recovery path, the commands need to work as printed.

Suggested fix
   printError("  If gateway cleanup did not complete, run:");
   printError(`    openshell gateway destroy -g ${GATEWAY_NAME}`);
-  printError(
-    `    docker volume ls -q --filter "name=openshell-cluster-${GATEWAY_NAME}" | xargs -r docker volume rm`,
-  );
-  printError(`    nemoclaw onboard --resume`);
+  printError(
+    `    volumes="$(docker volume ls -q --filter "name=openshell-cluster-${GATEWAY_NAME}")"; [ -z "$volumes" ] || docker volume rm $volumes`,
+  );
+  printError(`    ${cliName()} onboard --resume`);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/onboard.ts` around lines 2635 - 2640, Update the fallback recovery
printouts to be portable and use the CLI helper: replace the GNU-specific `xargs
-r` invocation with a POSIX-friendly form such as `xargs -I {} docker volume rm
{}` so macOS/BSD xargs works, and replace the hardcoded `nemoclaw` with the
existing cliName() helper; modify the printError calls that reference
GATEWAY_NAME and the CLI invocation (the lines building the docker volume
removal command and the `nemoclaw onboard --resume` line) to use `GATEWAY_NAME`
and `cliName()` respectively.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. I am leaving this one unchanged in this PR because the implementation prompt explicitly required the fallback guidance to use nemoclaw, openshell gateway destroy -g nemoclaw, and docker volume ls -q --filter "name=openshell-cluster-nemoclaw" | xargs -r docker volume rm. I agree the BSD/GNU portability point is real; changing that command contract would be a separate decision from this scoped cleanup fix.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ericksoa Got it — thanks for clarifying the prompt constraint. I’ll leave this unchanged for this PR.

If you’d like, I can open a follow-up issue to track:

  • Replace hardcoded “nemoclaw” with cliName() in recovery guidance.
  • Make the docker volume removal line portable across GNU/BSD (avoid xargs -r).
  • Add a brief note in docs/tests to cover macOS portability.

Want me to create that issue and assign it to you?


🧠 Learnings used
Learnt from: jyaunches
Repo: NVIDIA/NemoClaw PR: 2495
File: src/lib/onboard-inference-probes.ts:135-323
Timestamp: 2026-04-27T13:06:57.456Z
Learning: In NVIDIA/NemoClaw PRs that extract code from `src/lib/onboard.ts` into new behavior-preserving modules (e.g., `src/lib/onboard-providers.ts`, `src/lib/onboard-ollama-proxy.ts`, `src/lib/onboard-inference-probes.ts`), reviewers should avoid requesting refactors/complexity/style improvements in the extracted modules as part of the same PR. Only check for correctness and behavior preservation; defer non-behavior-preserving cleanup to separate follow-up PRs.

Learnt from: ericksoa
Repo: NVIDIA/NemoClaw PR: 2554
File: src/lib/onboard.ts:698-700
Timestamp: 2026-04-28T17:22:19.715Z
Learning: For NVIDIA/NemoClaw credential environment hydration/migration, implement fill-only-if-missing semantics across the onboarding and credentials modules: (1) In src/lib/credentials.ts, stageLegacyCredentialsToEnv() should only consider an allowlisted set of credential keys and should set process.env[key] only when getCredential(key) returns null (never override an explicitly provided env export). Treat blank/whitespace values as unset. (2) In src/lib/onboard.ts, hydrateCredentialEnv(envName) must first read getCredential(envName) and only call stageLegacyCredentialsToEnv() when that specific key is missing; after staging, re-read and then set process.env[envName]. This ensures stale credentials.json values cannot override explicitly provided environment credentials.

@ericksoa
ericksoa merged commit ae99c84 into main May 6, 2026
19 checks passed
@wscurran wscurran added bug-fix PR fixes a bug or regression and removed fix labels Jun 3, 2026
@cv
cv deleted the fix/final-gateway-failure-cleanup branch June 28, 2026 00:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug-fix PR fixes a bug or regression

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants