Skip to content

fix(e2e): make nightly teardown reliable and prevent sandbox leaks - #2313

Merged
brandonpelfrey merged 12 commits into
mainfrom
prekshi/nightly-e2e-cleanup-robustness
Apr 23, 2026
Merged

brandonpelfrey merged 12 commits into
mainfrom
prekshi/nightly-e2e-cleanup-robustness

Conversation

@prekshivyas

@prekshivyas prekshivyas commented Apr 23, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Addresses the recent network-policy-e2e flake in nightly-e2e and the broader sandbox-leak pattern across the e2e suite.

Root cause (immediate flake)

In run 24806434211 the network-policy-e2e job failed at onboard with:

Sandbox 'e2e-net-policy' already exists but is not ready.
Pass --recreate-sandbox or set NEMOCLAW_RECREATE_SANDBOX=1 to overwrite.
FATAL: Onboard failed

A prior run on the shared Brev launchable left e2e-net-policy in a not-ready state. Neither the workflow nor test-network-policy.sh set NEMOCLAW_RECREATE_SANDBOX=1, and the script's preflight cleanup (test-network-policy.sh:217) was guarded by nemoclaw list | grep, which does not surface not-ready sandboxes — so the preflight destroy never fired.

Broader issue (sandbox leaks)

15 of 27 test/e2e/test-*.sh scripts had no trap teardown EXIT. A mid-run failure leaves the sandbox alive on the launchable until the next run's NEMOCLAW_RECREATE_SANDBOX=1 clobbers it (if set). On the shared launchable this accumulates as dangling k8s pods, netns, volumes — eventually producing the exact not-ready state this PR is closing.

