Skip to content

fix(rebuild): abort when all state dirs fail to back up (#6972) - #7005

Merged
cv merged 7 commits into
NVIDIA:mainfrom
TonyLuo-NV:worktree-issue-6972-rebuild-backup-guard
Jul 16, 2026
Merged

cv merged 7 commits into
NVIDIA:mainfrom
TonyLuo-NV:worktree-issue-6972-rebuild-backup-guard

Conversation

@TonyLuo-NV

@TonyLuo-NV TonyLuo-NV commented Jul 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes the silent, catastrophic data-loss half of #6972.

In #6972, after a GB10 host reboot the sandbox's mounted .hermes/ state was left with wrong ownership/permissions (dirs drwx------ owned by root/systemd-network, config -r--r--r-- root-owned). On the next rebuild, the sandbox-user SSH tar could not read the mis-owned state directories, so all 14 top-level state dirs failed (memories, sessions, workspace, plans, skills, plugins, ...) while only 3 loose files backed up. The rebuild then proceeded and permanently destroyed every failed directory, warning only:

⚠ Partial backup: 0 dirs and 3 files OK; 14 dirs and 0 files failed
  Rebuild will continue — failed state could not be preserved.

Root cause of the abort gap

backupSandboxStateForRebuild only aborted when the backup preserved nothing at all (!hasAnyBackup). Because 3 loose files were saved, hasAnyBackup was true, so it fell through to the lenient "Rebuild will continue" path — even though every directory of user state was lost. The sibling recreate path (sandbox-backup-on-recreate.ts) already aborts on a partial backup; the rebuild path did not.

Fix

Treat a backup that preserved zero state directories while directories existed and failed (backedUpDirs.length === 0 && failedDirs.length > 0) as data loss:

  • Abort by default, requiring --force (same escape hatch as a fully-empty backup).
  • Under --force, keep any salvageable partial manifest instead of discarding the files that did back up.
  • Emit a diagnostic pointing at the likely wrong-ownership/permissions root cause (e.g. a host reboot remapping the mount's UIDs).

The benign case — most dirs succeed and only a root-owned nested subdir marks a single top-level dir failed — still proceeds unchanged.

Scope note (what this PR does NOT change)

The issue's other symptom — GATEWAY_CONFIG_HASH_MISMATCH blocking recover "even with shields down" — is fail-closed-correct behavior. The Hermes preflight (managed-gateway-control.py::_verify_locked_hermes_hash) infers "sealed" from config.yaml/.env being root-owned + unwritable, then strictly compares against the sealed hash. The reboot's ownership corruption made shields-down config look sealed, so the strict check fired and correctly refused to start a gateway whose config it can't verify. The upstream root cause is the mount-UID remap across reboot (rootless/userns subuid offset), which lives in OpenShell, not NemoClaw — deliberately left out of scope here.

Testing

  • npx vitest run src/lib/actions/sandbox/rebuild-flow-helpers.test.ts → 19 passed (3 new):
    • aborts when every state dir failed even though loose files were saved
    • keeps the salvageable partial manifest under --force
    • still proceeds when at least one state directory was preserved (benign case)
  • typecheck:cli clean for the changed file.

Reproducing the full hardware condition (GB10 reboot + userns UID remap) is out of reach here; the deterministic decision-logic defect is covered by the added unit tests.

Checklist

  • Conventional Commit
  • Signed-off-by present (DCO)
  • Targeted tests added and passing

Signed-off-by: Tony Luo [email protected]

Summary by CodeRabbit

  • Bug Fixes
    • Improved sandbox rebuild backup handling to abort safely when no sandbox state directories are preserved (even if some loose files were captured), unless --force is used.
    • Added more specific abort/error hints for permission/ownership failures and missing-after-extraction scenarios.
    • Refined --force to preserve and use recoverable partial backup results when available, with clearer warnings and fallback behavior.
  • Documentation
    • Updated rebuild workflow and command reference docs to distinguish partial vs total state preservation outcomes and --force behavior.
  • Tests
    • Expanded assertions around --force vs non---force backup failure messaging.

Rebuild only aborted a partial backup when it preserved *nothing* at all.
If a few loose files backed up but every top-level state directory failed —
the exact shape reported in NVIDIA#6972, where a post-reboot mount-ownership
corruption left all `.hermes` state dirs unreadable and only 3 loose files
were saved — the rebuild proceeded and permanently destroyed all 14 state
directories (memories, sessions, workspace, plans, ...) with just a warning.

Treat a backup that preserved zero state directories (while directories
existed and failed) as data loss: abort by default and require `--force`,
matching the sibling recreate path. Under `--force`, keep any salvageable
partial manifest instead of discarding the files that did back up. Emit a
diagnostic pointing at the likely wrong-ownership/permissions root cause.

The benign case — most dirs succeed, one root-owned nested subdir marks a
single top-level dir failed — still proceeds unchanged.

Signed-off-by: Tony Luo <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Jul 16, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@coderabbitai

coderabbitai Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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

Updates sandbox rebuild backup handling to detect catastrophic state-directory failures, provide categorized error messages, preserve partial manifests under --force, and document and test permission, extraction, forced recovery, and partial-success scenarios.

Changes

Sandbox rebuild backup handling

Layer / File(s) Summary
Backup failure decision logic
src/lib/actions/sandbox/rebuild-flow-helpers.ts
Categorizes directory backup failures, aborts when all state directories fail, and returns partial backup manifests when --force is enabled.
Backup failure behavior coverage
src/lib/actions/sandbox/rebuild-flow-helpers.test.ts
Covers permission failures, absent directories after extraction, forced partial recovery, complete failure hints, and continuation after partial backup success.
Rebuild failure behavior documentation
docs/manage-sandboxes/recover-rebuild-sandboxes.mdx, docs/reference/commands.mdx
Documents partial preservation, total backup failure, force-enabled restoration, and registry-only recreation.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant RebuildFlow
  participant SandboxBackup
  participant SandboxRestore
  RebuildFlow->>SandboxBackup: back up sandbox state
  SandboxBackup-->>RebuildFlow: complete, partial, or failed manifest
  RebuildFlow->>SandboxRestore: restore captured artifacts or recreate from registry metadata
Loading

Suggested labels: bug-fix, area: sandbox, UAT

Suggested reviewers: cv

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 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 change: rebuild now aborts when all state directories fail to back up.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@github-actions

github-actions Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

PR Review Advisor — Informational

Advisor assessment: Informational / high confidence
Next action: No advisor follow-up needed.
Findings: 0 blockers · 0 warnings · 0 suggestions
Status: No actionable findings remain in the canonical review ledger.

Model lanes

  • GPT-5.6 Terra (primary): Completed · high confidence · 0 blockers · 0 warnings · 0 suggestions
  • Nemotron 3 Ultra (second opinion): Completed · high confidence · 0 blockers · 1 warning · 0 suggestions
  • Model comparison: normalized findings differ; normalized E2E selections match; Nemotron reported the same number of blockers, 1 more warning, the same number of suggestions.

Nemotron output stays in workflow artifacts and does not change the assessment above.

E2E guidance

Advisory only. E2E / PR Gate selects and runs jobs independently.

Recommended E2E: onboard-repair, onboard-resume, state-backup-restore, upgrade-stale-sandbox

4 optional E2E recommendations
  • sandbox-rebuild
  • rebuild-hermes
  • rebuild-openclaw
  • ubuntu-repo-docker-post-reboot-recovery

Workflow run details

This automated review informs maintainers. Warnings and suggestions do not require a response. A maintainer decides whether to merge.

@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.

🧹 Nitpick comments (1)
src/lib/actions/sandbox/rebuild-flow-helpers.ts (1)

300-310: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Diagnostic message ignores failedDirReasons and always guesses "ownership or permissions".

The BackupResult contract exposes failedDirReasons specifically to distinguish "permission denied" (tar could not read the content) from "absent after extraction" (tar succeeded but the dir never materialized) so operators can tell an ownership problem from a missing dir. This new diagnostic block never reads that map and always prints the "wrong ownership or permissions" hypothesis, even when the real cause is a dir that's simply missing rather than unreadable — potentially sending operators down the wrong troubleshooting path.

🔧 Suggested fix: use failedDirReasons when available
       console.error(
         `  None of the ${dirCount} sandbox state ${dirCount === 1 ? "directory" : "directories"} could be read (only ${fileCount} loose ${fileCount === 1 ? "file was" : "files were"} saved).`,
       );
-      console.error(
-        "  This usually means the sandbox's mounted state has wrong ownership or permissions — for example after a host reboot remapped the mount's UIDs.",
-      );
+      const reasons = backup.failedDirReasons && Object.values(backup.failedDirReasons).join("; ");
+      console.error(
+        reasons
+          ? `  Failure reasons: ${reasons}`
+          : "  This usually means the sandbox's mounted state has wrong ownership or permissions — for example after a host reboot remapped the mount's UIDs.",
+      );
🤖 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/actions/sandbox/rebuild-flow-helpers.ts` around lines 300 - 310,
Update the diagnostic block following the “Failed to back up sandbox state”
message to inspect BackupResult.failedDirReasons for the failed directories.
Distinguish permission-denied/read failures from directories absent after
extraction, and print the corresponding troubleshooting guidance instead of
always attributing the issue to ownership or permissions; retain a sensible
fallback when reasons are unavailable.
🤖 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.

Nitpick comments:
In `@src/lib/actions/sandbox/rebuild-flow-helpers.ts`:
- Around line 300-310: Update the diagnostic block following the “Failed to back
up sandbox state” message to inspect BackupResult.failedDirReasons for the
failed directories. Distinguish permission-denied/read failures from directories
absent after extraction, and print the corresponding troubleshooting guidance
instead of always attributing the issue to ownership or permissions; retain a
sensible fallback when reasons are unavailable.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 2a7f04c6-cadc-45d0-954f-7d55b745b184

📥 Commits

Reviewing files that changed from the base of the PR and between c1bda80 and 0e7e206.

📒 Files selected for processing (2)
  • src/lib/actions/sandbox/rebuild-flow-helpers.test.ts
  • src/lib/actions/sandbox/rebuild-flow-helpers.ts

Address CodeRabbit review: the new all-state-dirs-failed guard always
attributed the failure to wrong ownership/permissions. Use the existing
BackupResult.failedDirReasons contract to distinguish "permission denied"
(ownership/permissions hypothesis) from "absent after extraction" (unstable
or disappearing mount), and surface the per-directory cause on the Failed
line via formatFailedBackupItems.

Signed-off-by: Tony Luo <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@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

🤖 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/actions/sandbox/rebuild-flow-helpers.test.ts`:
- Around line 349-361: Update the backupSpy fixture in the test “aborts with an
unstable-mount hint when every dir was absent after extraction (`#6972`)” so its
manifest matches the failed result: use manifest: null for this non-force abort
case, or provide a manifest consistent with backedUpDirs: [] and the listed
files.
🪄 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: e7d05308-00b5-4843-bfee-30ccb8e2046c

📥 Commits

Reviewing files that changed from the base of the PR and between 0e7e206 and 0f4d0d1.

📒 Files selected for processing (2)
  • src/lib/actions/sandbox/rebuild-flow-helpers.test.ts
  • src/lib/actions/sandbox/rebuild-flow-helpers.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/lib/actions/sandbox/rebuild-flow-helpers.ts

@TonyLuo-NV
TonyLuo-NV requested a review from cv July 16, 2026 08:41
@TonyLuo-NV

Copy link
Copy Markdown
Collaborator Author

CI is green on all 43 contributor-controllable checks (build/typecheck, all cli-test-shards, plugin/installer tests, CodeQL, ShellCheck, guardrails, DCO, commit-lint, CodeRabbit — all resolved, 0 unresolved comments — plus both PR review advisors). A transient cli-test-shard flake (unrelated 5000ms timeouts in dashboard-port/nim) was cleared via rerun.

The sole remaining non-green check is E2E / PR Gate Coordination: this fork PR touches backup/onboard/state code, so it selected credentialed E2E jobs (state-backup-restore, onboard-repair, onboard-resume, upgrade-stale-sandbox). No fork code received secrets. Controller run 29483970591 is waiting on the approve-credentialed-e2e-skip-for-fork-pr environment, whose only reviewer is @cv (current_user_can_approve: false for the PR author). @cv — please approve the credentialed-E2E-skip (Review deployments) to clear the last check.

TonyLuo-NV and others added 2 commits July 16, 2026 17:12
Address CodeRabbit: the non-force abort tests reused a manifest claiming
`.state` was backed up, contradicting backedUpDirs: []. Those paths bail
before the manifest is read, so use manifest: null to keep the fixtures
self-consistent.

Signed-off-by: Tony Luo <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@TonyLuo-NV
TonyLuo-NV marked this pull request as ready for review July 16, 2026 09:34

@cv cv left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approved at exact head 0e03fbe on base b528371. Accepted #6972 scope is satisfied: rebuild now fails closed when every state directory is lost, preserves salvageable loose files only under explicit --force, and documents the recovery contract accurately. Focused tests pass 20/20, conditional scan and normal hooks pass, docs build passes, current CI is green, DCO is present, all 7 commits are GitHub Verified, CodeRabbit has no unresolved thread, canonical advisor ledger is 0/0/0, and the nine-category security review passes. Fork credentialed E2E was intentionally not run; protected-environment approval recorded the audited exact-head skip and no fork code received repository secrets.

@cv
cv merged commit 032d7fa into NVIDIA:main Jul 16, 2026
50 checks passed
@TonyLuo-NV TonyLuo-NV linked an issue Jul 17, 2026 that may be closed by this pull request
2 tasks done
@cjagwani cjagwani mentioned this pull request Jul 17, 2026
10 of 21 tasks
cv pushed a commit that referenced this pull request Jul 17, 2026
<!-- markdownlint-disable MD041 -->
## Summary

Add the canonical dated changelog entry required before the v0.0.85
release plan can be generated.
The entry summarizes the user-visible OpenShell, DGX Station, inference,
MCP, onboarding, and recovery changes merged since v0.0.84 and links to
their owning guides.

## Changes

- Add `docs/changelog/2026-07-16.mdx` with the exact `## v0.0.85`
heading, parser-safe SPDX comment, release summary, and detailed
bullets.
- Link every documented theme to its most specific published OpenClaw
guide routes.
- Reconcile the release entry with these merged source PRs:
- #6726 -> `docs/changelog/2026-07-16.mdx`: Document the supported
OpenShell v0.0.85 upgrade, immutable consumed artifacts, multiline exec,
credential rewrite diagnostics, and child-process TLS boundary.
- #6986 -> `docs/changelog/2026-07-16.mdx`: Document managed MCP
behavior shared across supported agents.
- #6991 and #7045 -> `docs/changelog/2026-07-16.mdx`: Document qualified
DGX Station host preparation and the interactive-terminal boundary for
`--station-deepseek`.
- #6992, #7001, #7006, and #7044 -> `docs/changelog/2026-07-16.mdx`:
Document managed-model reasoning behavior, safe inference route
mutation, and verified vLLM served aliases.
- #6865, #7010, and #7028 -> `docs/changelog/2026-07-16.mdx`: Document
onboarding DNS recovery, explicit notice acceptance, and upgrades with
user-local OpenShell.
- #7005, #7021, #7029, and #7049 -> `docs/changelog/2026-07-16.mdx`:
Document rebuild backup safety, no-dashboard state, managed gateway
discovery, and Hermes shields topology checks.

## Type of Change

- [ ] Code change (feature, bug fix, or refactor)
- [ ] Code change with doc updates
- [x] Doc only (prose changes, no code sample modifications)
- [ ] Doc only (includes code sample changes)

## Quality Gates

- [ ] Tests added or updated for changed behavior
- [x] Existing tests cover changed behavior — justification:
`test/changelog-docs.test.ts` validates the canonical heading,
parser-safe SPDX comment, and detailed entry structure; the docs build
validates published routes.
- [ ] Tests not applicable — justification:
- [x] Docs updated for user-facing behavior changes
- [ ] Docs not applicable — justification:
- [ ] Sensitive paths changed (security, policy, credentials, preflight,
onboarding, inference, runner, sandbox, or messaging)
- [ ] Sensitive-path review completed or maintainer-approved waiver
recorded — reviewer/approval link/justification:
- [ ] Non-success, skipped, or missing CI check accepted by maintainer —
check name, approval link, and follow-up issue:

## Verification

- [x] PR description includes a `Signed-off-by:` line and every commit
appears as `Verified` in GitHub
- [x] Normal `pre-commit`, `commit-msg`, and `pre-push` hooks passed, or
`npm run check:diff` passed when hooks were skipped or unavailable
- [x] Targeted behavior tests pass for the current change set, or tests
are marked not applicable above — `npx vitest run
test/changelog-docs.test.ts` passed 6/6.
- [ ] Applicable broad gate passed — `npm test` for broad
runtime/test-harness changes; `npm run check` for repo-wide
validation/coverage changes — not applicable to this doc-only entry.
- [x] Quality Gates section completed with required justifications or
waivers
- [x] No secrets, API keys, or credentials committed
- [ ] `npm run docs` builds without warnings (doc changes only) — passed
with 0 errors and 2 pre-existing Fern warnings.
- [x] Doc pages follow the [style
guide](https://github.com/NVIDIA/NemoClaw/blob/main/docs/CONTRIBUTING.md)
(doc changes only)
- [x] New doc pages include SPDX header and frontmatter (new pages only)
— native changelog entries use the required parser-safe MDX SPDX comment
instead of frontmatter.

---
Signed-off-by: Charan Jagwani <[email protected]>


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Documentation**
  * Added release notes for NemoClaw v0.0.85.
* Documented improvements to compatibility, credential handling, setup
validation, recovery workflows, endpoint configuration, gateway
discovery, and runtime validation.
  * Added links to relevant user-guide sections.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Signed-off-by: Charan Jagwani <[email protected]>
@wscurran wscurran added area: sandbox OpenShell sandbox lifecycle, runtime, config, or recovery bug-fix PR fixes a bug or regression labels Jul 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: sandbox OpenShell sandbox lifecycle, runtime, config, or recovery bug-fix PR fixes a bug or regression

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[hermes] Impossible to start the gateway after a reboot

3 participants