diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index 31fdfed9768..ec976fc495d 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -316,6 +316,15 @@ If `rebuild` stops after recording the journal, rerun the command with the same - It continues deletion when the live sandbox still has the journaled source identity. - It continues creation when the recorded OpenShell gateway explicitly reports the source sandbox as absent. - It accepts an existing replacement only when its live identity and sandbox registry generation match the journal. +- It starts a new replacement when the journaled replacement provably never took effect. + +NemoClaw treats a journaled replacement as void when the sandbox registry row and the live same-name sandbox report the same OpenShell identity on the journaled gateway, and that identity is not the journaled replacement. +A registry row or a live sandbox on any other gateway leaves the journal in place, because that journal may still own an unregistered replacement on its own gateway. +The rerun atomically replaces the void journal with a fresh journal against that live source, without leaving an unjournaled interval. It then reports `Replaced the void replacement journal for ''; its source sandbox is registered and live.` +A journal whose replacement never took therefore stops blocking `rebuild` for the rest of the session. + +The journal binds the durable source registry row, so it does not resume after a command that rewrites that row. +Messaging channel state is exempt: `channels add`, `channels stop`, `channels start`, and `channels remove` rewrite the recorded messaging plan, and the journal ignores that field. Do not retry rebuild when a retained policy handoff contains a literal credential. Recover any required data from the backup before deletion, and keep the backup and handoff until that recovery is complete. Restore or select the recorded gateway and confirm `openshell status` is healthy. Only then use the ordinary fail-closed destroy flow and confirm OpenShell reports the sandbox deleted: diff --git a/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts b/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts index 3c00260e265..16b72c686c0 100644 --- a/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts @@ -96,8 +96,7 @@ function stubRecreateJournal(): RebuildRecreateJournal { }, targetGeneration: "generation-1", targetIntentFingerprint: "intent-1", - markDeleting: vi.fn(), - observeSourceForDelete: vi.fn(() => "source" as const), + beginDelete: vi.fn(() => "source" as const), confirmDeleted: vi.fn(), completeAcceptedTarget: vi.fn(), }; @@ -961,7 +960,7 @@ describe("rebuild destroy phase", () => { ["sandbox", "get", "-g", "nemoclaw", "alpha"], expect.objectContaining({ timeout: expect.any(Number) }), ); - expect(recreateJournal.markDeleting).toHaveBeenCalledOnce(); + expect(recreateJournal.beginDelete).toHaveBeenCalledOnce(); expect(recreateJournal.confirmDeleted).toHaveBeenCalledOnce(); }); @@ -972,8 +971,9 @@ describe("rebuild destroy phase", () => { order.push("forward:stop"); return true; }); - vi.mocked(recreateJournal.markDeleting).mockImplementation(() => { + vi.mocked(recreateJournal.beginDelete).mockImplementation(() => { order.push("journal:deleting"); + return "source"; }); mocks.runOpenshell.mockImplementation((args: string[]) => { const deleting = args[1] === "delete"; @@ -997,17 +997,12 @@ describe("rebuild destroy phase", () => { onDeleted: vi.fn(), }); - expect(order).toEqual([ - "forward:stop", - "journal:deleting", - "openshell:delete", - "forward:stop", - ]); + expect(order).toEqual(["forward:stop", "journal:deleting", "openshell:delete", "forward:stop"]); }); it("reattaches MCP providers when the delete boundary cannot be journaled (#7734)", async () => { const recreateJournal = stubRecreateJournal(); - vi.mocked(recreateJournal.markDeleting).mockImplementation(() => { + vi.mocked(recreateJournal.beginDelete).mockImplementation(() => { throw new Error("session store is unwritable"); }); mocks.prepareMcpForRebuild.mockResolvedValue({ diff --git a/src/lib/actions/sandbox/rebuild-destroy-phase.ts b/src/lib/actions/sandbox/rebuild-destroy-phase.ts index b8cf4060ce5..befb7bc0eea 100644 --- a/src/lib/actions/sandbox/rebuild-destroy-phase.ts +++ b/src/lib/actions/sandbox/rebuild-destroy-phase.ts @@ -407,8 +407,7 @@ export async function runRebuildDestroyPhase( // running sandbox is left without its MCP wiring. let sourcePresence: RebuildRecreateSourcePresence; try { - sourcePresence = recreateJournal.observeSourceForDelete(); - recreateJournal.markDeleting(); + sourcePresence = recreateJournal.beginDelete(); } catch (error) { const mcpRecoveryFailure = await reattachMcpAfterDeleteFailure( sandboxName, diff --git a/src/lib/actions/sandbox/rebuild-hermes-accepted-target.test.ts b/src/lib/actions/sandbox/rebuild-hermes-accepted-target.test.ts index b30525b732e..2f882699155 100644 --- a/src/lib/actions/sandbox/rebuild-hermes-accepted-target.test.ts +++ b/src/lib/actions/sandbox/rebuild-hermes-accepted-target.test.ts @@ -184,8 +184,7 @@ describe("Hermes accepted replacement recovery", () => { targetGeneration: "generation-1", targetIntentFingerprint: "intent-1", completeAcceptedTarget, - markDeleting: vi.fn(), - observeSourceForDelete: vi.fn(), + beginDelete: vi.fn(), confirmDeleted: vi.fn(), }); }); diff --git a/src/lib/actions/sandbox/rebuild-recreate-journal.test.ts b/src/lib/actions/sandbox/rebuild-recreate-journal.test.ts index 047df339340..e0db2c06f9c 100644 --- a/src/lib/actions/sandbox/rebuild-recreate-journal.test.ts +++ b/src/lib/actions/sandbox/rebuild-recreate-journal.test.ts @@ -24,6 +24,7 @@ vi.mock("../../onboard/gateway-teardown-authority", async (importOriginal) => ({ resolveGatewayRebuildAuthority: mocks.resolveGatewayRebuildAuthority, })); +import { fingerprintSandboxRecreateValue } from "../../onboard/sandbox-recreate-transaction"; import type { CheckpointGatewayAuthority } from "../../state/onboard-checkpoint-types"; import type { Session } from "../../state/onboard-session"; import * as onboardSession from "../../state/onboard-session"; @@ -265,6 +266,9 @@ describe("rebuild replacement journal", () => { session = mutator(session) ?? session; return session; }); + vi.spyOn(onboardSession, "compareAndSwapSession").mockImplementation((matches, mutator) => { + return matches(session) ? ((session = mutator(session) ?? session), "updated") : "mismatch"; + }); vi.spyOn(registry, "getSandbox").mockReturnValue({ name: "alpha", agent: "langchain-deepagents-code", @@ -279,9 +283,9 @@ describe("rebuild replacement journal", () => { vi.restoreAllMocks(); }); - function open() { + function open(target = NON_DEFAULT_TARGET) { return openRebuildRecreateJournal({ - target: NON_DEFAULT_TARGET, + target, expectedGatewayAuthority: STANDALONE_GATEWAY_AUTHORITY, agentName: "langchain-deepagents-code", targetIntentFingerprint: fingerprintRebuildRecreateTargetIntent(recreateOptions), @@ -370,10 +374,80 @@ describe("rebuild replacement journal", () => { expect(session.checkpoint?.sandboxRecreate?.sourceLiveIdentityFingerprint).toBeNull(); }); + it("starts a fresh journal when the stranded one no longer owns a replacement (#10473)", () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "alpha", + agent: "langchain-deepagents-code", + gatewayName: "nemoclaw-9090", + gatewayPort: 9090, + lifecycleGeneration: "44444444-4444-4444-8444-444444444444", + lifecycleLiveIdentityFingerprint: fingerprintSandboxRecreateValue(SANDBOX_ID), + } as registry.SandboxEntry); + const stranded = open(); + onboardSession.updateSession((current) => { + const checkpoint = current.checkpoint as NonNullable; + const transaction = checkpoint.sandboxRecreate as NonNullable< + typeof checkpoint.sandboxRecreate + >; + current.checkpoint = { + ...checkpoint, + sandboxRecreate: { ...transaction, phase: "deleted" }, + }; + return current; + }); + expect(session.checkpoint?.sandboxRecreate).toMatchObject({ + id: stranded.id, + phase: "deleted", + }); + + const restarted = open(); + + expect(restarted.id).not.toBe(stranded.id); + expect(restarted.acceptedTarget).toBe(false); + expect(restarted.sourceConfirmedAbsent).toBe(false); + expect(session.checkpoint?.sandboxRecreate).toMatchObject({ + id: restarted.id, + phase: "planned", + revision: 0, + }); + }); + + it("keeps a stranded journal when the matching source is on another gateway (#10473)", () => { + mocks.captureOpenshell.mockReturnValue(absentProbe()); + const stranded = open(); + expect(session.checkpoint?.sandboxRecreate).toMatchObject({ + id: stranded.id, + gatewayName: "nemoclaw-9090", + phase: "deleted", + }); + + // Same sandbox name and same live identity, but the row and the probe now + // describe a sandbox on a different gateway. The journal may still own an + // unregistered replacement on nemoclaw-9090, so it must survive. + mocks.captureOpenshell.mockReturnValue(livePresentProbe()); + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "alpha", + agent: "langchain-deepagents-code", + gatewayName: "nemoclaw-7070", + gatewayPort: 7070, + lifecycleGeneration: "44444444-4444-4444-8444-444444444444", + lifecycleLiveIdentityFingerprint: fingerprintSandboxRecreateValue(SANDBOX_ID), + } as registry.SandboxEntry); + + expect(() => + open({ sandboxName: "alpha", gatewayName: "nemoclaw-7070", gatewayPort: 7070 }), + ).toThrow(/different recreate transaction in progress/); + expect(session.checkpoint?.sandboxRecreate).toMatchObject({ + id: stranded.id, + gatewayName: "nemoclaw-9090", + phase: "deleted", + }); + }); + it("records the delete boundary before and after the destructive command", () => { const journal = open(); - journal.markDeleting(); + journal.beginDelete(); expect(session.checkpoint?.sandboxRecreate?.phase).toBe("deleting"); mocks.captureOpenshell.mockReturnValue(absentProbe()); @@ -385,14 +459,14 @@ describe("rebuild replacement journal", () => { mocks.captureOpenshell.mockReturnValue(absentProbe()); const journal = open(); - journal.markDeleting(); + journal.beginDelete(); expect(session.checkpoint?.sandboxRecreate?.phase).toBe("deleted"); }); it("stops before the next mutation when the source outlives its delete", () => { const journal = open(); - journal.markDeleting(); + journal.beginDelete(); expect(() => journal.confirmDeleted()).toThrow( /OpenShell still reports the journaled source after delete/, diff --git a/src/lib/actions/sandbox/rebuild-recreate-journal.ts b/src/lib/actions/sandbox/rebuild-recreate-journal.ts index 9368aa2f8d4..b34ce2f7aea 100644 --- a/src/lib/actions/sandbox/rebuild-recreate-journal.ts +++ b/src/lib/actions/sandbox/rebuild-recreate-journal.ts @@ -24,16 +24,15 @@ import { } from "../../onboard/sandbox-recreate-probe"; import { advanceSandboxRecreateTransaction, - beginSandboxRecreateTransaction, + beginSandboxRecreateDelete, clearCompletedSandboxRecreateTransaction, fingerprintSandboxRecreateValue, - planSandboxRecreateRecovery, + ownSandboxRecreateTransaction, type SandboxRecreateSourcePresence, sandboxRecreatePhaseReached, } from "../../onboard/sandbox-recreate-transaction"; import { isValidName } from "../../sandbox-name-contract"; import { decisionSelected } from "../../state/onboard-checkpoint-decision"; -import { deriveCheckpointFromSession } from "../../state/onboard-checkpoint-migrate"; import type { CheckpointGatewayAuthority, CheckpointSandboxRecreatePhase, @@ -534,8 +533,7 @@ export interface RebuildRecreateJournal { readonly gatewayAuthority: CheckpointGatewayAuthority; readonly targetGeneration: string; readonly targetIntentFingerprint: string; - markDeleting(): void; - observeSourceForDelete(): RebuildRecreateSourcePresence; + beginDelete(): RebuildRecreateSourcePresence; confirmDeleted(): void; completeAcceptedTarget(): void; } @@ -641,56 +639,60 @@ export function openRebuildRecreateJournal( throw error; } const gatewayAuthority = checkpointGatewayAuthority(authority); - const sourceEntry = registry.getSandbox(target.sandboxName); - const observation = observe(target); - const active = onboardSession.loadSession()?.checkpoint?.sandboxRecreate ?? null; - const recovery = active - ? planSandboxRecreateRecovery(active, observation, sourceEntry) - : { action: "continue_delete" as const }; - if (recovery.action === "reject") { - throw new Error( - `Cannot resume sandbox '${target.sandboxName}' replacement: ${recovery.reason}.`, - ); - } - // A registered, ready same-name sandbox carrying the journaled target - // generation and identity is the replacement this rebuild already proved. - // The caller must retire the transaction instead of deleting it again. - const acceptedTarget = recovery.action === "accept_target"; - - const session = onboardSession.updateSession((current) => { - const checkpoint = current.checkpoint ?? deriveCheckpointFromSession(current); - current.checkpoint = { + const owned = ownSandboxRecreateTransaction({ + sessionStore: { + loadSession: onboardSession.loadSession, + updateSession: onboardSession.updateSession, + compareAndSwapSession: onboardSession.compareAndSwapSession, + }, + sandboxName: target.sandboxName, + gatewayName: target.gatewayName, + gatewayPort: target.gatewayPort, + targetIntentFingerprint, + readRegistryEntry: () => registry.getSandbox(target.sandboxName), + observe: () => observe(target), + decorateCheckpoint: (current, checkpoint, now) => ({ ...checkpoint, machineState: current.machine.state, - updatedAt: new Date().toISOString(), + updatedAt: now, sandboxIdentity: decisionSelected({ name: target.sandboxName, agent: agentName }), gatewayAuthority: decisionSelected(gatewayAuthority), - }; - beginSandboxRecreateTransaction(current, { - sandboxName: target.sandboxName, - gatewayName: target.gatewayName, - gatewayPort: target.gatewayPort, - sourceEntry, - observation, - targetIntentFingerprint, - }); - return current; + }), }); - - const transaction = session.checkpoint?.sandboxRecreate; - if (!transaction) { - throw new Error( - `Sandbox '${target.sandboxName}' replacement journal could not be recorded before deletion.`, + const { session, transaction, recovery } = owned; + if (owned.replacedTransactionId) { + log( + `Replaced void journal ${owned.replacedTransactionId} with ${transaction.id} for '${target.sandboxName}'; its source sandbox is registered and live`, + ); + console.log( + ` Replaced the void replacement journal for '${target.sandboxName}'; its source sandbox is registered and live.`, ); } + const acceptedTarget = recovery.action === "accept_target"; log( `Journaled replacement ${transaction.id} for '${target.sandboxName}' on ${target.gatewayName}:${String(target.gatewayPort)} at phase '${transaction.phase}'`, ); + const openingSessionId = session.sessionId; + let currentTransaction = transaction; let phase: CheckpointSandboxRecreatePhase = transaction.phase; + const revalidateGatewayAuthority = (): void => { + const currentAuthority = resolveGatewayRebuildAuthority({ + gatewayName: target.gatewayName, + gatewayPort: target.gatewayPort, + }); + if (!sameGatewayOwner(authority, currentAuthority)) { + throw new GatewayAuthorityError( + "Gateway lifecycle authority changed after the recreate journal was recorded " + + `(${describeGatewayOwnerForError(authority)} -> ${describeGatewayOwnerForError(currentAuthority)}). ` + + "Retry the rebuild; the current run will not delete the source sandbox.", + ); + } + }; const advance = (next: CheckpointSandboxRecreatePhase): void => { onboardSession.updateSession((current) => { - phase = advanceSandboxRecreateTransaction(current, transaction.id, next).phase; + currentTransaction = advanceSandboxRecreateTransaction(current, transaction.id, next); + phase = currentTransaction.phase; return current; }); }; @@ -702,22 +704,23 @@ export function openRebuildRecreateJournal( gatewayAuthority, targetGeneration: transaction.targetGeneration, targetIntentFingerprint: transaction.targetIntentFingerprint, - markDeleting: () => { - if (sandboxRecreatePhaseReached(phase, "deleted")) return; - advance("deleting"); - }, - observeSourceForDelete: () => { - const current = observe(target); - if (current.state === "missing") return "missing"; - if ( - !transaction.sourceLiveIdentityFingerprint || - current.liveIdentityFingerprint !== transaction.sourceLiveIdentityFingerprint - ) { - throw new Error( - `Cannot delete sandbox '${target.sandboxName}': the live same-name sandbox is not the journaled source.`, - ); - } - return "source"; + beginDelete: () => { + const begun = beginSandboxRecreateDelete({ + sessionStore: { + loadSession: onboardSession.loadSession, + updateSession: onboardSession.updateSession, + compareAndSwapSession: onboardSession.compareAndSwapSession, + }, + openingSessionId, + expectedTransaction: currentTransaction, + targetIntentFingerprint, + revalidateGatewayAuthority, + readRegistryEntry: () => registry.getSandbox(target.sandboxName), + observe: () => observe(target), + }); + currentTransaction = begun.transaction; + phase = currentTransaction.phase; + return begun.sourcePresence; }, confirmDeleted: () => { if (observe(target).state !== "missing") { diff --git a/src/lib/actions/sandbox/rebuild-recreate-observability.test.ts b/src/lib/actions/sandbox/rebuild-recreate-observability.test.ts index 12af8e28a6e..461b89b9293 100644 --- a/src/lib/actions/sandbox/rebuild-recreate-observability.test.ts +++ b/src/lib/actions/sandbox/rebuild-recreate-observability.test.ts @@ -160,8 +160,7 @@ function makeInput(overrides: Partial = {}): RebuildR gatewayAuthority: STANDALONE_GATEWAY_AUTHORITY, targetGeneration: "generation-1", targetIntentFingerprint: "intent-1", - markDeleting: vi.fn(), - observeSourceForDelete: vi.fn(() => "source" as const), + beginDelete: vi.fn(() => "source" as const), confirmDeleted: vi.fn(), completeAcceptedTarget: vi.fn(), }, diff --git a/src/lib/actions/sandbox/rebuild-recreate-reasoning.test.ts b/src/lib/actions/sandbox/rebuild-recreate-reasoning.test.ts index 917150d9d41..72c5744f237 100644 --- a/src/lib/actions/sandbox/rebuild-recreate-reasoning.test.ts +++ b/src/lib/actions/sandbox/rebuild-recreate-reasoning.test.ts @@ -94,8 +94,7 @@ const recreateJournal: RebuildRecreateJournal = { gatewayAuthority: GATEWAY_AUTHORITY, targetGeneration: "22222222-2222-4222-8222-222222222222", targetIntentFingerprint: "rebuild-reasoning-target", - markDeleting: vi.fn(), - observeSourceForDelete: vi.fn((): "missing" => "missing"), + beginDelete: vi.fn((): "missing" => "missing"), confirmDeleted: vi.fn(), completeAcceptedTarget: vi.fn(), }; diff --git a/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts b/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts index 27bfeb1b704..bd560690dd4 100644 --- a/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts +++ b/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts @@ -178,6 +178,12 @@ describe("rebuild resume snapshot repair", () => { vi.spyOn(agentRuntime, "getAgentDisplayName").mockReturnValue("OpenClaw"), vi.spyOn(onboardSession, "loadSession").mockImplementation(loadSession), vi.spyOn(onboardSession, "updateSession").mockImplementation(updateSession), + vi.spyOn(onboardSession, "compareAndSwapSession").mockImplementation((matches, mutator) => { + const current = cloneSession(session); + return matches(current) + ? ((session = cloneSession(mutator(current) ?? current)), "updated") + : "mismatch"; + }), vi.spyOn(onboardSession, "acquireOnboardLock").mockReturnValue({ acquired: true, lockFile: "/tmp/nemoclaw-onboard.lock", diff --git a/src/lib/actions/sandbox/rebuild-shields-finally.test.ts b/src/lib/actions/sandbox/rebuild-shields-finally.test.ts index 9c446f9b35b..56617c0fb82 100644 --- a/src/lib/actions/sandbox/rebuild-shields-finally.test.ts +++ b/src/lib/actions/sandbox/rebuild-shields-finally.test.ts @@ -116,7 +116,7 @@ describe("rebuild shields relock guard", () => { gatewayAuthority, targetGeneration: "generation-1", targetIntentFingerprint: "intent-1", - markDeleting: vi.fn(), + beginDelete: vi.fn(() => "source" as const), confirmDeleted: vi.fn(), }); }); @@ -187,9 +187,9 @@ describe("rebuild shields relock guard", () => { phaseMocks.runDestroy.mockResolvedValue({ entries: [], removalReceipt: null }); phaseMocks.runRecreate.mockRejectedValue(new Error("replacement creation failed")); - await expect( - rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).rejects.toThrow("replacement creation failed"); + await expect(rebuildSandbox("alpha", ["--yes"], { throwOnError: true })).rejects.toThrow( + "replacement creation failed", + ); expect(phaseMocks.runRecreate).toHaveBeenCalledOnce(); expect(phaseMocks.cleanupPolicySource).toHaveBeenCalledExactlyOnceWith( diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index ef87afb5f05..fbc29a993fe 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -428,11 +428,7 @@ const promptValidatedSandboxName = sandboxAgent.createPromptValidatedSandboxName exit: process.exit, }); const modelRouter: typeof import("./onboard/model-router") = require("./onboard/model-router"); -const { - isRoutedInferenceProvider, - loadBlueprintProfile, - reconcileModelRouter, -} = modelRouter; +const { isRoutedInferenceProvider, loadBlueprintProfile, reconcileModelRouter } = modelRouter; const routedInference: typeof import("./onboard/routed-inference") = require("./onboard/routed-inference"); const { OnboardRuntimeBoundary, @@ -1505,17 +1501,13 @@ const gatewayRecovery = createGatewayRecoveryOrchestration({ startGatewayWithOptions: gatewayStart.startGatewayWithOptions, }); -const { - recoverGatewayRuntime, - startDockerDriverGateway, - startGateway, - startGatewayForRecovery, -} = createGatewayLifecycleApplication({ - dockerDriverStart: dockerDriverGatewayStart, - recovery: gatewayRecovery, - registration: gatewayRegistration, - start: gatewayStart, -}); +const { recoverGatewayRuntime, startDockerDriverGateway, startGateway, startGatewayForRecovery } = + createGatewayLifecycleApplication({ + dockerDriverStart: dockerDriverGatewayStart, + recovery: gatewayRecovery, + registration: gatewayRegistration, + start: gatewayStart, + }); const { getSandboxRuntimeRegistryFields, hasSandboxGpuDrift, updateReusedSandboxMetadata } = sandboxRegistryMetadata.createSandboxRegistryMetadataHelpers({ @@ -3180,7 +3172,11 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { agentSupportsWebSearch, agentSupportsWebSearchProvider, ...{ note, cliName }, - updateSession: onboardSession.updateSession, + ...{ + loadSession: onboardSession.loadSession, + updateSession: onboardSession.updateSession, + compareAndSwapSession: onboardSession.compareAndSwapSession, + }, getStoredMessagingChannelConfig, hydrateMessagingChannelConfig, messagingChannelConfigsEqual, diff --git a/src/lib/onboard/machine/core-flow-phases.test.ts b/src/lib/onboard/machine/core-flow-phases.test.ts index 42d9eedef27..0e8158bc081 100644 --- a/src/lib/onboard/machine/core-flow-phases.test.ts +++ b/src/lib/onboard/machine/core-flow-phases.test.ts @@ -239,7 +239,9 @@ function createPhases( note: vi.fn(), cliName: () => "nemoclaw", + loadSession: () => createSession(), updateSession: vi.fn((mutator) => mutator(createSession()) ?? createSession()), + compareAndSwapSession: vi.fn(() => "mismatch" as const), getStoredMessagingChannelConfig: () => null, hydrateMessagingChannelConfig: (config) => config, messagingChannelConfigsEqual: () => true, @@ -645,9 +647,7 @@ describe("core onboard flow phases", () => { resolved?: { policy?: { basePolicyPath?: string } }; }; const runVerifiedEffects = args[16] as - | ((context: { - revalidateSandboxIdentity: (operation: string) => void; - }) => Promise) + | ((context: { revalidateSandboxIdentity: (operation: string) => void }) => Promise) | undefined; expect(createIntent).toMatchObject({ resolved: { policy: { basePolicyPath: "/repo/policy.yaml" } }, diff --git a/src/lib/onboard/machine/handlers/sandbox-rebuild-web-search-reuse.test.ts b/src/lib/onboard/machine/handlers/sandbox-rebuild-web-search-reuse.test.ts index 11784bb243c..20785c48fcc 100644 --- a/src/lib/onboard/machine/handlers/sandbox-rebuild-web-search-reuse.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-rebuild-web-search-reuse.test.ts @@ -10,9 +10,11 @@ import { type CheckpointSandboxRecreateTransaction, type OnboardCheckpoint, } from "../../../state/onboard-checkpoint-types"; +import type { SandboxEntry } from "../../../state/registry"; import { createSession, type Session } from "../../../state/onboard-session"; import { detectMessagingChannelsFromEnv } from "../../messaging-channel-setup"; import { handleSandboxState } from "./sandbox"; +import { fingerprintSandboxRegistryEntry } from "../../sandbox-recreate-transaction"; import { baseOptions, createDeps } from "./sandbox-test-fixtures"; vi.mock("../../messaging-channel-setup", () => ({ @@ -26,6 +28,22 @@ const PROVIDER_NAME = `${SANDBOX_NAME}-brave-search`; const AT = "2026-01-01T00:00:00.000Z"; const TARGET_INTENT_FINGERPRINT = "target-intent"; +function sourceRegistryEntry(): SandboxEntry { + return { + name: SANDBOX_NAME, + provider: "provider", + model: "model", + endpointUrl: null, + preferredInferenceApi: "openai-completions", + gatewayName: "nemoclaw", + gatewayPort: 8080, + webSearchEnabled: false, + toolDisclosure: "progressive", + fromDockerfile: null, + hermesAuthMethod: null, + }; +} + function recreateTransaction( overrides: Partial = {}, ): CheckpointSandboxRecreateTransaction { @@ -36,7 +54,7 @@ function recreateTransaction( sandboxName: SANDBOX_NAME, gatewayName: "nemoclaw", gatewayPort: 8080, - sourceRegistryFingerprint: "source-registry", + sourceRegistryFingerprint: fingerprintSandboxRegistryEntry(sourceRegistryEntry()), sourceLiveIdentityFingerprint: null, sourceWorkload: null, targetIntentFingerprint: TARGET_INTENT_FINGERPRINT, @@ -117,6 +135,7 @@ function recreateWebSearch( const { deps, calls } = createDeps( { getSandboxReuseState: () => "missing", + getSandboxRegistryEntry: sourceRegistryEntry, providerMatchesGatewayCredential: overrides.providerMatchesGatewayCredential ?? ((name, type, credentialEnv) => @@ -152,16 +171,16 @@ describe("rebuild web-search credential reuse", () => { expect(calls.createSandbox).toHaveBeenCalledTimes(1); }); - it.each([ - "planned", - "deleting", - ])("revalidates while the recreate journal is still at phase %s", async (phase) => { - const { run, calls } = recreateWebSearch(rebuiltSession(recreateTransaction({ phase }))); + it.each(["planned", "deleting"])( + "revalidates while the recreate journal is still at phase %s", + async (phase) => { + const { run, calls } = recreateWebSearch(rebuiltSession(recreateTransaction({ phase }))); - await run; + await run; - expect(calls.validateBrave).toHaveBeenCalledTimes(1); - }); + expect(calls.validateBrave).toHaveBeenCalledTimes(1); + }, + ); it("never reuses on a recreate journal that names a different sandbox", async () => { const { run, calls } = recreateWebSearch( diff --git a/src/lib/onboard/machine/handlers/sandbox-recreate-journal.test.ts b/src/lib/onboard/machine/handlers/sandbox-recreate-journal.test.ts index c7506fb2264..45b71bac87c 100644 --- a/src/lib/onboard/machine/handlers/sandbox-recreate-journal.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-recreate-journal.test.ts @@ -150,14 +150,7 @@ it("journals not-ready repair on the selected non-default gateway (#6492)", asyn ); expect(calls.note).toHaveBeenCalledWith(expect.stringContaining("run 'nemohermes gc'")); const orderedPhases = phases.filter((phase, index) => index === 0 || phase !== phases[index - 1]); - expect(orderedPhases).toEqual([ - null, - "planned", - "created", - "registry_committing", - "completed", - null, - ]); + expect(orderedPhases).toEqual([null, "created", "registry_committing", "completed", null]); expect(session.checkpoint?.sandboxRecreate).toBeNull(); }); @@ -687,6 +680,60 @@ it("creates a missing sandbox from a preserved registry row without removing the expect(session.checkpoint?.sandboxRecreate ?? null).toBeNull(); }); +it("keeps durable state and emits no success when FSM CAS save throws (#10491)", async () => { + const session = createSession({ sandboxName: "saved", agent: "openclaw" }); + session.steps.sandbox.status = "complete"; + session.machine.state = "agent_setup"; + session.checkpoint = { + ...deriveCheckpointFromSession(session), + sandboxIdentity: decisionSelected({ name: "saved", agent: "openclaw" }), + gatewayAuthority: decisionSelected({ + gatewayName: "nemoclaw", + gatewayPort: 8080, + mode: "nemoclaw-managed", + source: "standalone", + endpoint: null, + stateDir: null, + supervisor: null, + requiredCapabilities: [], + }), + }; + const oldJournal = session.checkpoint?.sandboxRecreate ?? null; + const { deps, calls } = createDeps( + { + getSandboxReuseState: () => "not_ready", + getSandboxRegistryEntry: () => ({ + name: "saved", + gatewayName: "nemoclaw", + gatewayPort: 8080, + provider: "provider", + model: "model", + }), + getSandboxRecreateObservation: () => ({ + state: "not_ready", + liveIdentityFingerprint: fingerprintSandboxRecreateValue("source-id"), + }), + compareAndSwapSession: vi.fn((matches, mutator) => { + const transient = structuredClone(session); + return matches(transient) + ? (mutator(transient), + (() => { + throw new Error("durable CAS save failed"); + })()) + : ("mismatch" as const); + }), + }, + session, + ); + + await expect( + handleSandboxState({ ...baseOptions(deps, session), resume: true, sandboxName: "saved" }), + ).rejects.toThrow("durable CAS save failed"); + expect(session.checkpoint?.sandboxRecreate ?? null).toEqual(oldJournal); + expect(calls.createSandbox).not.toHaveBeenCalled(); + expect(calls.complete).not.toHaveBeenCalled(); +}); + it("opens the lifecycle journal for a fresh route reservation before creation (#9833)", async () => { const session = createSession({ sandboxName: "fresh", agent: "openclaw" }); session.checkpoint = { diff --git a/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts b/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts index cf428bbee18..192d6b751a0 100644 --- a/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts +++ b/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts @@ -168,10 +168,17 @@ export function createDeps( const calls = { checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true as const })), note: vi.fn(), + loadSession: vi.fn(() => session), updateSession: vi.fn((mutator: (value: Session) => Session | void) => { session = mutator(session) ?? session; return session; }), + compareAndSwapSession: vi.fn( + (matches: (value: Session) => boolean, mutator: (value: Session) => Session | void) => + matches(session) + ? ((session = mutator(session) ?? session), "updated" as const) + : ("mismatch" as const), + ), persistMessaging: vi.fn(), clearPlanEnv: vi.fn(), removeSandbox: vi.fn((): SandboxRemovalReceipt | null => null), @@ -267,7 +274,9 @@ export function createDeps( agentSupportsWebSearch: () => true, note: calls.note, cliName: () => "nemoclaw", + loadSession: calls.loadSession, updateSession: calls.updateSession, + compareAndSwapSession: calls.compareAndSwapSession, getStoredMessagingChannelConfig: () => null, hydrateMessagingChannelConfig: (config: MessagingChannelConfig | null) => config, messagingChannelConfigsEqual: () => true, diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index e0a4870cca2..34d8d9fb1ad 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -32,6 +32,7 @@ import type { OnboardCheckpoint, } from "../../../state/onboard-checkpoint-types"; import type { + CompareAndSwapSessionResult, HermesAuthMethod, Session, SessionResourceProfile, @@ -81,9 +82,9 @@ import { import type { SandboxCreateIntent as ResolvedSandboxCreateIntent } from "../../sandbox-create-intent-types"; import { advanceSandboxRecreateTransaction, - beginSandboxRecreateTransaction, clearCompletedSandboxRecreateTransaction, fingerprintSandboxRecreateValue, + ownSandboxRecreateTransaction, type ReplacedSandboxSourceEntry, type ReplacedSandboxWorkloadCleanupResult, retireReplacedSandboxWorkload as retireReplacedSandboxWorkloadDefault, @@ -245,7 +246,13 @@ export interface SandboxStateOptions< ): boolean; note(message: string): void; cliName(): string; + loadSession(): Session | null; updateSession(mutator: (session: Session) => Session | void): Session; + compareAndSwapSession( + matches: (session: Session) => boolean, + mutator: (session: Session) => Session | void, + command?: string, + ): CompareAndSwapSessionResult; getStoredMessagingChannelConfig( sandboxName: string | null, session: Session | null, @@ -1855,23 +1862,40 @@ class SandboxStateFlow< ); } if (!gateway) return null; - const observation = this.deps.getSandboxRecreateObservation(sandboxName); - const updated = this.deps.updateSession((current) => { - beginSandboxRecreateTransaction(current, { - sandboxName, - gatewayName: gateway.gatewayName, - gatewayPort: gateway.gatewayPort, - sourceEntry, - observation, - targetIntentFingerprint: selectSandboxRecreateTargetIntentFingerprint( - existing, - this.sandboxRecreateTargetIntentFingerprint(sandboxName, createIntent), - this.options.recreateJournalTargetIntentFingerprint, - ), - }); - return current; - }); - return updated.checkpoint?.sandboxRecreate ?? null; + const targetIntentFingerprint = selectSandboxRecreateTargetIntentFingerprint( + existing, + this.sandboxRecreateTargetIntentFingerprint(sandboxName, createIntent), + this.options.recreateJournalTargetIntentFingerprint, + ); + return ownSandboxRecreateTransaction({ + sessionStore: { + loadSession: this.deps.loadSession, + updateSession: this.deps.updateSession, + compareAndSwapSession: this.deps.compareAndSwapSession, + }, + sandboxName, + gatewayName: gateway.gatewayName, + gatewayPort: gateway.gatewayPort, + targetIntentFingerprint, + readRegistryEntry: () => this.deps.getSandboxRegistryEntry(sandboxName), + observe: () => this.deps.getSandboxRecreateObservation(sandboxName), + decorateCheckpoint: (_current, checkpoint) => { + const currentGateway = selectedGatewayForSandboxRecreate( + checkpoint, + this.options.gatewayName, + ); + if ( + !currentGateway || + currentGateway.gatewayName !== gateway.gatewayName || + currentGateway.gatewayPort !== gateway.gatewayPort + ) { + throw new Error( + `Cannot journal sandbox '${sandboxName}': the selected gateway authority changed.`, + ); + } + return checkpoint; + }, + }).transaction; } private sandboxRecreateTargetIntentFingerprint( diff --git a/src/lib/onboard/machine/transition-traces.test.ts b/src/lib/onboard/machine/transition-traces.test.ts index 9e28ad929fe..557aef5b80b 100644 --- a/src/lib/onboard/machine/transition-traces.test.ts +++ b/src/lib/onboard/machine/transition-traces.test.ts @@ -52,6 +52,15 @@ function createTracedRuntime(initialSession: Session = createSession()) { session = cloneSession(next); return cloneSession(session); }; + const compareAndSwapSession = ( + matches: (value: Session) => boolean, + mutator: (value: Session) => Session | void, + ): "updated" | "mismatch" => { + const current = cloneSession(session); + return matches(current) + ? ((session = cloneSession(mutator(current) ?? current)), "updated") + : "mismatch"; + }; const applySafeUpdates = (updates: SessionUpdates = {}): Session => updateSession((current) => { Object.assign(current, filterSafeUpdates(updates)); @@ -82,7 +91,13 @@ function createTracedRuntime(initialSession: Session = createSession()) { emitEvent: (event) => events.push(event), now: () => NOW, }; - return { runtime: new OnboardRuntime(deps), events, updateSession }; + return { + runtime: new OnboardRuntime(deps), + events, + loadSession: () => cloneSession(session), + updateSession, + compareAndSwapSession, + }; } function traceOf(events: readonly OnboardMachineEvent[]): string[] { @@ -208,7 +223,8 @@ describe("onboard machine lifecycle traces (#6225)", () => { machine: machineAt("sandbox", 5), steps: { sandbox: completedStep() }, }); - const { runtime, events, updateSession } = createTracedRuntime(resumedSession); + const { runtime, events, loadSession, updateSession, compareAndSwapSession } = + createTracedRuntime(resumedSession); await runtime.start({ resumed: true }); const session = await runtime.session(); const journal = bindJournaledRecreate(session, "my-assistant", "openclaw", updateSession); @@ -219,7 +235,9 @@ describe("onboard machine lifecycle traces (#6225)", () => { getSandboxReuseState: () => "not_ready", getSandboxRecreateObservation: journal.observe, createSandbox: journal.completeCreate, + loadSession, updateSession, + compareAndSwapSession, recordRepairEvent: (type, options) => runtime.emitRepairEvent(type, options), recordStepComplete: async (_stepName, updates) => updateSession((current) => { diff --git a/src/lib/onboard/onboard-recreate-journal.test.ts b/src/lib/onboard/onboard-recreate-journal.test.ts index 16e400ea2f8..a28d0b61823 100644 --- a/src/lib/onboard/onboard-recreate-journal.test.ts +++ b/src/lib/onboard/onboard-recreate-journal.test.ts @@ -110,6 +110,9 @@ describe("non-resumed onboard replacement journal (#7735)", () => { session = mutator(session) ?? session; return session; }); + vi.spyOn(onboardSession, "compareAndSwapSession").mockImplementation((matches, mutator) => { + return matches(session) ? ((session = mutator(session) ?? session), "updated") : "mismatch"; + }); vi.spyOn(registry, "getSandbox").mockReturnValue({ name: "alpha", agent: "openclaw", @@ -133,9 +136,9 @@ describe("non-resumed onboard replacement journal (#7735)", () => { vi.restoreAllMocks(); }); - function open(intent: OnboardRecreateTargetIntent = BASE_INTENT) { + function open(intent: OnboardRecreateTargetIntent = BASE_INTENT, target = NON_DEFAULT_TARGET) { return openOnboardRecreateJournal({ - target: NON_DEFAULT_TARGET, + target, agentName: "openclaw", intent, note: vi.fn(), @@ -159,6 +162,7 @@ describe("non-resumed onboard replacement journal (#7735)", () => { open(); expect(mocks.resolveGatewayTeardownAuthority).toHaveBeenCalledWith({ + sandboxName: "alpha", gatewayName: "nemoclaw-9090", gatewayPort: 9090, }); @@ -350,4 +354,61 @@ describe("non-resumed onboard replacement journal (#7735)", () => { expect(session.checkpoint?.sandboxRecreate?.phase).toBe("deleted"); expect(session.checkpoint?.sandboxRecreate?.sourceLiveIdentityFingerprint).toBeNull(); }); + + it("starts a fresh journal when the stranded one no longer owns a replacement (#10473)", () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw-9090", + gatewayPort: 9090, + lifecycleGeneration: "44444444-4444-4444-8444-444444444444", + lifecycleLiveIdentityFingerprint: SANDBOX_FINGERPRINT, + } as registry.SandboxEntry); + const stranded = open(); + stranded.advance("deleted"); + expect(session.checkpoint?.sandboxRecreate?.phase).toBe("deleted"); + + const restarted = open(); + + expect(restarted.targetGeneration).not.toBe(stranded.targetGeneration); + expect(restarted.acceptedTarget).toBe(false); + expect(session.checkpoint?.sandboxRecreate).toMatchObject({ + phase: "planned", + revision: 0, + sourceLiveIdentityFingerprint: SANDBOX_FINGERPRINT, + }); + }); + + it("keeps a stranded journal when the matching source is on another gateway (#10473)", () => { + mocks.captureOpenshell.mockReturnValue(absentProbe()); + open(); + const stranded = session.checkpoint?.sandboxRecreate; + expect(stranded).toMatchObject({ gatewayName: "nemoclaw-9090", phase: "deleted" }); + + // Same sandbox name and same live identity, but the row and the probe now + // describe a sandbox on a different gateway. The journal may still own an + // unregistered replacement on nemoclaw-9090, so it must survive. + mocks.captureOpenshell.mockReturnValue(livePresentProbe()); + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw-7070", + gatewayPort: 7070, + lifecycleGeneration: "44444444-4444-4444-8444-444444444444", + lifecycleLiveIdentityFingerprint: SANDBOX_FINGERPRINT, + } as registry.SandboxEntry); + + expect(() => + open(BASE_INTENT, { + sandboxName: "alpha", + gatewayName: "nemoclaw-7070", + gatewayPort: 7070, + }), + ).toThrow(/different recreate transaction in progress/); + expect(session.checkpoint?.sandboxRecreate).toMatchObject({ + id: stranded?.id, + gatewayName: "nemoclaw-9090", + phase: "deleted", + }); + }); }); diff --git a/src/lib/onboard/onboard-recreate-journal.ts b/src/lib/onboard/onboard-recreate-journal.ts index 29cdb0d4a72..a8465954df0 100644 --- a/src/lib/onboard/onboard-recreate-journal.ts +++ b/src/lib/onboard/onboard-recreate-journal.ts @@ -2,10 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { decisionSelected } from "../state/onboard-checkpoint-decision"; -import { deriveCheckpointFromSession } from "../state/onboard-checkpoint-migrate"; import * as onboardSession from "../state/onboard-session"; import * as registry from "../state/registry"; import { checkpointGatewayAuthority } from "./gateway-authority-checkpoint"; +import { sameGatewayOwner } from "./gateway-ownership"; import { resolveGatewayTeardownAuthority } from "./gateway-teardown-authority"; import { observeSandboxOnGateway, @@ -15,11 +15,10 @@ import { import { abandonSandboxRecreateTransaction, advanceSandboxRecreateTransaction, - beginSandboxRecreateTransaction, clearCompletedSandboxRecreateTransaction, createSandboxRecreateRuntime, fingerprintSandboxRecreateValue, - planSandboxRecreateRecovery, + ownSandboxRecreateTransaction, type SandboxRecreateRuntime, sandboxRecreatePhaseReached, } from "./sandbox-recreate-transaction"; @@ -73,57 +72,58 @@ export type OwnedSandboxRecreateRuntime = SandboxRecreateRuntime & { abandon(): void; }; +/** Capture gateway lifecycle authority and return its delete-edge revalidator. */ +export function createOnboardRecreateGatewayAuthorityRevalidator(target: SandboxRecreateTarget): { + authority: ReturnType; + revalidate: () => void; +} { + const authority = resolveGatewayTeardownAuthority(target); + return { + authority, + revalidate: () => { + const currentAuthority = resolveGatewayTeardownAuthority(target); + if (!sameGatewayOwner(authority, currentAuthority)) { + throw new Error( + `Cannot delete sandbox '${target.sandboxName}': its gateway lifecycle authority changed.`, + ); + } + }, + }; +} + export function openOnboardRecreateJournal( input: OpenOnboardRecreateJournalInput, ): OwnedSandboxRecreateRuntime { const { target, agentName, note } = input; const targetIntentFingerprint = fingerprintOnboardRecreateTargetIntent(input.intent); const observe = input.observe ?? observeSandboxOnGateway; - const authority = resolveGatewayTeardownAuthority({ + const gatewayAuthority = createOnboardRecreateGatewayAuthorityRevalidator(target); + const { authority } = gatewayAuthority; + const owned = ownSandboxRecreateTransaction({ + sessionStore: { + loadSession: onboardSession.loadSession, + updateSession: onboardSession.updateSession, + compareAndSwapSession: onboardSession.compareAndSwapSession, + }, + sandboxName: target.sandboxName, gatewayName: target.gatewayName, gatewayPort: target.gatewayPort, - }); - const sourceEntry = registry.getSandbox(target.sandboxName); - if (!sourceEntry) { - throw new Error( - `Cannot start sandbox '${target.sandboxName}' recreate transaction without its source registry row.`, - ); - } - const observation = observe(target); - const active = onboardSession.loadSession()?.checkpoint?.sandboxRecreate ?? null; - if (active) { - const recovery = planSandboxRecreateRecovery(active, observation, sourceEntry); - if (recovery.action === "reject") { - throw new Error( - `Cannot resume sandbox '${target.sandboxName}' replacement: ${recovery.reason}.`, - ); - } - } - - const session = onboardSession.updateSession((current) => { - const checkpoint = current.checkpoint ?? deriveCheckpointFromSession(current); - current.checkpoint = { + targetIntentFingerprint, + requireSourceEntry: true, + readRegistryEntry: () => registry.getSandbox(target.sandboxName), + observe: () => observe(target), + decorateCheckpoint: (current, checkpoint, now) => ({ ...checkpoint, machineState: current.machine.state, - updatedAt: new Date().toISOString(), + updatedAt: now, sandboxIdentity: decisionSelected({ name: target.sandboxName, agent: agentName }), gatewayAuthority: decisionSelected(checkpointGatewayAuthority(authority)), - }; - beginSandboxRecreateTransaction(current, { - sandboxName: target.sandboxName, - gatewayName: target.gatewayName, - gatewayPort: target.gatewayPort, - sourceEntry, - observation, - targetIntentFingerprint, - }); - return current; + }), }); - - const transaction = session.checkpoint?.sandboxRecreate; - if (!transaction) { - throw new Error( - `Sandbox '${target.sandboxName}' replacement journal could not be recorded before deletion.`, + const { transaction, registryEntry: sourceEntry } = owned; + if (owned.replacedTransactionId) { + note( + ` Replaced void journal ${owned.replacedTransactionId} with ${transaction.id} for '${target.sandboxName}'; its source sandbox is registered and live.`, ); } note( @@ -146,6 +146,8 @@ export function openOnboardRecreateJournal( sourceEntry, (sandboxName, gatewayName) => observe({ ...target, sandboxName, gatewayName }), note, + () => registry.getSandbox(target.sandboxName), + gatewayAuthority.revalidate, ); return { diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 44f79dbb10d..efb47d58f4d 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -43,7 +43,10 @@ import type { ManagedHermesStateVolumeContext, } from "../managed-workload/hermes-state-volume"; import { removeManagedHermesStateVolume } from "../managed-workload/hermes-state-volume"; -import type { OwnedSandboxRecreateRuntime } from "../onboard-recreate-journal"; +import { + createOnboardRecreateGatewayAuthorityRevalidator, + type OwnedSandboxRecreateRuntime, +} from "../onboard-recreate-journal"; import { managedImageRuntimeIdentity } from "../managed-image/agents"; import { managedStartupStateRoots, @@ -1212,6 +1215,35 @@ function readHermesPortableLifecycleGeneration(input: { : undefined; } +function selectRecreateGatewayAuthority( + requested: boolean, + target: { sandboxName: string; gatewayName: string; gatewayPort: number }, +) { + return requested ? createOnboardRecreateGatewayAuthorityRevalidator(target) : undefined; +} + +function deleteJournaledRecreateSource(input: { + readonly runtime: Pick< + import("../sandbox-recreate-transaction").SandboxRecreateRuntime, + "beginDelete" | "journaledGatewayName" + >; + readonly sandboxName: string; + readonly gatewayName: string; + readonly runOpenshell: SandboxCreateOrchestrationRuntime["runOpenshell"]; +}): void { + if (input.runtime.beginDelete() !== "source") return; + input.runOpenshell( + [ + "sandbox", + "delete", + "-g", + input.runtime.journaledGatewayName ?? input.gatewayName, + input.sandboxName, + ], + { ignoreError: true }, + ); +} + export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrchestrationRuntime) { const postCreateRecoveryRetryOwner = installPostCreateRecoveryRetryOwner(); return async function createSandboxWithBaseImageResolution( @@ -1611,6 +1643,10 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche existingEntry, readRegistry: registry.getSandbox, }); + const recreateGatewayAuthority = selectRecreateGatewayAuthority( + Boolean(createIntent?.recreateTransaction), + { sandboxName, gatewayName: GATEWAY_NAME, gatewayPort: GATEWAY_PORT }, + ); let recreateRuntime: | import("../sandbox-recreate-transaction").SandboxRecreateRuntime | OwnedSandboxRecreateRuntime = sandboxRecreateTransaction.createSandboxRecreateRuntime( @@ -1621,6 +1657,8 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche recreateRegistryEntry, getSandboxRecreateObservation, note, + () => registry.getSandbox(sandboxName), + recreateGatewayAuthority?.revalidate, ); const acceptedTargetPendingIdentity = readAcceptedPendingVerifiedCreate({ acceptedTarget: recreateRuntime.acceptedTarget, @@ -1993,16 +2031,12 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche redact, }); revalidateSandboxIdentity(true, `deleting sandbox '${sandboxName}'`); - runOpenshell( - [ - "sandbox", - "delete", - "-g", - recreateRuntime.journaledGatewayName ?? GATEWAY_NAME, - sandboxName, - ], - { ignoreError: true }, - ); + deleteJournaledRecreateSource({ + runtime: recreateRuntime, + sandboxName, + gatewayName: GATEWAY_NAME, + runOpenshell, + }); if ( !waitForSandboxRecreateDeleteAbsence( sandboxName, diff --git a/src/lib/onboard/sandbox-recreate-transaction.test.ts b/src/lib/onboard/sandbox-recreate-transaction.test.ts index f0f7ee69402..0a0bdf7ad33 100644 --- a/src/lib/onboard/sandbox-recreate-transaction.test.ts +++ b/src/lib/onboard/sandbox-recreate-transaction.test.ts @@ -453,6 +453,9 @@ describe("sandbox recreate journal", () => { mutator(session); return session; }, + compareAndSwapSession: (matches, mutator) => { + return matches(session) ? (mutator(session), "updated") : "mismatch"; + }, }, { id: TX_ID, @@ -505,6 +508,9 @@ describe("sandbox recreate journal", () => { mutator(session); return session; }, + compareAndSwapSession: (matches, mutator) => { + return matches(session) ? (mutator(session), "updated") : "mismatch"; + }, }, { id: TX_ID, @@ -552,6 +558,9 @@ describe("sandbox recreate journal", () => { mutator(session); return session; }, + compareAndSwapSession: (matches, mutator) => { + return matches(session) ? (mutator(session), "updated") : "mismatch"; + }, }, { id: TX_ID, @@ -578,6 +587,77 @@ describe("sandbox recreate journal", () => { expect(session.checkpoint?.sandboxRecreate).toMatchObject({ phase: "deleting" }); }); + it("revalidates authority and source evidence at the second delete edge (#10491)", () => { + const session = createSession({ sandboxName: "alpha" }); + beginSandboxRecreateTransaction( + session, + beginInput({ state: "ready", liveIdentityFingerprint: SOURCE_ID }), + ); + let registryEntry = SOURCE_ENTRY; + let observation: SandboxRecreateObservation = { + state: "ready", + liveIdentityFingerprint: SOURCE_ID, + }; + const revalidateGatewayAuthority = vi.fn(); + const runtime = createSandboxRecreateRuntime( + { + loadSession: () => session, + updateSession: (mutator) => (mutator(session), session), + compareAndSwapSession: (matches, mutator) => + matches(session) ? (mutator(session), "updated") : "mismatch", + }, + { id: TX_ID, targetGeneration: TARGET_GENERATION, targetIntentFingerprint: TARGET_INTENT }, + "alpha", + "nemoclaw-31818", + SOURCE_ENTRY, + () => observation, + () => undefined, + () => registryEntry, + revalidateGatewayAuthority, + ); + + expect(runtime.beginDelete()).toBe("source"); + registryEntry = { ...SOURCE_ENTRY, imageTag: "foreign" }; + observation = { state: "ready", liveIdentityFingerprint: FOREIGN_ID }; + expect(() => runtime.beginDelete()).toThrow(/registry row changed|not the journaled source/iu); + expect(revalidateGatewayAuthority).toHaveBeenCalledTimes(2); + expect(session.checkpoint?.sandboxRecreate).toMatchObject({ phase: "deleting", revision: 1 }); + }); + + it("refuses authority drift after the runtime opens (#10491)", () => { + const session = createSession({ sandboxName: "alpha" }); + beginSandboxRecreateTransaction( + session, + beginInput({ state: "ready", liveIdentityFingerprint: SOURCE_ID }), + ); + let authorityMatches = true; + const runtime = createSandboxRecreateRuntime( + { + loadSession: () => session, + updateSession: (mutator) => (mutator(session), session), + compareAndSwapSession: (matches, mutator) => + matches(session) ? (mutator(session), "updated") : "mismatch", + }, + { id: TX_ID, targetGeneration: TARGET_GENERATION, targetIntentFingerprint: TARGET_INTENT }, + "alpha", + "nemoclaw-31818", + SOURCE_ENTRY, + () => ({ state: "ready", liveIdentityFingerprint: SOURCE_ID }), + () => undefined, + () => SOURCE_ENTRY, + () => + authorityMatches + ? undefined + : (() => { + throw new Error("gateway lifecycle authority changed"); + })(), + ); + authorityMatches = false; + + expect(() => runtime.beginDelete()).toThrow(/gateway lifecycle authority changed/iu); + expect(session.checkpoint?.sandboxRecreate).toMatchObject({ phase: "planned", revision: 0 }); + }); + it("refuses to open the delete edge when no transaction proves the source (#7736)", () => { const session = createSession({ sandboxName: "alpha" }); const runtime = createSandboxRecreateRuntime( @@ -613,6 +693,12 @@ describe("sandbox recreate journal", () => { mutator(session); return session; }, + compareAndSwapSession: ( + matches: (current: typeof session) => boolean, + mutator: (current: typeof session) => typeof session | void, + ) => { + return matches(session) ? (mutator(session), "updated" as const) : ("mismatch" as const); + }, }; const request = { id: TX_ID, diff --git a/src/lib/onboard/sandbox-recreate-transaction.ts b/src/lib/onboard/sandbox-recreate-transaction.ts index 33a22cd2777..9da98f3f335 100644 --- a/src/lib/onboard/sandbox-recreate-transaction.ts +++ b/src/lib/onboard/sandbox-recreate-transaction.ts @@ -198,16 +198,63 @@ const ROUTE_RESERVATION_FIELDS: readonly (keyof SandboxEntry)[] = [ "gatewayName", "gatewayPort", ]; -const RECEIPT_BOUND_PROJECTION_FIELDS: readonly (keyof SandboxEntry)[] = ["mcp"]; +// Rebuild may update these independently projected fields before delete. +// The source fingerprint still binds every sandbox, gateway, lifecycle, agent, +// and workload ownership field. +const RECEIPT_BOUND_PROJECTION_FIELDS: readonly (keyof SandboxEntry)[] = [ + "mcp", + // `messaging` is a rehydrated projection, not durable sandbox identity: the + // channel commands own it (`channels add|stop|start|remove` rewrite the plan + // workflow label, disabledChannels, and the derived per-channel active, + // disabled, and hostForward fields), and loading the registry re-derives the + // rest of it from the built-in channel manifests and the ambient environment. + // Binding it made a `channels stop` plus `channels start` between two rebuilds + // change the fingerprint of an untouched sandbox, which left every later + // rebuild rejecting its own journal (#10473). + "messaging", +]; -export function fingerprintSandboxRegistryEntry(entry: SandboxEntry): string { +function fingerprintDurableSandboxEntry( + entry: SandboxEntry, + excluded: readonly (keyof SandboxEntry)[], +): string { const durable: Record = { ...entry }; - for (const field of [...ROUTE_RESERVATION_FIELDS, ...RECEIPT_BOUND_PROJECTION_FIELDS]) { - delete durable[field]; - } + for (const field of excluded) delete durable[field]; return fingerprintSandboxRecreateValue(durable); } +export function fingerprintSandboxRegistryEntry(entry: SandboxEntry): string { + return fingerprintDurableSandboxEntry(entry, [ + ...ROUTE_RESERVATION_FIELDS, + ...RECEIPT_BOUND_PROJECTION_FIELDS, + ]); +} + +/** + * Accept a source row against a journal written before `messaging` left the + * durable fingerprint. + * + * Such a journal recorded a digest that still covered the messaging projection, + * so recomputing it the new way never matches. Because a journal parked past the + * delete boundary outlives an upgrade, refusing it would strand a rebuild whose + * source sandbox is already deleted. The compatibility digest reproduces the + * exact pre-#10473 field set, so it accepts only what the previous release + * already accepted. + */ +function sandboxRecreateSourceRowMatches( + entry: SandboxEntry | null, + recordedFingerprint: string, +): boolean { + if (!entry) return recordedFingerprint === fingerprintSandboxRecreateValue(null); + if (fingerprintSandboxRegistryEntry(entry) === recordedFingerprint) return true; + return ( + fingerprintDurableSandboxEntry(entry, [ + ...ROUTE_RESERVATION_FIELDS, + ...RECEIPT_BOUND_PROJECTION_FIELDS.filter((field) => field !== "messaging"), + ]) === recordedFingerprint + ); +} + export function fingerprintSandboxLiveIdentity(getOutput: string): string | null { const clean = String(getOutput).replace(/\x1b\[[0-9;]*m/g, ""); const match = clean.match(/^\s*Id:\s+(\S+)\s*$/im); @@ -485,7 +532,7 @@ export function assertSandboxRecreateSourceProof( ); } if (!check.registryEntry) return fail("the source registry row is absent"); - if (fingerprintSandboxRegistryEntry(check.registryEntry) !== proof.sourceRegistryFingerprint) { + if (!sandboxRecreateSourceRowMatches(check.registryEntry, proof.sourceRegistryFingerprint)) { return fail("the source registry row changed after the transaction recorded it"); } if (check.observation.state === "missing") { @@ -549,28 +596,22 @@ export interface BeginSandboxRecreateTransactionInput { readonly targetGeneration?: string; } -export function beginSandboxRecreateTransaction( - session: Session, +function newSandboxRecreateTransaction( + checkpoint: OnboardCheckpoint, input: BeginSandboxRecreateTransactionInput, ): CheckpointSandboxRecreateTransaction { - const existing = activeTransaction(session); - if (existing) { - assertSameTransaction(existing, input); - return existing; - } if (input.observation.state !== "missing" && !input.observation.liveIdentityFingerprint) { throw new Error( `Cannot recreate sandbox '${input.sandboxName}': OpenShell did not report a stable sandbox Id.`, ); } - const checkpoint = baseCheckpoint(session); - const now = input.now ?? new Date().toISOString(); if (!input.sourceEntry && input.observation.state !== "missing") { throw new Error( `Cannot start sandbox '${input.sandboxName}' lifecycle journal without its source registry row while OpenShell reports a same-name sandbox.`, ); } - const transaction: CheckpointSandboxRecreateTransaction = { + const now = input.now ?? new Date().toISOString(); + return { version: 1, id: input.id ?? randomUUID(), revision: 0, @@ -589,12 +630,33 @@ export function beginSandboxRecreateTransaction( startedAt: now, updatedAt: now, }; +} + +function setSandboxRecreateTransaction( + session: Session, + checkpoint: OnboardCheckpoint, + transaction: CheckpointSandboxRecreateTransaction, +): void { session.checkpoint = { ...checkpoint, machineState: session.machine.state, - updatedAt: now, + updatedAt: transaction.updatedAt, sandboxRecreate: transaction, }; +} + +export function beginSandboxRecreateTransaction( + session: Session, + input: BeginSandboxRecreateTransactionInput, +): CheckpointSandboxRecreateTransaction { + const existing = activeTransaction(session); + if (existing) { + assertSameTransaction(existing, input); + return existing; + } + const checkpoint = baseCheckpoint(session); + const transaction = newSandboxRecreateTransaction(checkpoint, input); + setSandboxRecreateTransaction(session, checkpoint, transaction); return transaction; } @@ -737,16 +799,106 @@ export type SandboxRecreateRecoveryPlan = | { readonly action: "continue_delete" } | { readonly action: "continue_create" } | { readonly action: "accept_target" } + | { readonly action: "restart_from_source" } | { readonly action: "reject"; readonly reason: string }; function reject(reason: string): SandboxRecreateRecoveryPlan { return { action: "reject", reason }; } +/** + * The gateway a piece of recreate evidence was gathered on. + * + * Structural so both a `SandboxEntry` and a probe target satisfy it without the + * transaction module importing the probe module it already feeds. + */ +export interface SandboxRecreateGateway { + readonly gatewayName: string; + readonly gatewayPort: number; +} + +/** + * The same pairing as recorded on a registry row, where a legacy row may carry + * neither field. A journal always records both, so an unset row fails closed. + */ +interface SandboxRecreateGatewayEvidence { + readonly gatewayName?: string | null; + readonly gatewayPort?: number | null; +} + +/** Whether evidence names the gateway the journal recorded. Absent evidence never matches. */ +function onSandboxRecreateGateway( + transaction: CheckpointSandboxRecreateTransaction, + gateway: SandboxRecreateGatewayEvidence | null | undefined, +): boolean { + return ( + gateway?.gatewayName === transaction.gatewayName && + gateway.gatewayPort === transaction.gatewayPort + ); +} + +/** + * A journal whose replacement provably never happened. + * + * The caller has already ruled out the registered replacement, so the journal + * still claims a replacement is in flight. When the registry row and a live + * same-name sandbox name the same OpenShell identity, that claim is false: the + * sandbox this row describes is intact and there is no unregistered replacement + * to converge on. The recorded replacement is void, and the owner may retire it + * and open a fresh transaction against the live source instead of refusing every + * later rebuild for the rest of the session (#10473). + * + * The identity equality is what makes this safe. A replacement that was created + * but not yet registered carries a fresh OpenShell Id while the preserved row + * still carries the source's, so it can never satisfy this and stays protected + * by the fail-closed refusals in `planUnregisteredReplacementRecovery`. + * + * The name equality binds the evidence to the journal. `checkpoint.sandboxRecreate` + * holds one journal for the whole session, so a caller can present the row and + * observation of a different sandbox; that pairing must keep refusing rather than + * retire a journal protecting another sandbox's replacement. + * + * The gateway equality binds that evidence to the journal's own gateway. A + * sandbox name identifies one row per registry, not one sandbox per fleet, and + * `gatewayName`/`gatewayPort` sit in `ROUTE_RESERVATION_FIELDS` so the source + * fingerprint cannot notice a row that moved gateways under an open journal. + * The transaction owner evaluates this while `compareAndSwapSession` owns the + * session writer boundary. Without the checks below, evidence gathered on + * gateway B could replace a journal that still owns an unregistered replacement + * on gateway A and orphan it. Requiring the row and observation to name the + * journaled gateway keeps that decision fail-closed. + */ +function replacementIsVoid( + transaction: CheckpointSandboxRecreateTransaction, + observation: SandboxRecreateObservation, + registryEntry: SandboxEntry | null, + observedGateway: SandboxRecreateGateway | null | undefined, +): boolean { + return Boolean( + onSandboxRecreateGateway(transaction, observedGateway) && + onSandboxRecreateGateway(transaction, registryEntry) && + registryEntry?.name === transaction.sandboxName && + sandboxRecreateSourceRowMatches(registryEntry, transaction.sourceRegistryFingerprint) && + registryEntry.lifecycleLiveIdentityFingerprint && + transaction.sourceLiveIdentityFingerprint && + observation.state !== "missing" && + observation.liveIdentityFingerprint === registryEntry.lifecycleLiveIdentityFingerprint && + observation.liveIdentityFingerprint === transaction.sourceLiveIdentityFingerprint && + observation.liveIdentityFingerprint !== transaction.targetLiveIdentityFingerprint, + ); +} + +/** + * @param observedGateway The gateway `observation` was probed on. Omitting it + * withholds the `restart_from_source` downgrade entirely, so a caller that + * cannot name its gateway keeps the pre-#10473 refusal instead of retiring a + * journal it never proved is void. + */ export function planSandboxRecreateRecovery( transaction: CheckpointSandboxRecreateTransaction, observation: SandboxRecreateObservation, registryEntry: SandboxEntry | null, + observedGateway?: SandboxRecreateGateway | null, ): SandboxRecreateRecoveryPlan { if (registryEntry?.lifecycleGeneration === transaction.targetGeneration) { if (!transaction.targetLiveIdentityFingerprint) { @@ -766,9 +918,30 @@ export function planSandboxRecreateRecovery( return { action: "accept_target" }; } - const sourceStateUnchanged = registryEntry - ? fingerprintSandboxRegistryEntry(registryEntry) === transaction.sourceRegistryFingerprint - : transaction.sourceRegistryFingerprint === fingerprintSandboxRecreateValue(null); + const unregistered = planUnregisteredReplacementRecovery(transaction, observation, registryEntry); + // Only deleted and creating can represent an interrupted replacement whose + // source returned. The transaction owner can atomically replace that journal + // when the live sandbox and registry row prove the source identity (#10473). + if ( + (transaction.phase === "deleted" || transaction.phase === "creating") && + unregistered.action === "reject" && + replacementIsVoid(transaction, observation, registryEntry, observedGateway) + ) { + return { action: "restart_from_source" }; + } + return unregistered; +} + +/** The recovery decision for a journal whose replacement is not registered. */ +function planUnregisteredReplacementRecovery( + transaction: CheckpointSandboxRecreateTransaction, + observation: SandboxRecreateObservation, + registryEntry: SandboxEntry | null, +): SandboxRecreateRecoveryPlan { + const sourceStateUnchanged = sandboxRecreateSourceRowMatches( + registryEntry, + transaction.sourceRegistryFingerprint, + ); if (transaction.phase === "completed") { return reject("the completed transaction no longer matches its replacement registry row"); } @@ -854,6 +1027,268 @@ interface SandboxRecreateSessionStore { ): CompareAndSwapSessionResult; } +interface SandboxRecreateTransactionOwnerStore extends SandboxRecreateSessionStore { + compareAndSwapSession( + matches: (session: Session) => boolean, + mutator: (session: Session) => Session | void, + command?: string, + ): CompareAndSwapSessionResult; +} + +export interface OwnSandboxRecreateTransactionInput { + readonly sessionStore: SandboxRecreateTransactionOwnerStore; + readonly sandboxName: string; + readonly gatewayName: string; + readonly gatewayPort: number; + readonly targetIntentFingerprint: string; + readonly requireSourceEntry?: boolean; + readonly readRegistryEntry: () => SandboxEntry | null; + readonly observe: () => SandboxRecreateObservation; + readonly decorateCheckpoint: ( + session: Session, + checkpoint: OnboardCheckpoint, + now: string, + ) => OnboardCheckpoint; +} + +export interface OwnedSandboxRecreateTransaction { + readonly session: Session; + readonly transaction: CheckpointSandboxRecreateTransaction; + readonly recovery: SandboxRecreateRecoveryPlan; + readonly replacedTransactionId: string | null; + readonly registryEntry: SandboxEntry | null; +} + +/** Open or atomically replace the recreate transaction owned by one session. */ +export function ownSandboxRecreateTransaction( + input: OwnSandboxRecreateTransactionInput, +): OwnedSandboxRecreateTransaction { + const openingSession = input.sessionStore.loadSession(); + if (!openingSession) { + throw new Error(`Cannot journal sandbox '${input.sandboxName}': no onboarding session exists.`); + } + const openingSessionId = openingSession.sessionId; + const expectedOld = activeTransaction(openingSession); + const expectedOldFingerprint = fingerprintSandboxRecreateValue(expectedOld); + let freshRegistryEntry: SandboxEntry | null | undefined; + let freshObservation: SandboxRecreateObservation | undefined; + let recovery: SandboxRecreateRecoveryPlan = { action: "continue_delete" }; + let replacedTransactionId: string | null = null; + let writtenTransaction: CheckpointSandboxRecreateTransaction | null = null; + + const result = input.sessionStore.compareAndSwapSession( + (current) => { + if ( + current.sessionId !== openingSessionId || + fingerprintSandboxRecreateValue(activeTransaction(current)) !== expectedOldFingerprint + ) { + return false; + } + freshRegistryEntry = input.readRegistryEntry(); + freshObservation = input.observe(); + if (input.requireSourceEntry && !freshRegistryEntry) { + throw new Error( + `Cannot start sandbox '${input.sandboxName}' recreate transaction without its source registry row.`, + ); + } + if (expectedOld) { + if ( + expectedOld.sandboxName !== input.sandboxName || + expectedOld.gatewayName !== input.gatewayName || + expectedOld.gatewayPort !== input.gatewayPort || + expectedOld.targetIntentFingerprint !== input.targetIntentFingerprint + ) { + throw new Error( + `Sandbox '${input.sandboxName}' has a different recreate transaction in progress; resume or repair that transaction before changing its target.`, + ); + } + recovery = planSandboxRecreateRecovery(expectedOld, freshObservation, freshRegistryEntry, { + gatewayName: input.gatewayName, + gatewayPort: input.gatewayPort, + }); + if (recovery.action === "reject") { + throw new Error( + `Cannot resume sandbox '${input.sandboxName}' replacement: ${recovery.reason}.`, + ); + } + if (recovery.action === "restart_from_source") { + replacedTransactionId = expectedOld.id; + } + } + return true; + }, + (current) => { + if (freshRegistryEntry === undefined || !freshObservation) { + throw new Error(`Cannot journal sandbox '${input.sandboxName}': fresh evidence is absent.`); + } + const now = new Date().toISOString(); + const checkpoint = input.decorateCheckpoint(current, baseCheckpoint(current), now); + if (recovery.action === "restart_from_source" || !expectedOld) { + writtenTransaction = newSandboxRecreateTransaction(checkpoint, { + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + gatewayPort: input.gatewayPort, + sourceEntry: freshRegistryEntry, + observation: freshObservation, + targetIntentFingerprint: input.targetIntentFingerprint, + now, + }); + setSandboxRecreateTransaction(current, checkpoint, writtenTransaction); + } else { + writtenTransaction = expectedOld; + setSandboxRecreateTransaction(current, checkpoint, expectedOld); + } + return current; + }, + `nemoclaw own sandbox '${input.sandboxName}' recreate transaction`, + ); + if (result === "busy") { + throw new Error( + `Cannot journal sandbox '${input.sandboxName}': another onboarding writer owns the session lock.`, + ); + } + if (result !== "updated" || !writtenTransaction) { + throw new Error( + `Cannot journal sandbox '${input.sandboxName}': its onboarding session or recreate transaction changed.`, + ); + } + + const storedSession = input.sessionStore.loadSession(); + if ( + !storedSession || + storedSession.sessionId !== openingSessionId || + fingerprintSandboxRecreateValue(activeTransaction(storedSession)) !== + fingerprintSandboxRecreateValue(writtenTransaction) + ) { + throw new Error( + `Cannot verify sandbox '${input.sandboxName}' recreate transaction after the write.`, + ); + } + return { + session: storedSession, + transaction: writtenTransaction, + recovery, + replacedTransactionId, + registryEntry: freshRegistryEntry as SandboxEntry | null, + }; +} + +export interface BeginSandboxRecreateDeleteInput { + readonly sessionStore: SandboxRecreateTransactionOwnerStore; + readonly openingSessionId: string; + readonly expectedTransaction: CheckpointSandboxRecreateTransaction; + readonly targetIntentFingerprint: string; + readonly revalidateGatewayAuthority?: () => void; + readonly readRegistryEntry: () => SandboxEntry | null; + readonly observe: () => SandboxRecreateObservation; +} + +/** Revalidate all source authority and journal deleting in one writer boundary. */ +export function beginSandboxRecreateDelete(input: BeginSandboxRecreateDeleteInput): { + readonly sourcePresence: SandboxRecreateSourcePresence; + readonly transaction: CheckpointSandboxRecreateTransaction; +} { + let observation: SandboxRecreateObservation | undefined; + let nextTransaction: CheckpointSandboxRecreateTransaction | null = null; + const result = input.sessionStore.compareAndSwapSession( + (current) => { + const transaction = activeTransaction(current); + const firstDeleteEdge = input.expectedTransaction.phase !== "deleting"; + const ownsDeleteEdge = + transaction?.id === input.expectedTransaction.id && + transaction.sandboxName === input.expectedTransaction.sandboxName && + transaction.gatewayName === input.expectedTransaction.gatewayName && + transaction.gatewayPort === input.expectedTransaction.gatewayPort && + transaction.targetGeneration === input.expectedTransaction.targetGeneration && + transaction.targetIntentFingerprint === input.targetIntentFingerprint && + (firstDeleteEdge + ? fingerprintSandboxRecreateValue(transaction) === + fingerprintSandboxRecreateValue(input.expectedTransaction) + : transaction.phase === "deleting" && + transaction.sourceRegistryFingerprint === + input.expectedTransaction.sourceRegistryFingerprint && + transaction.sourceLiveIdentityFingerprint === + input.expectedTransaction.sourceLiveIdentityFingerprint); + if (current.sessionId !== input.openingSessionId || !transaction || !ownsDeleteEdge) { + return false; + } + input.revalidateGatewayAuthority?.(); + const registryEntry = input.readRegistryEntry(); + if (!sandboxRecreateSourceRowMatches(registryEntry, transaction.sourceRegistryFingerprint)) { + throw new Error( + `Cannot delete sandbox '${transaction.sandboxName}': its source registry row changed.`, + ); + } + if ( + registryEntry?.gatewayName != null && + (registryEntry.gatewayName !== transaction.gatewayName || + registryEntry.gatewayPort !== transaction.gatewayPort) + ) { + throw new Error( + `Cannot delete sandbox '${transaction.sandboxName}': its registry gateway authority changed.`, + ); + } + const gatewayAuthority = current.checkpoint?.gatewayAuthority; + if ( + gatewayAuthority && + isDecisionSelected(gatewayAuthority) && + (gatewayAuthority.value.gatewayName !== transaction.gatewayName || + gatewayAuthority.value.gatewayPort !== transaction.gatewayPort) + ) { + throw new Error( + `Cannot delete sandbox '${transaction.sandboxName}': its journaled gateway authority changed.`, + ); + } + observation = input.observe(); + if ( + observation.state !== "missing" && + (!transaction.sourceLiveIdentityFingerprint || + observation.liveIdentityFingerprint !== transaction.sourceLiveIdentityFingerprint) + ) { + throw new Error( + `Cannot delete sandbox '${transaction.sandboxName}': the live same-name sandbox is not the journaled source.`, + ); + } + return true; + }, + (current) => { + const transaction = activeTransaction(current) as CheckpointSandboxRecreateTransaction; + nextTransaction = sandboxRecreatePhaseReached(transaction.phase, "deleted") + ? transaction + : transaction.phase === "deleting" + ? transaction + : advanceSandboxRecreateTransaction(current, transaction.id, "deleting"); + return current; + }, + `nemoclaw begin deleting sandbox '${input.expectedTransaction.sandboxName}'`, + ); + if (result === "busy") { + throw new Error( + `Cannot delete sandbox '${input.expectedTransaction.sandboxName}': another onboarding writer owns the session lock.`, + ); + } + if (result !== "updated" || !observation || !nextTransaction) { + throw new Error( + `Cannot delete sandbox '${input.expectedTransaction.sandboxName}': its onboarding session or recreate transaction changed.`, + ); + } + const stored = input.sessionStore.loadSession(); + if ( + !stored || + stored.sessionId !== input.openingSessionId || + fingerprintSandboxRecreateValue(activeTransaction(stored)) !== + fingerprintSandboxRecreateValue(nextTransaction) + ) { + throw new Error( + `Cannot verify sandbox '${input.expectedTransaction.sandboxName}' deleting journal after the write.`, + ); + } + return { + sourcePresence: observation.state === "missing" ? "missing" : "source", + transaction: nextTransaction, + }; +} + export type SandboxRecreateSourcePresence = "missing" | "source"; export interface SandboxRecreateRuntime { @@ -929,6 +1364,8 @@ export function createSandboxRecreateRuntime( registryEntry: SandboxEntry | null, observe: (sandboxName: string, gatewayName: string) => SandboxRecreateObservation, note: (message: string) => void, + readRegistryEntry: () => SandboxEntry | null = () => registryEntry, + revalidateGatewayAuthority?: () => void, ): SandboxRecreateRuntime { if (!request) return NO_SANDBOX_RECREATE; const openingSession = sessionStore.loadSession(); @@ -943,10 +1380,12 @@ export function createSandboxRecreateRuntime( throw new Error(`Sandbox '${sandboxName}' recreate journal has no owning session.`); } const openingSessionId = openingSession.sessionId; + let currentTransaction = transaction; let phase: CheckpointSandboxRecreatePhase = transaction.phase; const advance = (next: CheckpointSandboxRecreatePhase): void => { sessionStore.updateSession((current) => { - phase = advanceSandboxRecreateTransaction(current, transaction.id, next).phase; + currentTransaction = advanceSandboxRecreateTransaction(current, transaction.id, next); + phase = currentTransaction.phase; return current; }); }; @@ -955,10 +1394,17 @@ export function createSandboxRecreateRuntime( transaction, observe(sandboxName, transaction.gatewayName), registryEntry, + transaction, ); if (recovery.action === "reject") { throw new Error(`Cannot resume sandbox '${sandboxName}' recreation: ${recovery.reason}.`); } + // The caller owns journal replacement before handing this transaction off. + if (recovery.action === "restart_from_source") { + throw new Error( + `Cannot resume sandbox '${sandboxName}' recreation: its journal no longer owns a replacement.`, + ); + } if (recovery.action === "accept_target") { note(` [resume] Recovering journaled replacement sandbox '${sandboxName}'.`); } else if ( @@ -982,19 +1428,24 @@ export function createSandboxRecreateRuntime( }, advance, beginDelete: () => { - const live = observe(sandboxName, transaction.gatewayName); - if (live.state !== "missing") { - if ( - !transaction.sourceLiveIdentityFingerprint || - live.liveIdentityFingerprint !== transaction.sourceLiveIdentityFingerprint - ) { - throw new Error( - `Cannot delete sandbox '${sandboxName}': the live same-name sandbox is not the journaled source.`, - ); - } + const compareAndSwap = sessionStore.compareAndSwapSession; + if (!compareAndSwap) { + throw new Error( + `Cannot delete sandbox '${sandboxName}' without the writer-safe session update boundary.`, + ); } - if (!sandboxRecreatePhaseReached(phase, "deleted")) advance("deleting"); - return live.state === "missing" ? "missing" : "source"; + const begun = beginSandboxRecreateDelete({ + sessionStore: { ...sessionStore, compareAndSwapSession: compareAndSwap }, + openingSessionId, + expectedTransaction: currentTransaction, + targetIntentFingerprint: request.targetIntentFingerprint, + revalidateGatewayAuthority, + readRegistryEntry, + observe: () => observe(sandboxName, transaction.gatewayName), + }); + currentTransaction = begun.transaction; + phase = currentTransaction.phase; + return begun.sourcePresence; }, confirmDeleted: () => { if (observe(sandboxName, transaction.gatewayName).state !== "missing") { diff --git a/src/lib/onboard/sandbox-recreate-void-journal.test.ts b/src/lib/onboard/sandbox-recreate-void-journal.test.ts new file mode 100644 index 00000000000..0c64b1870d6 --- /dev/null +++ b/src/lib/onboard/sandbox-recreate-void-journal.test.ts @@ -0,0 +1,642 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import type { + CheckpointSandboxRecreatePhase, + CheckpointSandboxRecreateTransaction, +} from "../state/onboard-checkpoint-types"; +import { createSession } from "../state/onboard-session"; +import type { SandboxEntry } from "../state/registry"; +import { + beginSandboxRecreateDelete, + beginSandboxRecreateTransaction, + fingerprintSandboxRecreateValue, + fingerprintSandboxRegistryEntry, + ownSandboxRecreateTransaction, + planSandboxRecreateRecovery, + type SandboxRecreateObservation, +} from "./sandbox-recreate-transaction"; + +const ISO = "2026-07-27T20:00:00.000Z"; +const TX_ID = "11111111-1111-4111-8111-111111111111"; +const TARGET_GENERATION = "22222222-2222-4222-8222-222222222222"; +const SOURCE_GENERATION = "44444444-4444-4444-8444-444444444444"; +const SOURCE_ID = fingerprintSandboxRecreateValue("openshell-source-id"); +const TARGET_ID = fingerprintSandboxRecreateValue("target-id"); +const FOREIGN_ID = fingerprintSandboxRecreateValue("foreign-openshell-id"); +const TARGET_INTENT = fingerprintSandboxRecreateValue({ agent: "openclaw", provider: "nvidia" }); +const SOURCE_ENTRY: SandboxEntry = { + name: "alpha", + agent: "openclaw", + provider: "nvidia", + model: "model-a", + credentialEnv: "NVIDIA_API_KEY", + gatewayName: "nemoclaw-31818", + gatewayPort: 31818, + openshellDriver: "docker", + imageTag: "openshell/sandbox-from:old", +}; + +/** The same row once its own lifecycle registration committed. */ +const REGISTERED_SOURCE_ENTRY: SandboxEntry = { + ...SOURCE_ENTRY, + lifecycleGeneration: SOURCE_GENERATION, + lifecycleLiveIdentityFingerprint: SOURCE_ID, +}; + +const LIVE_SOURCE: SandboxRecreateObservation = { + state: "ready", + liveIdentityFingerprint: SOURCE_ID, +}; +const ABSENT_SOURCE: SandboxRecreateObservation = { + state: "missing", + liveIdentityFingerprint: null, +}; + +/** The gateway every journal, row, and probe in this suite belongs to. */ +const JOURNAL_GATEWAY = { gatewayName: "nemoclaw-31818", gatewayPort: 31818 } as const; +/** A second gateway that never owns the journal under test. */ +const FOREIGN_GATEWAY = { gatewayName: "nemoclaw-9090", gatewayPort: 9090 } as const; + +function transactionAt( + phase: CheckpointSandboxRecreatePhase, + sourceEntry: SandboxEntry = REGISTERED_SOURCE_ENTRY, +): CheckpointSandboxRecreateTransaction { + return { + version: 1, + id: TX_ID, + revision: 3, + sandboxName: "alpha", + gatewayName: "nemoclaw-31818", + gatewayPort: 31818, + sourceRegistryFingerprint: fingerprintSandboxRegistryEntry(sourceEntry), + sourceLiveIdentityFingerprint: SOURCE_ID, + sourceWorkload: null, + targetIntentFingerprint: TARGET_INTENT, + targetGeneration: TARGET_GENERATION, + targetLiveIdentityFingerprint: TARGET_ID, + phase, + startedAt: ISO, + updatedAt: ISO, + }; +} + +describe("sandbox recreate recovery from a void journal", () => { + it.each(["deleted", "creating"] as const)( + "keeps refusing durable source-row drift from %s (#10473)", + (phase) => { + expect( + planSandboxRecreateRecovery( + transactionAt(phase), + LIVE_SOURCE, + { + ...REGISTERED_SOURCE_ENTRY, + imageTag: "changed-out-of-band", + }, + JOURNAL_GATEWAY, + ), + ).toMatchObject({ + action: "reject", + reason: expect.stringMatching(/preserved source registry row changed/), + }); + }, + ); + + it.each(["deleted", "creating"] as const)( + "restarts from %s when the preserved row still describes the live source (#10473)", + (phase) => { + expect( + planSandboxRecreateRecovery( + transactionAt(phase), + { state: "not_ready", liveIdentityFingerprint: SOURCE_ID }, + REGISTERED_SOURCE_ENTRY, + JOURNAL_GATEWAY, + ), + ).toEqual({ action: "restart_from_source" }); + }, + ); + + it.each(["planned", "deleting"] as const)( + "still continues source deletion from %s once the source row carries its live identity (#10473)", + (phase) => { + expect( + planSandboxRecreateRecovery( + transactionAt(phase), + LIVE_SOURCE, + REGISTERED_SOURCE_ENTRY, + JOURNAL_GATEWAY, + ), + ).toEqual({ action: "continue_delete" }); + }, + ); + + it.each(["planned", "deleting", "deleted", "creating"] as const)( + "still continues target creation from %s once the source row carries its live identity (#10473)", + (phase) => { + expect( + planSandboxRecreateRecovery( + transactionAt(phase), + ABSENT_SOURCE, + REGISTERED_SOURCE_ENTRY, + JOURNAL_GATEWAY, + ), + ).toEqual({ action: "continue_create" }); + }, + ); + + it("keeps refusing a changed source row while the source stays absent (#10473)", () => { + expect( + planSandboxRecreateRecovery( + transactionAt("deleted"), + ABSENT_SOURCE, + { + ...REGISTERED_SOURCE_ENTRY, + imageTag: "changed-out-of-band", + }, + JOURNAL_GATEWAY, + ), + ).toMatchObject({ + action: "reject", + reason: expect.stringMatching(/preserved source registry row changed/), + }); + }); + + it("keeps refusing an unregistered replacement that holds the source name (#10473)", () => { + expect( + planSandboxRecreateRecovery( + transactionAt("creating"), + { state: "ready", liveIdentityFingerprint: fingerprintSandboxRecreateValue("new-id") }, + REGISTERED_SOURCE_ENTRY, + JOURNAL_GATEWAY, + ), + ).toMatchObject({ action: "reject", reason: expect.stringMatching(/appeared/) }); + }); + + it("keeps refusing a live sandbox the preserved row does not identify (#10473)", () => { + expect( + planSandboxRecreateRecovery( + transactionAt("deleted"), + LIVE_SOURCE, + { + ...REGISTERED_SOURCE_ENTRY, + lifecycleLiveIdentityFingerprint: FOREIGN_ID, + imageTag: "changed-out-of-band", + }, + JOURNAL_GATEWAY, + ), + ).toMatchObject({ + action: "reject", + reason: expect.stringMatching(/preserved source registry row changed/), + }); + }); + + it("keeps refusing a source row that never recorded a live identity (#10473)", () => { + expect( + planSandboxRecreateRecovery( + transactionAt("deleted", SOURCE_ENTRY), + LIVE_SOURCE, + { + ...SOURCE_ENTRY, + imageTag: "changed-out-of-band", + }, + JOURNAL_GATEWAY, + ), + ).toMatchObject({ + action: "reject", + reason: expect.stringMatching(/preserved source registry row changed/), + }); + }); + + it("keeps refusing when the live sandbox is the journaled replacement (#10473)", () => { + expect( + planSandboxRecreateRecovery( + transactionAt("created"), + { state: "ready", liveIdentityFingerprint: TARGET_ID }, + { ...REGISTERED_SOURCE_ENTRY, lifecycleLiveIdentityFingerprint: TARGET_ID }, + JOURNAL_GATEWAY, + ), + ).toMatchObject({ + action: "reject", + reason: expect.stringMatching(/did not commit the journaled generation/), + }); + }); + + it.each(["deleted", "creating"] as const)( + "restarts from %s before the journal records any replacement identity (#10473)", + (phase) => { + expect( + planSandboxRecreateRecovery( + { ...transactionAt(phase), targetLiveIdentityFingerprint: null }, + LIVE_SOURCE, + REGISTERED_SOURCE_ENTRY, + JOURNAL_GATEWAY, + ), + ).toEqual({ action: "restart_from_source" }); + }, + ); + + it("keeps refusing when the journal names another sandbox (#10473)", () => { + expect( + planSandboxRecreateRecovery( + { ...transactionAt("creating"), sandboxName: "beta" }, + LIVE_SOURCE, + REGISTERED_SOURCE_ENTRY, + JOURNAL_GATEWAY, + ), + ).toMatchObject({ action: "reject", reason: expect.stringMatching(/appeared/) }); + }); + + // The journal may still own an unregistered replacement on its own gateway. + // `gatewayName`/`gatewayPort` are excluded from the source fingerprint, so + // nothing else in the planner notices a row that moved gateways, and the + // openers run this before `assertSameTransaction` could refuse (#10473). + it("keeps refusing when the registry row names another gateway (#10473)", () => { + const movedRow = { ...REGISTERED_SOURCE_ENTRY, ...FOREIGN_GATEWAY }; + // The row still satisfies the source-row proof, so only the gateway differs. + expect(fingerprintSandboxRegistryEntry(movedRow)).toBe( + fingerprintSandboxRegistryEntry(REGISTERED_SOURCE_ENTRY), + ); + + expect( + planSandboxRecreateRecovery( + transactionAt("creating"), + LIVE_SOURCE, + movedRow, + FOREIGN_GATEWAY, + ), + ).toMatchObject({ action: "reject" }); + }); + + it("keeps refusing when only the observed gateway differs (#10473)", () => { + expect( + planSandboxRecreateRecovery( + transactionAt("creating"), + LIVE_SOURCE, + REGISTERED_SOURCE_ENTRY, + FOREIGN_GATEWAY, + ), + ).toMatchObject({ action: "reject" }); + }); + + it("keeps refusing when the caller cannot name the observed gateway (#10473)", () => { + expect( + planSandboxRecreateRecovery(transactionAt("creating"), LIVE_SOURCE, REGISTERED_SOURCE_ENTRY), + ).toMatchObject({ action: "reject" }); + }); + + it("resumes a journal recorded before messaging left the fingerprint (#10473)", () => { + const messaging = { + schemaVersion: 1, + plan: { + schemaVersion: 1, + sandboxName: "alpha", + agent: "openclaw", + workflow: "add-channel", + disabledChannels: [], + channels: [{ channelId: "teams", configured: true, disabled: false, active: true }], + }, + }; + const rowWithChannel = { ...REGISTERED_SOURCE_ENTRY, messaging } as unknown as SandboxEntry; + // The pre-#10473 digest covered the same fields plus `messaging`. This + // fixture carries no receipt-bound field, so the projection is explicit. + const legacyFingerprint = fingerprintSandboxRecreateValue({ + name: "alpha", + agent: "openclaw", + openshellDriver: "docker", + imageTag: "openshell/sandbox-from:old", + lifecycleGeneration: SOURCE_GENERATION, + lifecycleLiveIdentityFingerprint: SOURCE_ID, + messaging, + }); + expect(fingerprintSandboxRegistryEntry(rowWithChannel)).not.toBe(legacyFingerprint); + + expect( + planSandboxRecreateRecovery( + { ...transactionAt("deleted"), sourceRegistryFingerprint: legacyFingerprint }, + ABSENT_SOURCE, + rowWithChannel, + JOURNAL_GATEWAY, + ), + ).toEqual({ action: "continue_create" }); + }); + + it("keeps accepting the registered replacement over a restart (#10473)", () => { + expect( + planSandboxRecreateRecovery( + transactionAt("creating"), + { state: "ready", liveIdentityFingerprint: TARGET_ID }, + { + ...REGISTERED_SOURCE_ENTRY, + lifecycleGeneration: TARGET_GENERATION, + lifecycleLiveIdentityFingerprint: TARGET_ID, + }, + JOURNAL_GATEWAY, + ), + ).toEqual({ action: "accept_target" }); + }); +}); + +describe("atomic recreate journal ownership", () => { + function sessionWithTransaction() { + const session = createSession({ sandboxName: "alpha", agent: "openclaw" }); + beginSandboxRecreateTransaction(session, { + sandboxName: "alpha", + gatewayName: JOURNAL_GATEWAY.gatewayName, + gatewayPort: JOURNAL_GATEWAY.gatewayPort, + sourceEntry: REGISTERED_SOURCE_ENTRY, + observation: LIVE_SOURCE, + targetIntentFingerprint: TARGET_INTENT, + id: TX_ID, + targetGeneration: TARGET_GENERATION, + now: ISO, + }); + return session; + } + + function storeFor(session: ReturnType) { + return { + loadSession: () => session, + updateSession: (mutator: (current: typeof session) => typeof session | void) => { + mutator(session); + return session; + }, + compareAndSwapSession: ( + matches: (current: typeof session) => boolean, + mutator: (current: typeof session) => typeof session | void, + ) => { + return matches(session) ? (mutator(session), "updated" as const) : ("mismatch" as const); + }, + }; + } + + it("replaces a void journal without exposing an empty journal (#10473)", () => { + const session = sessionWithTransaction(); + session.checkpoint = { + ...session.checkpoint!, + sandboxRecreate: { ...session.checkpoint!.sandboxRecreate!, phase: "deleted" }, + }; + const seen: Array = []; + const baseStore = storeFor(session); + const owned = ownSandboxRecreateTransaction({ + sessionStore: { + ...baseStore, + compareAndSwapSession: (matches, mutator) => { + return matches(session) + ? (seen.push(session.checkpoint?.sandboxRecreate?.id ?? null), + mutator(session), + seen.push(session.checkpoint?.sandboxRecreate?.id ?? null), + "updated") + : "mismatch"; + }, + }, + sandboxName: "alpha", + ...JOURNAL_GATEWAY, + targetIntentFingerprint: TARGET_INTENT, + readRegistryEntry: () => REGISTERED_SOURCE_ENTRY, + observe: () => LIVE_SOURCE, + decorateCheckpoint: (_current, checkpoint) => checkpoint, + }); + + expect(owned.transaction.id).not.toBe(TX_ID); + expect(seen).toEqual([TX_ID, owned.transaction.id]); + expect(seen).not.toContain(null); + }); + + it("fails closed when the opening session changes before journal ownership (#10473)", () => { + const session = sessionWithTransaction(); + const openingId = session.sessionId; + const baseStore = storeFor(session); + expect(() => + ownSandboxRecreateTransaction({ + sessionStore: { + ...baseStore, + compareAndSwapSession: (matches, mutator) => { + session.sessionId = "replacement-session"; + return matches(session) ? (mutator(session), "updated") : "mismatch"; + }, + }, + sandboxName: "alpha", + ...JOURNAL_GATEWAY, + targetIntentFingerprint: TARGET_INTENT, + readRegistryEntry: () => REGISTERED_SOURCE_ENTRY, + observe: () => LIVE_SOURCE, + decorateCheckpoint: (_current, checkpoint) => checkpoint, + }), + ).toThrow(/session or recreate transaction changed/); + expect(openingId).not.toBe(session.sessionId); + expect(session.checkpoint?.sandboxRecreate?.id).toBe(TX_ID); + }); + + it("fails closed when journal readback differs from the transaction written (#10473)", () => { + const session = sessionWithTransaction(); + const baseStore = storeFor(session); + let loads = 0; + expect(() => + ownSandboxRecreateTransaction({ + sessionStore: { + ...baseStore, + loadSession: () => { + loads += 1; + const transaction = session.checkpoint!.sandboxRecreate!; + return loads < 2 + ? session + : { + ...session, + checkpoint: { + ...session.checkpoint!, + sandboxRecreate: { ...transaction, revision: transaction.revision + 1 }, + }, + }; + }, + }, + sandboxName: "alpha", + ...JOURNAL_GATEWAY, + targetIntentFingerprint: TARGET_INTENT, + readRegistryEntry: () => REGISTERED_SOURCE_ENTRY, + observe: () => LIVE_SOURCE, + decorateCheckpoint: (_current, checkpoint) => checkpoint, + }), + ).toThrow(/Cannot verify sandbox 'alpha' recreate transaction after the write/); + }); + + it.each(["busy", "mismatch"] as const)( + "fails closed when the journal owner CAS returns %s (#10473)", + (result) => { + const session = sessionWithTransaction(); + expect(() => + ownSandboxRecreateTransaction({ + sessionStore: { ...storeFor(session), compareAndSwapSession: () => result }, + sandboxName: "alpha", + ...JOURNAL_GATEWAY, + targetIntentFingerprint: TARGET_INTENT, + readRegistryEntry: () => REGISTERED_SOURCE_ENTRY, + observe: () => LIVE_SOURCE, + decorateCheckpoint: (_current, checkpoint) => checkpoint, + }), + ).toThrow( + result === "busy" ? /owns the session lock/ : /session or recreate transaction changed/, + ); + expect(session.checkpoint?.sandboxRecreate?.id).toBe(TX_ID); + }, + ); + + it("rejects journal replacement when the requested target intent changed (#10473)", () => { + const session = sessionWithTransaction(); + session.checkpoint = { + ...session.checkpoint!, + sandboxRecreate: { ...session.checkpoint!.sandboxRecreate!, phase: "deleted" }, + }; + expect(() => + ownSandboxRecreateTransaction({ + sessionStore: storeFor(session), + sandboxName: "alpha", + ...JOURNAL_GATEWAY, + targetIntentFingerprint: fingerprintSandboxRecreateValue("changed-intent"), + readRegistryEntry: () => REGISTERED_SOURCE_ENTRY, + observe: () => LIVE_SOURCE, + decorateCheckpoint: (_current, checkpoint) => checkpoint, + }), + ).toThrow(/different recreate transaction in progress/); + expect(session.checkpoint?.sandboxRecreate?.id).toBe(TX_ID); + }); + + it("rejects delete when the full transaction changes before CAS (#10473)", () => { + const session = sessionWithTransaction(); + const expected = structuredClone(session.checkpoint!.sandboxRecreate!); + session.checkpoint = { + ...session.checkpoint!, + sandboxRecreate: { + ...session.checkpoint!.sandboxRecreate!, + revision: session.checkpoint!.sandboxRecreate!.revision + 1, + }, + }; + + expect(() => + beginSandboxRecreateDelete({ + sessionStore: storeFor(session), + openingSessionId: session.sessionId, + expectedTransaction: expected, + targetIntentFingerprint: TARGET_INTENT, + readRegistryEntry: () => REGISTERED_SOURCE_ENTRY, + observe: () => LIVE_SOURCE, + }), + ).toThrow(/session or recreate transaction changed/); + expect(session.checkpoint?.sandboxRecreate?.phase).toBe("planned"); + }); + + it("rejects delete when the target intent differs from the current journal (#10473)", () => { + const session = sessionWithTransaction(); + const expected = structuredClone(session.checkpoint!.sandboxRecreate!); + expect(() => + beginSandboxRecreateDelete({ + sessionStore: storeFor(session), + openingSessionId: session.sessionId, + expectedTransaction: expected, + targetIntentFingerprint: fingerprintSandboxRecreateValue("changed-intent"), + readRegistryEntry: () => REGISTERED_SOURCE_ENTRY, + observe: () => LIVE_SOURCE, + }), + ).toThrow(/session or recreate transaction changed/); + expect(session.checkpoint?.sandboxRecreate?.phase).toBe("planned"); + }); + + it.each([ + ["registry row", { ...REGISTERED_SOURCE_ENTRY, imageTag: "foreign" }, LIVE_SOURCE], + [ + "registry gateway", + { ...REGISTERED_SOURCE_ENTRY, gatewayName: "foreign", gatewayPort: 9090 }, + LIVE_SOURCE, + ], + [ + "live identity", + REGISTERED_SOURCE_ENTRY, + { state: "ready", liveIdentityFingerprint: FOREIGN_ID }, + ], + ] as const)("rejects delete after fresh %s drift (#10473)", (_label, row, observation) => { + const session = sessionWithTransaction(); + const expected = structuredClone(session.checkpoint!.sandboxRecreate!); + expect(() => + beginSandboxRecreateDelete({ + sessionStore: storeFor(session), + openingSessionId: session.sessionId, + expectedTransaction: expected, + targetIntentFingerprint: TARGET_INTENT, + readRegistryEntry: () => row as SandboxEntry, + observe: () => observation, + }), + ).toThrow(/registry row changed|gateway authority changed|not the journaled source/); + expect(session.checkpoint?.sandboxRecreate?.phase).toBe("planned"); + }); +}); + +describe("source registry fingerprint across channel mutations", () => { + afterEach(() => { + vi.unstubAllEnvs(); + vi.resetModules(); + }); + + it("survives a channel the operator stops and starts between rebuilds (#10473)", async () => { + const home = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-void-journal-")); + vi.stubEnv("HOME", home); + vi.resetModules(); + try { + const registry = await import("../state/registry"); + // The writer `channels stop` and `channels start` actually use. + const { persistManifestChannelDisabledPlan } = + await import("../actions/sandbox/policy-channel"); + registry.registerSandbox({ + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + gatewayPort: 8080, + imageTag: "nemoclaw/openclaw:2026.3.11", + messaging: { + schemaVersion: 1, + plan: { + schemaVersion: 1, + sandboxName: "alpha", + agent: "openclaw", + workflow: "add-channel", + disabledChannels: [], + channels: [{ channelId: "teams", configured: true, disabled: false, active: true }], + }, + }, + } as unknown as SandboxEntry); + const initialRow = registry.getSandbox("alpha") as SandboxEntry; + const session = createSession({ sandboxName: "alpha", agent: "openclaw" }); + beginSandboxRecreateTransaction(session, { + sandboxName: "alpha", + gatewayName: "nemoclaw", + gatewayPort: 8080, + sourceEntry: initialRow, + observation: LIVE_SOURCE, + targetIntentFingerprint: TARGET_INTENT, + id: TX_ID, + targetGeneration: TARGET_GENERATION, + now: ISO, + }); + const transaction = structuredClone(session.checkpoint!.sandboxRecreate!); + + expect(await persistManifestChannelDisabledPlan("alpha", "teams", true)).not.toBeNull(); + expect(registry.getDisabledChannels("alpha")).toEqual(["teams"]); + expect(await persistManifestChannelDisabledPlan("alpha", "teams", false)).not.toBeNull(); + expect(registry.getDisabledChannels("alpha")).toEqual([]); + + const restarted = registry.getSandbox("alpha") as SandboxEntry; + expect(restarted.messaging?.plan.workflow).toBe("start-channel"); + expect( + planSandboxRecreateRecovery(transaction, LIVE_SOURCE, restarted, { + gatewayName: "nemoclaw", + gatewayPort: 8080, + }), + ).toEqual({ action: "continue_delete" }); + } finally { + await fs.rm(home, { recursive: true, force: true }); + } + }); +}); diff --git a/test/helpers/rebuild-flow-generic-harness.ts b/test/helpers/rebuild-flow-generic-harness.ts index 380e4df25f4..87bc36c5106 100644 --- a/test/helpers/rebuild-flow-generic-harness.ts +++ b/test/helpers/rebuild-flow-generic-harness.ts @@ -388,6 +388,13 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): (mutator as (value: typeof session) => typeof session | void)(session); return session; }); + vi.spyOn(onboardSession, "compareAndSwapSession").mockImplementation((...args: unknown[]) => { + const [matches, mutator] = args as [ + (current: typeof session) => boolean, + (current: typeof session) => unknown, + ]; + return matches(session) ? (mutator(session), "updated") : "mismatch"; + }); const releaseOnboardLockSpy = vi .spyOn(onboardSession, "releaseOnboardLock") .mockImplementation(() => undefined); diff --git a/test/mcp/mcp-destroy-lifecycle.test.ts b/test/mcp/mcp-destroy-lifecycle.test.ts index 563b84fd84c..31929042ffe 100644 --- a/test/mcp/mcp-destroy-lifecycle.test.ts +++ b/test/mcp/mcp-destroy-lifecycle.test.ts @@ -120,8 +120,7 @@ function stubRecreateJournal(): RebuildRecreateJournal { }, targetGeneration: "generation-1", targetIntentFingerprint: "intent-1", - markDeleting: vi.fn(), - observeSourceForDelete: vi.fn(() => "source" as const), + beginDelete: vi.fn(() => "source" as const), confirmDeleted: vi.fn(), completeAcceptedTarget: vi.fn(), };