Changes

  • .github/workflows/nightly-e2e.yaml — add NEMOCLAW_RECREATE_SANDBOX: "1" to the 3 jobs still missing it: network-policy-e2e, inference-routing-e2e, deployment-services-e2e.
  • test/e2e/test-network-policy.sh, test/e2e/test-inference-routing.sh — replace list | grep-gated preflight destroys with unconditional nemoclaw "$SANDBOX_NAME" destroy --yes 2>/dev/null || true. Post-failure assertions (e.g. TC-INF-06/07 checking that no sandbox was created after a bad key) kept unchanged — those are checks, not cleanup.
  • test/e2e/lib/sandbox-teardown.sh — new shared helper (executable, #!/usr/bin/env bash). Registers each sandbox name and installs a single trap … EXIT that destroys every registered sandbox and clears onboard.lock. Keeps the per-script diff to two lines so reviewers can audit the full wiring quickly.
  • 15 test scripts wired up: credential-sanitization, full-e2e, hermes-e2e, messaging-providers, onboard-repair (two sandboxes), onboard-resume, rebuild-hermes, rebuild-openclaw, sandbox-rebuild, sandbox-survival, shields-config, skip-permissions-policy, snapshot-commands, telegram-injection, upgrade-stale-sandbox.
  • test-onboard-repair.sh, test-onboard-resume.sh — extra conditional shim: if ! command -v nemoclaw; then nemoclaw() { node "$REPO/bin/nemoclaw.js" "$@"; }; fi. These two scripts drive the CLI via run_nemoclaw (bare node bin/nemoclaw.js) and don't assume a global CLI on PATH; without the shim, the trap's nemoclaw destroy would silently no-op in repo-local dev runs. CI (with install-openshell.sh + npm link on PATH) skips the shim.
  • NEMOCLAW_E2E_KEEP_SANDBOX=1 escape hatch so a local dev reproducing a flake can inspect the sandbox after the test — CI never sets this variable.
  • .gitleaksignore — allowlist two pre-existing false-positives (discord-client-secret rule matching the fake DISCORD_BOT_TOKEN_A/_B strings at nightly-e2e.yaml:232-233 from test(e2e): skip cleanly under VPN, cover Discord token rotation #2257). These are test fakes, not secrets. Unblocks pre-commit for any branch rebased onto current main.

Intentionally skipped

  • test-runtime-overrides.sh — pure docker run --rm, no sandbox.
  • test-spark-install.sh — install smoke, no sandbox.
  • 10 scripts that already set a trap teardown EXIT themselves were not changed, because sourcing the helper would silently replace their existing trap: deployment-services, diagnostics, double-onboard, gpu-e2e, inference-routing, network-policy, ollama-auth-proxy, sandbox-operations, token-rotation, e2e-cloud-experimental.

Type of Change

  • Code change for a bug fix / infra robustness improvement.

Testing

  • bash -n syntax check on all 18 modified scripts + new helper — passes
  • Helper smoke test with mock nemoclaw: register_sandbox_for_teardown registered two sandboxes, EXIT trap dispatched nemoclaw destroy --yes for both; with NEMOCLAW_E2E_KEEP_SANDBOX=1 set, teardown correctly returned early without destroying
  • Double-destroy audit: grepped all 15 modified scripts — every one already has an end-of-main destroy --yes || true. My trap adds a second destroy on EXIT that's idempotent (|| true) and silent (>/dev/null 2>&1). Functionally zero impact on success paths; benefit is protection on failure paths where mid-script exit skips the end-of-main destroy.
  • No self-conflicting traps: grepped all 15 modified scripts — zero trap/exec calls. My helper's trap is the sole EXIT handler in each.
  • $REPO ordering verified — defined at test-onboard-repair.sh:51-53 / test-onboard-resume.sh:67-69, well before the shim at line 70 / 85.
  • pre-commit hooks (prek) clean: shellcheck, shfmt, commitlint, YAML validator, CLI test suite, gitleaks
  • Nightly E2E on this branch — run 24810292642 exercises the preflight + helper + wiring changes. A follow-up run will be triggered on the latest HEAD to cover the CodeRabbit fixes (shebang + shim).

Known gaps (not in this PR)

CI coverage: 5 of 15 modified scripts aren't invoked by any GH Actions workflow — test-credential-sanitization, test-onboard-repair, test-onboard-resume, test-sandbox-rebuild, test-telegram-injection. Changes are defensive (they benefit when run locally or from ad-hoc workflows) but aren't exercised in the automated suite.

Signal handling: the helper traps EXIT only (matching the existing convention in the 10 skipped scripts). SIGINT / SIGTERM / SIGKILL are not handled — consistent with the rest of the e2e suite.

.gitleaksignore fingerprints are positional (line 232/233 of nightly-e2e.yaml). Inherent limitation of gitleaks' allowlist format.

Out of scope (filed for a follow-up):

  • Workflow-level if: always() post-job cleanup (belt-and-suspenders against script crashes that never reach the trap)
  • Pre-run e2e-* sweeper at the launchable level

Signed-off-by: Prekshi Vyas [email protected]

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Tests

    • Centralized sandbox teardown added to E2E tests; most scripts now register sandboxes for automatic cleanup.
    • Some preflight cleanup changed to attempt unconditional sandbox destroy to reduce flaky preflight checks.
    • Added support so teardown works even when the test CLI isn’t globally installed.
  • Chores

    • CI E2E runs now request sandbox recreation for nightly jobs.
    • Updated secret-scan ignore entries for the nightly E2E workflow.

Root cause of the recent `network-policy-e2e` flake: a prior run left
`e2e-net-policy` in a not-ready state on the shared Brev launchable, and
onboard refused to overwrite because neither the workflow nor the test
script set `NEMOCLAW_RECREATE_SANDBOX=1`. The preflight cleanup at
`test-network-policy.sh:217` was guarded by `nemoclaw list | grep`,
which does not surface not-ready sandboxes, so the destroy never fired.

More broadly, 15 of 27 e2e test scripts had no `trap teardown EXIT`, so
a mid-run failure left the sandbox alive on the launchable until the
next run's `NEMOCLAW_RECREATE_SANDBOX=1` clobbered it (if set). On the
shared launchable this accumulates as dangling k8s pods, netns, volumes
and eventually pushes later runs into the not-ready state this PR is
closing.

Changes:
- `.github/workflows/nightly-e2e.yaml`: add `NEMOCLAW_RECREATE_SANDBOX: "1"`
  to the three jobs still missing it: `network-policy-e2e`,
  `inference-routing-e2e`, `deployment-services-e2e`.
- `test/e2e/test-network-policy.sh`, `test/e2e/test-inference-routing.sh`:
  replace the `list | grep`-gated preflight destroy with an unconditional
  `nemoclaw "$SANDBOX_NAME" destroy --yes 2>/dev/null || true`. Catches
  not-ready sandboxes the grep misses. Post-failure assertions (e.g.
  TC-INF-06/07 checking that no sandbox was created after a bad key)
  kept unchanged — those are checks, not cleanup.
- `test/e2e/lib/sandbox-teardown.sh`: new shared helper. Registers each
  sandbox name and installs a single `trap ... EXIT` that destroys every
  registered sandbox and clears the onboard.lock. Keeps the per-script
  diff to two lines so reviewers can audit the full wiring quickly.
- 15 test scripts sourced the helper and called
  `register_sandbox_for_teardown "$SANDBOX_NAME"` right after the name is
  defined: credential-sanitization, full-e2e, hermes-e2e, messaging-
  providers, onboard-repair (two sandboxes), onboard-resume, rebuild-
  hermes, rebuild-openclaw, sandbox-rebuild, sandbox-survival, shields-
  config, skip-permissions-policy, snapshot-commands, telegram-injection,
  upgrade-stale-sandbox.
- `test-runtime-overrides.sh` (pure `docker run --rm`) and
  `test-spark-install.sh` (install smoke, no sandbox) intentionally left
  alone — they create no sandbox to tear down.
- 10 scripts that already set a `trap teardown EXIT` themselves were not
  changed, because sourcing the helper would silently replace their
  existing trap. Covered: deployment-services, diagnostics, double-
  onboard, gpu-e2e, inference-routing, network-policy, ollama-auth-proxy,
  sandbox-operations, token-rotation, e2e-cloud-experimental.

Out of scope (filed for a follow-up): workflow-level `if: always()`
post-job cleanup (belt-and-suspenders against script crashes that never
reach the trap), and a pre-run `e2e-*` sweeper at the launchable level.

Signed-off-by: Prekshi Vyas <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Apr 23, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a shared E2E sandbox teardown helper and wires it into many test scripts to register sandboxes for exit-time destruction, changes some preflight steps to unconditionally destroy sandboxes, and sets NEMOCLAW_RECREATE_SANDBOX="1" in three nightly E2E workflow jobs.

Changes

Cohort / File(s) Summary
Workflow Configuration
\.github/workflows/nightly-e2e.yaml
Sets NEMOCLAW_RECREATE_SANDBOX="1" in the environment for the inference-routing-e2e, network-policy-e2e, and deployment-services-e2e jobs.
Sandbox Teardown Helper
test/e2e/lib/sandbox-teardown.sh
Adds a sourced helper that provides register_sandbox_for_teardown() and installs an EXIT trap to run nemoclaw <sandbox> destroy --yes for registered sandboxes; the teardown suppresses errors and intentionally does not remove ~/.nemoclaw/onboard.lock.
Unconditional Preflight Destroy
test/e2e/test-inference-routing.sh, test/e2e/test-network-policy.sh
Replaces conditional nemoclaw list checks with unconditional nemoclaw <sandbox> destroy --yes attempts in preflight; stderr suppressed and failures ignored.
Teardown Integration — Test Suite
test/e2e/test-credential-sanitization.sh, test/e2e/test-full-e2e.sh, test/e2e/test-hermes-e2e.sh, test/e2e/test-messaging-providers.sh, test/e2e/test-onboard-repair.sh, test/e2e/test-onboard-resume.sh, test/e2e/test-rebuild-hermes.sh, test/e2e/test-rebuild-openclaw.sh, test/e2e/test-sandbox-rebuild.sh, test/e2e/test-sandbox-survival.sh, test/e2e/test-shields-config.sh, test/e2e/test-skip-permissions-policy.sh, test/e2e/test-snapshot-commands.sh, test/e2e/test-telegram-injection.sh, test/e2e/test-upgrade-stale-sandbox.sh
Each test now sources the sandbox teardown helper and calls register_sandbox_for_teardown (typically after SANDBOX_NAME is set) to schedule automatic cleanup at exit; core test flows remain unchanged.
Gitleaks Ignore
.gitleaksignore
Adds entries to ignore two discord-client-secret findings at specific lines in nightly-e2e.yaml.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Script
    participant Helper as Sandbox Teardown Helper
    participant CLI as nemoclaw CLI
    rect rgba(200,220,255,0.5)
        Test->>Helper: source lib/sandbox-teardown.sh
        Test->>Helper: register_sandbox_for_teardown(SANDBOX_NAME)
    end
    rect rgba(200,255,200,0.5)
        Note over Helper,Test: On process EXIT
        Helper->>CLI: nemoclaw SANDBOX_NAME destroy --yes (stderr suppressed)
        CLI-->>Helper: exit status (ignored)
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I hop through scripts with gentle paws,
I mark each den with cleanup laws,
On exit I whisper, "time to sweep,"
Sandboxes tuck in, fall fast asleep,
Hooray — tidy burrows, peaceful jaws.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.15% 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 clearly summarizes the main purpose of the changeset: making nightly E2E teardown reliable and preventing sandbox resource leaks through centralized trap-based cleanup.
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch prekshi/nightly-e2e-cleanup-robustness

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

@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

🧹 Nitpick comments (1)
test/e2e/lib/sandbox-teardown.sh (1)

39-39: Prefer trap chaining to avoid potential clobbering in sourced context.

Line 39 unconditionally sets trap ... EXIT. While no current caller defines conflicting EXIT traps, the sourced pattern could be fragile. Consider using trap chaining (e.g., saving the existing trap and calling it within _nemoclaw_sandbox_teardown) or guarded installation to handle cases where a caller may define their own EXIT trap.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/e2e/lib/sandbox-teardown.sh` at line 39, The EXIT trap currently
unconditionally overwrites any existing trap by calling trap
_nemoclaw_sandbox_teardown EXIT; instead, preserve and chain the prior EXIT
trap: capture the current EXIT trap command (e.g., via existing_trap="$(trap -p
EXIT)") before installing the new trap, and modify _nemoclaw_sandbox_teardown to
invoke the preserved command (if any) after running its teardown steps; install
the trap so it calls both _nemoclaw_sandbox_teardown and the saved handler (or
guard against re-installing if already set) to avoid clobbering sourced
contexts.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@test/e2e/lib/sandbox-teardown.sh`:
- Around line 1-7: This file is missing the required shebang; add the line
"#!/usr/bin/env bash" as the very first line (above the SPDX headers) in
test/e2e/lib/sandbox-teardown.sh, then reformat with shfmt, run ShellCheck to
fix any issues, and ensure the file has the executable bit set so it satisfies
the repo shell-file requirements for shell scripts.

In `@test/e2e/test-onboard-repair.sh`:
- Around line 66-70: The EXIT trap in lib/sandbox-teardown.sh can call a bare
"nemoclaw" which will no-op if there's no global binary; ensure the teardown
uses the same invoker as tests by exporting or setting a NE MOCLAW_CMD (or
similar) to node "$REPO/bin/nemoclaw.js" and have register_sandbox_for_teardown
/ the trap call that variable (or call run_nemoclaw) instead of a plain
"nemoclaw"; update the test bootstrap (where register_sandbox_for_teardown is
called) to set and export the command (or source the run_nemoclaw wrapper) so
sandbox-teardown.sh always uses the correct node "$REPO/bin/nemoclaw.js"
invocation for cleanup.

---

Nitpick comments:
In `@test/e2e/lib/sandbox-teardown.sh`:
- Line 39: The EXIT trap currently unconditionally overwrites any existing trap
by calling trap _nemoclaw_sandbox_teardown EXIT; instead, preserve and chain the
prior EXIT trap: capture the current EXIT trap command (e.g., via
existing_trap="$(trap -p EXIT)") before installing the new trap, and modify
_nemoclaw_sandbox_teardown to invoke the preserved command (if any) after
running its teardown steps; install the trap so it calls both
_nemoclaw_sandbox_teardown and the saved handler (or guard against re-installing
if already set) to avoid clobbering sourced contexts.
🪄 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: Pro Plus

Run ID: 48ebf79e-3847-4539-a80b-ffa987364219

📥 Commits

Reviewing files that changed from the base of the PR and between 5fec344 and 6acbb4c.

📒 Files selected for processing (19)
  • .github/workflows/nightly-e2e.yaml
  • test/e2e/lib/sandbox-teardown.sh
  • test/e2e/test-credential-sanitization.sh
  • test/e2e/test-full-e2e.sh
  • test/e2e/test-hermes-e2e.sh
  • test/e2e/test-inference-routing.sh
  • test/e2e/test-messaging-providers.sh
  • test/e2e/test-network-policy.sh
  • test/e2e/test-onboard-repair.sh
  • test/e2e/test-onboard-resume.sh
  • test/e2e/test-rebuild-hermes.sh
  • test/e2e/test-rebuild-openclaw.sh
  • test/e2e/test-sandbox-rebuild.sh
  • test/e2e/test-sandbox-survival.sh
  • test/e2e/test-shields-config.sh
  • test/e2e/test-skip-permissions-policy.sh
  • test/e2e/test-snapshot-commands.sh
  • test/e2e/test-telegram-injection.sh
  • test/e2e/test-upgrade-stale-sandbox.sh

Comment thread test/e2e/lib/sandbox-teardown.sh Resolved
Comment thread test/e2e/test-onboard-repair.sh Resolved
prekshivyas and others added 4 commits April 22, 2026 17:32
`nightly-e2e.yaml:232-233` sets `DISCORD_BOT_TOKEN_A`/`_B` to the fake
values `test-fake-discord-A-rotation-e2e` and `test-fake-discord-B-
rotation-e2e` as part of the token-rotation E2E (added in #2257). The
`discord-client-secret` gitleaks rule false-positives on these strings
because the entropy and shape match the pattern. These values are not
secrets and never leave CI.

Unblocks pre-commit for any branch that rebases on current main.

Signed-off-by: Prekshi Vyas <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Local-dev scenario: a developer runs a single e2e script to reproduce a
flake, wants to inspect the sandbox (logs, filesystem, config) after the
test passes or fails. The new trap-based teardown destroys the sandbox
on every EXIT, including success, which removes that inspection target.

With NEMOCLAW_E2E_KEEP_SANDBOX=1 set, _nemoclaw_sandbox_teardown returns
early and leaves everything — sandbox and onboard.lock — in place. CI
never sets this variable, so nightly behavior is unchanged.

Signed-off-by: Prekshi Vyas <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1. `test/e2e/lib/sandbox-teardown.sh`: add `#!/usr/bin/env bash` shebang
   (above SPDX headers) and the executable bit to satisfy the repo's
   shell-file convention. The file is still meant to be sourced, not
   executed — shebang is for convention + shellcheck inference, not
   runtime.

2. `test/e2e/test-onboard-repair.sh`, `test/e2e/test-onboard-resume.sh`:
   these scripts drive the CLI via `run_nemoclaw()` which calls
   `node "$REPO/bin/nemoclaw.js"` and do not assume a globally-installed
   `nemoclaw` binary is on PATH. The teardown helper's EXIT trap calls
   `nemoclaw "$sbx" destroy --yes`, which would silently no-op in a
   repo-local dev environment with no global CLI.

   Add a conditional shim function before sourcing the helper so the
   trap routes through `node bin/nemoclaw.js` when no global is
   available. CI (where `install-openshell.sh` + `npm link` put
   `nemoclaw` on PATH) sees the shim skipped.

Signed-off-by: Prekshi Vyas <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@prekshivyas

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

Previous review comments have been addressed in commit 0e82e71:

  • Shebang #!/usr/bin/env bash added + executable bit set on test/e2e/lib/sandbox-teardown.sh
  • nemoclaw() shim added to test-onboard-repair.sh and test-onboard-resume.sh so the teardown trap works when the scripts drive the CLI via node bin/nemoclaw.js without a global nemoclaw on PATH

@coderabbitai

coderabbitai Bot commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

@prekshivyas: Thanks for the update! I'll redo the full review now, taking into account the changes from commit 0e82e71 (shebang + executable bit on sandbox-teardown.sh, and the nemoclaw() shims in test-onboard-repair.sh and test-onboard-resume.sh).

✅ Actions performed

Full review triggered.

@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: 1

🧹 Nitpick comments (1)
test/e2e/test-snapshot-commands.sh (1)

31-31: Honor NEMOCLAW_E2E_KEEP_SANDBOX=1 in explicit cleanup too.

Registration is good, but Line 217 still destroys the sandbox unconditionally. That bypasses the KEEP_SANDBOX escape hatch on successful runs.

♻️ Suggested patch
 info "Cleaning up..."
-nemoclaw "${SANDBOX_NAME}" destroy --yes 2>/dev/null || true
+if [[ "${NEMOCLAW_E2E_KEEP_SANDBOX:-}" != "1" ]]; then
+  nemoclaw "${SANDBOX_NAME}" destroy --yes 2>/dev/null || true
+else
+  info "Skipping sandbox destroy (NEMOCLAW_E2E_KEEP_SANDBOX=1)"
+fi

Also applies to: 215-218

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/e2e/test-snapshot-commands.sh` at line 31, The explicit sandbox teardown
currently always destroys the sandbox even when NEMOCLAW_E2E_KEEP_SANDBOX=1;
update the explicit cleanup code that calls the sandbox-destroying logic (the
place that invokes register_sandbox_for_teardown and the subsequent
unconditional destroy call) to first check the NEMOCLAW_E2E_KEEP_SANDBOX
environment variable and skip the destroy when it is set (e.g., if [ -n
"$NEMOCLAW_E2E_KEEP_SANDBOX" ] || [ "$NEMOCLAW_E2E_KEEP_SANDBOX" = "1" ]; then
echo "Keeping sandbox"; else destroy_sandbox_or_call_existing_teardown; fi), and
apply the same conditional guard to the other explicit cleanup site mentioned so
both spots honor the escape hatch.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@test/e2e/lib/sandbox-teardown.sh`:
- Around line 31-38: The teardown script currently unconditionally removes the
global onboard lock (~/.nemoclaw/onboard.lock); instead, before calling rm -f,
check ownership and only remove the lock if it is owned by the current
process/user (e.g. use test -O "$HOME/.nemoclaw/onboard.lock" or compare $(stat
-c %u ...) to $UID), so update the block around the rm invocation in
sandbox-teardown.sh (the branch governed by NEMOCLAW_E2E_KEEP_SANDBOX) to
perform that ownership check and only unlink the file when ownership matches.

---

Nitpick comments:
In `@test/e2e/test-snapshot-commands.sh`:
- Line 31: The explicit sandbox teardown currently always destroys the sandbox
even when NEMOCLAW_E2E_KEEP_SANDBOX=1; update the explicit cleanup code that
calls the sandbox-destroying logic (the place that invokes
register_sandbox_for_teardown and the subsequent unconditional destroy call) to
first check the NEMOCLAW_E2E_KEEP_SANDBOX environment variable and skip the
destroy when it is set (e.g., if [ -n "$NEMOCLAW_E2E_KEEP_SANDBOX" ] || [
"$NEMOCLAW_E2E_KEEP_SANDBOX" = "1" ]; then echo "Keeping sandbox"; else
destroy_sandbox_or_call_existing_teardown; fi), and apply the same conditional
guard to the other explicit cleanup site mentioned so both spots honor the
escape hatch.
🪄 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: Pro Plus

Run ID: be3627e5-064a-4ea5-ad10-35b2e261a423

📥 Commits

Reviewing files that changed from the base of the PR and between 21c537c and 0e82e71.

📒 Files selected for processing (20)
  • .github/workflows/nightly-e2e.yaml
  • .gitleaksignore
  • test/e2e/lib/sandbox-teardown.sh
  • test/e2e/test-credential-sanitization.sh
  • test/e2e/test-full-e2e.sh
  • test/e2e/test-hermes-e2e.sh
  • test/e2e/test-inference-routing.sh
  • test/e2e/test-messaging-providers.sh
  • test/e2e/test-network-policy.sh
  • test/e2e/test-onboard-repair.sh
  • test/e2e/test-onboard-resume.sh
  • test/e2e/test-rebuild-hermes.sh
  • test/e2e/test-rebuild-openclaw.sh
  • test/e2e/test-sandbox-rebuild.sh
  • test/e2e/test-sandbox-survival.sh
  • test/e2e/test-shields-config.sh
  • test/e2e/test-skip-permissions-policy.sh
  • test/e2e/test-snapshot-commands.sh
  • test/e2e/test-telegram-injection.sh
  • test/e2e/test-upgrade-stale-sandbox.sh

Comment thread test/e2e/lib/sandbox-teardown.sh Resolved
prekshivyas and others added 5 commits April 22, 2026 18:01
CodeRabbit correctly flagged that the teardown helper's
`rm -f ~/.nemoclaw/onboard.lock` is unsafe on shared machines: that lock
is global and PID-ownership-aware in `src/lib/onboard-session.ts`
(acquireOnboardLock / releaseOnboardLock verify the holder's PID and
the file's inode before touching it). A concurrent e2e run on the same
host could have a live lock; our unconditional rm would yank it out
from under them.

Drop the rm line from the helper. A crashed process leaves a stale
lock; the next onboard detects it via isProcessAlive + inode check in
acquireOnboardLock and cleans it up automatically. No change in observed
behavior for the crashed-run-then-retry case the rm was meant to cover.

Nightly CI runs on isolated ubuntu-latest runners per job, so concurrent
locks don't happen there — but the shared Brev launchable and any
local-dev machine with two e2e scripts running in parallel both benefit.

Does NOT touch the ten existing scripts that do the same rm -f in their
own teardowns (test-network-policy.sh, test-deployment-services.sh,
test-inference-routing.sh, test-diagnostics.sh, test-sandbox-operations.sh,
test-token-rotation.sh, test-ollama-auth-proxy-e2e.sh, test-double-onboard.sh,
test-gpu-e2e.sh, test-e2e-cloud-experimental.sh) — that's a pre-existing
pattern worth a separate audit.

Signed-off-by: Prekshi Vyas <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…anup

CodeRabbit nitpick on #2313: the escape hatch I added only gated the
trap-based teardown in sandbox-teardown.sh. Each individual test script
also calls `nemoclaw "$SANDBOX_NAME" destroy --yes` in its own
end-of-main cleanup section, which bypassed the env var — so a
successful run still destroyed the sandbox despite `KEEP_SANDBOX=1`.

Guard each affected end-of-main destroy with:

  [[ "${NEMOCLAW_E2E_KEEP_SANDBOX:-}" = "1" ]] || nemoclaw … destroy …

`|` binds tighter than `||`, so the pipe variants parse correctly:
`[[ X ]] || (nemoclaw … | tail -3) || true`.

Guarded sites (12 scripts):
- test-full-e2e.sh, test-hermes-e2e.sh, test-messaging-providers.sh,
  test-rebuild-hermes.sh, test-rebuild-openclaw.sh,
  test-sandbox-rebuild.sh, test-sandbox-survival.sh (two sites: jump-to-
  cleanup early exit + final cleanup), test-shields-config.sh,
  test-skip-permissions-policy.sh, test-snapshot-commands.sh
- test-onboard-repair.sh (two sandboxes wrapped in one if-block),
  test-onboard-resume.sh

Intentionally **not** guarded:
- Preflight destroys at script start — those should always run so the
  onboard gets a clean slate.
- Mid-test destroys that are part of the test logic (e.g.
  test-sandbox-survival.sh's backup-workspace cycle destroys the
  sandbox as a test step, not as cleanup).
- Follow-up `openshell gateway destroy` / `openshell sandbox delete`
  calls after the main destroy — scoped to one target per commit.

Signed-off-by: Prekshi Vyas <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Extends the fix in cfc90f6 (which removed the unsafe rm from my new
sandbox-teardown.sh helper) to every pre-existing `teardown()` function
in the 10 scripts my PR skipped because they already had their own trap.

Five of those scripts did the same unconditional
`rm -f ~/.nemoclaw/onboard.lock` in their trap-based teardown. On a
shared host with concurrent e2e runs, that could yank a live lock out
from under another process. `acquireOnboardLock` in
`src/lib/onboard-session.ts` is PID-ownership-aware (liveness + inode
check), so a crashed process's stale lock gets cleaned up automatically
on the next onboard; the explicit rm is unnecessary.

Sites removed (all inside trap-based teardown()/cleanup() functions):
- test-network-policy.sh:537
- test-deployment-services.sh:413
- test-diagnostics.sh:394
- test-sandbox-operations.sh:657
- test-inference-routing.sh:665

Other 5 scripts in the "has own trap" cohort (test-token-rotation,
test-ollama-auth-proxy-e2e, test-double-onboard, test-gpu-e2e,
test-e2e-cloud-experimental) do not unlink the onboard.lock in their
teardown — nothing to remove.

Intentionally NOT changing:
- Preflight `rm -f` calls at the top of setup_sandbox / test functions.
  Same unsafe-under-concurrency pattern, but scoped to a narrow window
  right before onboard. Out of scope for this PR.

Signed-off-by: Prekshi Vyas <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
When I expanded the workflow env var to three jobs earlier in this PR
I used "consistency with other jobs" as the rationale. That turned out
to be wrong for two of the three — the env var introduces an
unnecessary delete+create cycle that hit an openshell k8s race in
nightly run 24811493024:

  Sandbox 'e2e-deploy' exists and is ready — recreating by explicit request.
  Deleted sandbox e2e-deploy
  [image rebuild, ~2 min]
  × sandbox 'e2e-deploy' already exists
  FATAL: Onboard failed for 'e2e-deploy'

Audit of the three jobs I set the env var on:

- network-policy-e2e: install.sh's onboard leaves the sandbox in a
  not-ready state that `nemoclaw list | grep` doesn't surface, so the
  test's second onboard hits "already exists but not ready" without
  RECREATE=1. KEEP.
- inference-routing-e2e: test-inference-routing.sh now does an
  unconditional preflight destroy (my change earlier in this PR) at
  every call site. Setting RECREATE=1 on top of that is redundant.
  Passed without it on main for the four most recent runs. REMOVE.
- deployment-services-e2e: test-deployment-services.sh's
  `onboard_sandbox()` has no preflight destroy; it just runs
  `nemoclaw onboard` and — on main — reuses the Ready sandbox that
  install.sh already created. Adding RECREATE=1 turned a clean reuse
  into a delete+rebuild+recreate round-trip that raced openshell's
  k8s pod teardown. REMOVE.

Signed-off-by: Prekshi Vyas <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Eight nightly jobs set `NEMOCLAW_RECREATE_SANDBOX: "1"` at the workflow
level while their test scripts already set the same variable internally
(via `export` or an inline per-onboard call). The workflow-level env is
pure duplication — removing it makes the "who actually relies on the
env var" answer visible at the workflow level.

Jobs trimmed (internal handling preserves behaviour):

- messaging-providers-e2e (test-messaging-providers.sh:192 exports)
- sandbox-survival-e2e (test-sandbox-survival.sh:204 sets per call)
- skip-permissions-e2e (test-skip-permissions-policy.sh:140 per call)
- snapshot-commands-e2e (test-snapshot-commands.sh:64 exports)
- shields-config-e2e (test-shields-config.sh:123 exports)
- rebuild-openclaw-e2e (test-rebuild-openclaw.sh:75 exports)
- upgrade-stale-sandbox-e2e (test-upgrade-stale-sandbox.sh:65 exports)
- rebuild-hermes-e2e (test-rebuild-hermes.sh:70 exports)

Jobs that keep the workflow-level env var (they need it — test scripts
do not force recreate internally):

- cloud-e2e, cloud-experimental-e2e, hermes-e2e, diagnostics-e2e, gpu-e2e
  (carryover from earlier main, kept to avoid scope creep on this PR)
- network-policy-e2e (my addition — belt-and-suspenders for the
  install.sh "not-ready sandbox" flake this PR is closing)

Signed-off-by: Prekshi Vyas <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@prekshivyas
prekshivyas requested a review from ericksoa April 23, 2026 02:37
@brandonpelfrey

Copy link
Copy Markdown
Contributor

Automated PR review summary

Reviewed PR #2313: fix(e2e): make nightly teardown reliable and prevent sandbox leaks

Recommendation

  • Recommendation: PASS
  • Highest observed severity: low
  • Block merge: no
  • Why: The highest-risk PR-specific behaviors I could validate in this session passed: the new shared teardown helper destroys all registered sandboxes and respects the KEEP escape hatch, the repair/resume scripts define the repo-local CLI shim before sourcing the helper, and the network-policy/inference-routing preflight logic now uses unconditional destroy instead of list-gated cleanup. I could not reattach to the install-session sandbox for stronger runtime validation because openshell sandbox ssh-config nemoclaw-local returned 'sandbox not found' in this separate session, but the available evidence does not indicate a regression in the PR itself.
  • Reviewer summary: Reviewed the PR with PR-specific adversarial probes. Core teardown/preflight claims held under targeted validation; the only failed probe was cross-session access to the install-created sandbox, which limited runtime E2E evidence but did not reveal a PR regression.

Installation and setup findings

  • Things went well: Installed the locally checked out Nemoclaw via the repo installer entrypoint and verified the NemoClaw-managed sandbox is usable over SSH, including an in-sandbox OpenClaw query. Onboarding timed out late in policy setup, but install, sandbox creation, sandbox exec, and provider reachability succeeded.

What was validated

  • The PR revision was checked out in an isolated review environment.
  • The local checkout was installed using the repository installer flow as closely as the environment allowed.
  • Adversarial, PR-specific probes were then run against the installed environment and relevant repository context.
  • Diff summary:
 .github/workflows/nightly-e2e.yaml            |  19 +---
 .gitleaksignore                               |   2 +
 Dockerfile                                    |   2 +-
 nemoclaw-blueprint/scripts/axios-proxy-fix.js |  64 +++++++++++
 nemoclaw-blueprint/scripts/http-proxy-fix.js  |  89 ----------------
 scripts/nemoclaw-start.sh                     | 147 ++++----------------------
 src/lib/sandbox-state.ts                      |  26 +----
 test/e2e/lib/sandbox-teardown.sh              |  50 +++++++++
 test/e2e/test-credential-sanitization.sh      |   4 +
 test/e2e/test-deployment-services.sh          |  58 ++++------
 test/e2e/test-diagnostics.sh                  |   4 +-
 test/e2e/test-double-onboard.sh               |  33 +-----
 test/e2e/test-full-e2e.sh                     |   6 +-
 test/e2e/test-hermes-e2e.sh                   |   6 +-
 test/e2e/test-inference-routing.sh            |  91 +++++++---------
 test/e2e/test-messaging-providers.sh          |   6 +-
 test/e2e/test-network-policy.sh               |  62 +++++------
 test/e2e/test-onboard-repair.sh               |  19 +++-
 test/e2e/test-onboard-resume.sh               |  53 +++++-----
 test/e2e/test-rebuild-hermes.sh  
...[truncated]

Passing tests and why they mattered

Passing test 1: Shared teardown helper destroys registered sandboxes and honors KEEP

  • What was tested: The new helper destroys every registered sandbox on EXIT, but skips cleanup when NEMOCLAW_E2E_KEEP_SANDBOX=1.
  • Why it mattered: If false, the PR would still leak sandboxes or would break the advertised local-debug escape hatch.
  • Observed result: Observed destroy calls for alpha and beta on normal exit; with KEEP=1 no destroy calls were emitted.
  • Command: bash /tmp/pr2313-test1.sh
  • Recommended follow-up coverage: Add a shell-level regression/integration test for helper EXIT behavior and KEEP handling, since this is the core new mechanism.

Passing test 2: Onboard repair/resume scripts define repo-local nemoclaw shim before helper load

  • What was tested: The two scripts that use node bin/nemoclaw.js now define a nemoclaw() shim early enough that the helper trap can still destroy sandboxes when no global CLI is on PATH.
  • Why it mattered: If false, repo-local dev runs could still silently leak sandboxes after failures.
  • Observed result: repair lines 66-75 and resume lines 81-90 show the command -v guard plus nemoclaw() shim immediately before sourcing lib/sandbox-teardown.sh.
  • Command: nl -ba test/e2e/test-onboard-repair.sh; nl -ba test/e2e/test-onboard-resume.sh
  • Recommended follow-up coverage: Add a regression test that runs these scripts with PATH stripped and verifies teardown still invokes the repo-local CLI path.

Passing test 3: Network-policy and inference-routing preflight now use unconditional destroy

  • What was tested: The flake fix is real: preflight cleanup no longer depends on nemoclaw list | grep, so not-ready sandboxes are still targeted for destruction.
  • Why it mattered: If false, the nightly flake root cause would remain and shared-runner stale sandboxes could still block onboard.
  • Observed result: network-policy setup_sandbox lines 217-221 and inference-routing lines 211-214 / 439-440 show unconditional destroy commands with comments explaining list-miss behavior.
  • Command: nl -ba test/e2e/test-network-policy.sh; nl -ba test/e2e/test-inference-routing.sh
  • Recommended follow-up coverage: Add targeted regression coverage that simulates a sandbox absent from list output but still destroyable, and verify preflight cleanup still proceeds.

Bottom line

  • Based on the install evidence and adversarial probes, this PR looks reasonable to approve.

@brandonpelfrey
brandonpelfrey merged commit 40df9d8 into main Apr 23, 2026
19 checks passed
@prekshivyas
prekshivyas deleted the prekshi/nightly-e2e-cleanup-robustness branch April 23, 2026 15:46
jyaunches added a commit that referenced this pull request Apr 23, 2026
Merge main into fix/nightly-e2e-repairs-v4, resolving conflicts:
- nightly-e2e.yaml: keep contains(needs.*.result, 'failure') from #2371,
  remove cloud-experimental-e2e from notify-on-failure needs array
- test-snapshot-commands.sh: keep exit-code check from this PR + tolerant
  grep regex from #2314

Address reviewer feedback:
- Drop NEMOCLAW_RECREATE_SANDBOX from deployment-services to avoid
  re-introducing the delete+create race fixed in #2313 (@prekshivyas)
- Update cloud-experimental-e2e disable comment: drop stale Landlock
  mention (fixed in OpenShell#810 v0.0.32+), reference only docs-drift
  (@prekshivyas)
- Extract dump_diagnostics() in test-snapshot-commands.sh to centralize
  duplicate probes from fail() and Phase 2b (CodeRabbit)
@wscurran wscurran added area: ci CI workflows, checks, release automation, or GitHub Actions area: e2e End-to-end tests, nightly failures, or validation infrastructure bug-fix PR fixes a bug or regression chore Build, CI, dependency, or tooling maintenance and removed CI/CD chore Build, CI, dependency, or tooling maintenance labels Jun 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: ci CI workflows, checks, release automation, or GitHub Actions area: e2e End-to-end tests, nightly failures, or validation infrastructure bug-fix PR fixes a bug or regression

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants