From 3c28a15eedbd03e0b1d6c1c354a1e8642db61d97 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Sun, 2 Aug 2026 09:39:43 -0700 Subject: [PATCH 1/4] chore(managed-bootstrap): checkpoint cleanup recovery FSM Signed-off-by: Aaron Erickson --- .../onboard/managed-bootstrap/adapter.test.ts | 147 +++++++++++++-- src/lib/onboard/managed-bootstrap/adapter.ts | 147 +++++++++++++-- .../managed-bootstrap/docker-journal.test.ts | 36 ++-- .../managed-bootstrap/docker-journal.ts | 38 ++-- .../managed-bootstrap/docker-test-fixture.ts | 28 ++- src/lib/onboard/managed-bootstrap/docker.ts | 173 +++++++++++++++--- src/lib/onboard/managed-bootstrap/index.ts | 4 + .../managed-bootstrap/runtime-create.ts | 4 +- .../runtime-provider-contract.test.ts | 2 +- .../onboard/sandbox-gpu-create-flow.test.ts | 42 ++++- .../onboard/sandbox-gpu-create-run-attempt.ts | 8 +- 11 files changed, 544 insertions(+), 85 deletions(-) diff --git a/src/lib/onboard/managed-bootstrap/adapter.test.ts b/src/lib/onboard/managed-bootstrap/adapter.test.ts index 666dfdcc317..90665185c4f 100644 --- a/src/lib/onboard/managed-bootstrap/adapter.test.ts +++ b/src/lib/onboard/managed-bootstrap/adapter.test.ts @@ -13,6 +13,7 @@ import { import { createManagedStartupRootApplyRequest } from "../managed-startup/root-apply"; import { activateManagedBootstrapSequence, + enforceManagedBootstrapRecoveryForSandbox, finalizeManagedBootstrapSequence, MANAGED_BOOTSTRAP_SCHEMA_VERSION, type ManagedBootstrapAdapter, @@ -24,6 +25,7 @@ import { type ManagedBootstrapHeldWorkloadHandle, type ManagedBootstrapObservedSnapshot, type ManagedBootstrapPreparedReplacementHandle, + ManagedBootstrapRecoveryBlockedError, type ManagedBootstrapReplacementHandle, prepareManagedBootstrapSequence, recoverManagedBootstrapTransactions, @@ -235,7 +237,7 @@ function adapterFor(agent: ManagedStartupAgent): Fixture { const order: string[] = []; const raw: Fixture["raw"] = { handle: null, snapshot: null, prepared: null }; const adapter: ManagedBootstrapAdapter = { - recoverUnfinishedTransactions: vi.fn(async () => []), + recoverUnfinishedTransactions: vi.fn(async () => ({ receipts: [], failures: [] })), createHeldWorkload: vi.fn(async (input) => { order.push("create"); const receipt = await input.launch({ @@ -717,41 +719,150 @@ describe("managed bootstrap adapter contract", () => { outcome: "rolled-back" as const, finalization: { ...receipt, bootstrapIdentity }, }); - vi.mocked(fixture.adapter.recoverUnfinishedTransactions).mockResolvedValueOnce([ - candidate("b".repeat(64)), - candidate("a".repeat(64)), - ]); + vi.mocked(fixture.adapter.recoverUnfinishedTransactions).mockResolvedValueOnce({ + receipts: [candidate("b".repeat(64)), candidate("a".repeat(64))], + failures: [], + }); const recovered = await recoverManagedBootstrapTransactions(fixture.adapter); - expect(recovered.map(({ bootstrapIdentity }) => bootstrapIdentity)).toEqual([ + expect(recovered.receipts.map(({ bootstrapIdentity }) => bootstrapIdentity)).toEqual([ "a".repeat(64), "b".repeat(64), ]); expect(Object.isFrozen(recovered)).toBe(true); - expect(recovered.every((entry) => Object.isFrozen(entry.finalization))).toBe(true); + expect(Object.isFrozen(recovered.receipts)).toBe(true); + expect(recovered.receipts.every((entry) => Object.isFrozen(entry.finalization))).toBe(true); }); it("rejects recovery evidence whose provider does not own the durable sandbox", async () => { const fixture = adapterFor("openclaw"); const receipt = cleanupReceipt(); - vi.mocked(fixture.adapter.recoverUnfinishedTransactions).mockResolvedValueOnce([ - { - schemaVersion: MANAGED_BOOTSTRAP_SCHEMA_VERSION, - providerId: "mxc", - sourcePhase: "cutover", - sandbox: receipt.sandbox, - bootstrapIdentity: IDENTITY, - outcome: "rolled-back", - finalization: receipt, - }, - ]); + vi.mocked(fixture.adapter.recoverUnfinishedTransactions).mockResolvedValueOnce({ + receipts: [ + { + schemaVersion: MANAGED_BOOTSTRAP_SCHEMA_VERSION, + providerId: "mxc", + sourcePhase: "cutover", + sandbox: receipt.sandbox, + bootstrapIdentity: IDENTITY, + outcome: "rolled-back", + finalization: receipt, + }, + ], + failures: [], + }); await expect(recoverManagedBootstrapTransactions(fixture.adapter)).rejects.toThrow( "recovery provider does not own", ); }); + it("normalizes provider-neutral failures and preserves bounded MXC-style diagnostics", async () => { + const fixture = adapterFor("hermes"); + const failure = (bootstrapIdentity: string, sandboxName: string | null) => ({ + schemaVersion: MANAGED_BOOTSTRAP_SCHEMA_VERSION, + providerId: "mxc", + sourcePhase: "provider-owned-cleanup", + sandbox: + sandboxName === null + ? null + : { sandboxName, sandboxId: `mxc-${sandboxName}`, driverId: "mxc" }, + bootstrapIdentity, + code: "provider-owned-retry", + retryable: true, + detail: "opaque MXC recovery evidence", + }); + vi.mocked(fixture.adapter.recoverUnfinishedTransactions).mockResolvedValueOnce({ + receipts: [], + failures: [failure("b".repeat(64), "bravo"), failure("a".repeat(64), null)], + }); + + const recovered = await recoverManagedBootstrapTransactions(fixture.adapter); + + expect(recovered.failures.map(({ bootstrapIdentity }) => bootstrapIdentity)).toEqual([ + "a".repeat(64), + "b".repeat(64), + ]); + expect(recovered.failures[0]).toMatchObject({ sandbox: null, providerId: "mxc" }); + expect(Object.isFrozen(recovered.failures)).toBe(true); + expect(recovered.failures.every(Object.isFrozen)).toBe(true); + }); + + it("rejects duplicate identities across recovered receipts and failures", async () => { + const fixture = adapterFor("openclaw"); + const receipt = cleanupReceipt(); + vi.mocked(fixture.adapter.recoverUnfinishedTransactions).mockResolvedValueOnce({ + receipts: [ + { + schemaVersion: MANAGED_BOOTSTRAP_SCHEMA_VERSION, + providerId: receipt.sandbox.driverId, + sourcePhase: "cutover", + sandbox: receipt.sandbox, + bootstrapIdentity: IDENTITY, + outcome: "rolled-back", + finalization: receipt, + }, + ], + failures: [ + { + schemaVersion: MANAGED_BOOTSTRAP_SCHEMA_VERSION, + providerId: receipt.sandbox.driverId, + sourcePhase: "cleanup", + sandbox: receipt.sandbox, + bootstrapIdentity: IDENTITY, + code: "retry", + retryable: true, + detail: "retained", + }, + ], + }); + + await expect(recoverManagedBootstrapTransactions(fixture.adapter)).rejects.toThrow( + "duplicate bootstrap identities", + ); + }); + + it("blocks same-name and identity-unknown failures while warning for unrelated sandboxes", () => { + const failure = (bootstrapIdentity: string, sandboxName: string | null) => + Object.freeze({ + schemaVersion: MANAGED_BOOTSTRAP_SCHEMA_VERSION, + providerId: "mxc", + sourcePhase: "cleanup", + sandbox: + sandboxName === null + ? null + : Object.freeze({ sandboxName, sandboxId: `mxc-${sandboxName}`, driverId: "mxc" }), + bootstrapIdentity, + code: "provider-owned-retry", + retryable: true, + detail: "opaque provider detail", + }); + const warn = vi.fn(); + const unrelated = failure("a".repeat(64), "bravo"); + const sameName = failure("b".repeat(64), "alpha"); + const identityUnknown = failure("c".repeat(64), null); + + expect( + enforceManagedBootstrapRecoveryForSandbox( + Object.freeze({ receipts: Object.freeze([]), failures: Object.freeze([unrelated]) }), + "alpha", + warn, + ), + ).toMatchObject({ failures: [unrelated] }); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("unrelated sandbox 'bravo'")); + + for (const blocking of [sameName, identityUnknown]) { + expect(() => + enforceManagedBootstrapRecoveryForSandbox( + Object.freeze({ receipts: Object.freeze([]), failures: Object.freeze([blocking]) }), + "alpha", + warn, + ), + ).toThrow(ManagedBootstrapRecoveryBlockedError); + } + }); + it.each([ "BASH_ENV=/sandbox/attacker", "ENV=/sandbox/attacker", diff --git a/src/lib/onboard/managed-bootstrap/adapter.ts b/src/lib/onboard/managed-bootstrap/adapter.ts index a1ca17f983f..b5e441b5d8f 100644 --- a/src/lib/onboard/managed-bootstrap/adapter.ts +++ b/src/lib/onboard/managed-bootstrap/adapter.ts @@ -250,6 +250,27 @@ export interface ManagedBootstrapRecoveryReceipt { readonly finalization: ManagedBootstrapFinalizationReceipt; } +/** Bounded provider-owned evidence that one durable transaction still needs attention. */ +export interface ManagedBootstrapRecoveryFailure { + readonly schemaVersion: typeof MANAGED_BOOTSTRAP_SCHEMA_VERSION; + readonly providerId: string; + /** Null when the durable record could not prove its provider-owned phase. */ + readonly sourcePhase: string | null; + /** Null when the durable record could not prove its sandbox identity. */ + readonly sandbox: ManagedBootstrapSandboxIdentity | null; + readonly bootstrapIdentity: string; + /** Provider-owned diagnostic code. Central orchestration must not branch on this value. */ + readonly code: string; + readonly retryable: boolean; + readonly detail: string; +} + +/** Lossless provider-neutral recovery output for one bounded enumeration pass. */ +export interface ManagedBootstrapRecoveryReport { + readonly receipts: readonly ManagedBootstrapRecoveryReceipt[]; + readonly failures: readonly ManagedBootstrapRecoveryFailure[]; +} + export class ManagedBootstrapDurableCommitCleanupPendingError extends Error { readonly bootstrapIdentity: string; readonly cleanupRuntimeId: string; @@ -308,6 +329,25 @@ export class ManagedBootstrapOwnerCleanupRequiredError extends Error { } } +export class ManagedBootstrapRecoveryBlockedError extends Error { + readonly sandboxName: string; + readonly failures: readonly ManagedBootstrapRecoveryFailure[]; + + constructor(sandboxName: string, failures: readonly ManagedBootstrapRecoveryFailure[]) { + const first = failures[0]; + super( + `Managed bootstrap recovery blocks sandbox '${sandboxName}' because ${String( + failures.length, + )} durable transaction${failures.length === 1 ? "" : "s"} still need attention.${ + first ? ` First failure ${first.bootstrapIdentity} (${first.code}): ${first.detail}` : "" + }`, + ); + this.name = "ManagedBootstrapRecoveryBlockedError"; + this.sandboxName = sandboxName; + this.failures = Object.freeze([...failures]); + } +} + export function attachManagedBootstrapRollbackError(failure: Error, rollbackError: unknown): void { ( failure as Error & { @@ -325,7 +365,7 @@ export interface ManagedBootstrapAdapter { * Enumerate durable unfinished records and reconcile each through the owning * provider. Implementations must be restart-safe and idempotent. */ - recoverUnfinishedTransactions(): Promise; + recoverUnfinishedTransactions(): Promise; /** Return only after one durable sandbox/driver identity reports Ready. */ createHeldWorkload( @@ -454,24 +494,103 @@ function normalizeRecoveryReceipt( }); } +function normalizeRecoveryFailure( + candidate: ManagedBootstrapRecoveryFailure, +): ManagedBootstrapRecoveryFailure { + if ( + typeof candidate !== "object" || + candidate === null || + Array.isArray(candidate) || + candidate.schemaVersion !== MANAGED_BOOTSTRAP_SCHEMA_VERSION || + typeof candidate.retryable !== "boolean" + ) { + protocolFail("recovery failure has an invalid schema"); + } + assertOpaqueString(candidate.providerId, "recovery failure provider ID", 256); + if (candidate.sourcePhase !== null) { + assertOpaqueString(candidate.sourcePhase, "recovery failure source phase", 256); + } + if (candidate.sandbox !== null) { + assertSandboxIdentity(candidate.sandbox); + if (candidate.sandbox.driverId !== candidate.providerId) { + protocolFail("recovery failure provider does not own the durable sandbox"); + } + } + if (!SHA256_RE.test(candidate.bootstrapIdentity)) { + protocolFail("recovery failure bootstrap identity must be lowercase SHA-256"); + } + assertOpaqueString(candidate.code, "recovery failure code", 256); + assertOpaqueString(candidate.detail, "recovery failure detail", 8 * 1024); + return Object.freeze({ + schemaVersion: MANAGED_BOOTSTRAP_SCHEMA_VERSION, + providerId: candidate.providerId, + sourcePhase: candidate.sourcePhase, + sandbox: candidate.sandbox === null ? null : Object.freeze({ ...candidate.sandbox }), + bootstrapIdentity: candidate.bootstrapIdentity, + code: candidate.code, + retryable: candidate.retryable, + detail: candidate.detail, + }); +} + /** Recover process-orphaned work without relying on coordinator WeakMap state. */ export async function recoverManagedBootstrapTransactions( adapter: ManagedBootstrapAdapter, -): Promise { +): Promise { const candidates = await adapter.recoverUnfinishedTransactions(); - if (!Array.isArray(candidates)) { - protocolFail("provider recovery must return a receipt array"); + if ( + typeof candidates !== "object" || + candidates === null || + Array.isArray(candidates) || + !Array.isArray(candidates.receipts) || + !Array.isArray(candidates.failures) + ) { + protocolFail("provider recovery must return bounded receipt and failure arrays"); } - const receipts = candidates.map(normalizeRecoveryReceipt); - const identities = receipts.map(({ bootstrapIdentity }) => bootstrapIdentity); + const receipts = candidates.receipts.map(normalizeRecoveryReceipt); + const failures = candidates.failures.map(normalizeRecoveryFailure); + const identities = [...receipts, ...failures].map(({ bootstrapIdentity }) => bootstrapIdentity); if (new Set(identities).size !== identities.length) { protocolFail("provider recovery returned duplicate bootstrap identities"); } - return Object.freeze( - [...receipts].sort((left, right) => - left.bootstrapIdentity.localeCompare(right.bootstrapIdentity), - ), + const byBootstrapIdentity = ( + left: ManagedBootstrapRecoveryReceipt | ManagedBootstrapRecoveryFailure, + right: ManagedBootstrapRecoveryReceipt | ManagedBootstrapRecoveryFailure, + ) => left.bootstrapIdentity.localeCompare(right.bootstrapIdentity); + return Object.freeze({ + receipts: Object.freeze([...receipts].sort(byBootstrapIdentity)), + failures: Object.freeze([...failures].sort(byBootstrapIdentity)), + }); +} + +/** Block only failures that can own the requested name; warn for exact unrelated sandboxes. */ +export function enforceManagedBootstrapRecoveryForSandbox( + report: ManagedBootstrapRecoveryReport, + sandboxName: string, + warn: (message: string) => void, +): ManagedBootstrapRecoveryReport { + assertOpaqueString(sandboxName, "recovery target sandbox name"); + const blocking = report.failures.filter( + (failure) => failure.sandbox === null || failure.sandbox.sandboxName === sandboxName, ); + for (const failure of report.failures) { + if (failure.sandbox === null || failure.sandbox.sandboxName === sandboxName) continue; + warn( + `Managed bootstrap recovery retained unrelated sandbox '${failure.sandbox.sandboxName}' ` + + `(${failure.bootstrapIdentity}, ${failure.code}).`, + ); + } + if (blocking.length > 0) { + throw new ManagedBootstrapRecoveryBlockedError( + sandboxName, + Object.freeze( + [...blocking].sort((left, right) => + left.bootstrapIdentity.localeCompare(right.bootstrapIdentity), + ), + ), + ); + } + return report; } export interface ManagedBootstrapPreparationInput { @@ -502,12 +621,16 @@ function protocolFail(message: string): never { throw new Error(`Managed bootstrap protocol violation: ${message}`); } -function assertOpaqueString(value: unknown, label: string): asserts value is string { +function assertOpaqueString( + value: unknown, + label: string, + maxBytes = 64 * 1024, +): asserts value is string { if ( typeof value !== "string" || value.length === 0 || value.includes("\0") || - Buffer.byteLength(value, "utf8") > 64 * 1024 + Buffer.byteLength(value, "utf8") > maxBytes ) { protocolFail(`${label} must be one bounded non-empty string`); } diff --git a/src/lib/onboard/managed-bootstrap/docker-journal.test.ts b/src/lib/onboard/managed-bootstrap/docker-journal.test.ts index 96f20db72bf..dc889bbbf87 100644 --- a/src/lib/onboard/managed-bootstrap/docker-journal.test.ts +++ b/src/lib/onboard/managed-bootstrap/docker-journal.test.ts @@ -15,6 +15,7 @@ import { type DockerManagedBootstrapFinalizationContext, type DockerManagedBootstrapFinalizationRecord, type DockerManagedBootstrapJournal, + type DockerManagedBootstrapJournalStore, DockerManagedBootstrapLegacyRecordRequiresAgentError, parseDockerManagedBootstrapFinalizationRecord, parseDockerManagedBootstrapJournal, @@ -30,6 +31,16 @@ function reverseKeys(value: T): T { return Object.fromEntries(Object.entries(value).reverse()) as T; } +function loadUnfinished( + store: DockerManagedBootstrapJournalStore, +): readonly DockerManagedBootstrapJournal[] { + return store.listUnfinishedIdentities().map((identity) => { + const record = store.load(identity); + if (!record) throw new Error(`enumerated journal ${identity} disappeared`); + return record; + }); +} + const journal = Object.freeze({ schemaVersion: DOCKER_MANAGED_BOOTSTRAP_JOURNAL_SCHEMA_VERSION, phase: "staged", @@ -318,12 +329,12 @@ describe("Docker managed bootstrap journal", () => { roots.push(root); const first = createFileDockerManagedBootstrapJournalStore(root); first.create(journal); - expect(first.listUnfinished()).toEqual([journal]); + expect(loadUnfinished(first)).toEqual([journal]); first.recordFinalization(finalization); - expect(first.listUnfinished()).toEqual([journal]); + expect(loadUnfinished(first)).toEqual([journal]); first.remove(IDENTITY, ["staged"]); - expect(first.listUnfinished()).toEqual([]); + expect(loadUnfinished(first)).toEqual([]); const restarted = createFileDockerManagedBootstrapJournalStore(root); expect(restarted.loadFinalization(IDENTITY)).toEqual(finalization); expect( @@ -349,7 +360,7 @@ describe("Docker managed bootstrap journal", () => { expect(completed.commitReceipt).toEqual(finalization.commitReceipt); const restarted = createFileDockerManagedBootstrapJournalStore(root); - expect(restarted.listUnfinished()).toEqual([completed]); + expect(loadUnfinished(restarted)).toEqual([completed]); const reorderedReceipt = reverseKeys({ ...finalization.commitReceipt, image: reverseKeys({ ...finalization.commitReceipt.image }), @@ -378,7 +389,7 @@ describe("Docker managed bootstrap journal", () => { for (const name of leftovers) fs.writeFileSync(path.join(directory, name), "orphan\n", { mode: 0o600 }); - expect(store.listUnfinished()).toEqual([journal]); + expect(loadUnfinished(store)).toEqual([journal]); for (const name of leftovers) expect(fs.existsSync(path.join(directory, name))).toBe(true); }); @@ -392,11 +403,11 @@ describe("Docker managed bootstrap journal", () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-docker-journal-")); roots.push(root); const store = createFileDockerManagedBootstrapJournalStore(root); - expect(store.listUnfinished()).toEqual([]); + expect(loadUnfinished(store)).toEqual([]); const target = path.join(root, DOCKER_MANAGED_BOOTSTRAP_JOURNAL_DIRECTORY, name); fs.writeFileSync(target, "near miss\n", { mode: 0o600 }); - expect(() => store.listUnfinished()).toThrow("unsupported entry"); + expect(() => store.listUnfinishedIdentities()).toThrow("unsupported entry"); expect(fs.existsSync(target)).toBe(true); }); @@ -421,10 +432,11 @@ describe("Docker managed bootstrap journal", () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-docker-journal-")); roots.push(root); const store = createFileDockerManagedBootstrapJournalStore(root); - expect(store.listUnfinished()).toEqual([]); + expect(loadUnfinished(store)).toEqual([]); const target = path.join(root, DOCKER_MANAGED_BOOTSTRAP_JOURNAL_DIRECTORY, `${IDENTITY}.json`); fs.writeFileSync(target, serialized, { mode: 0o600 }); - expect(() => store.listUnfinished()).toThrowError( + expect(store.listUnfinishedIdentities()).toEqual([IDENTITY]); + expect(() => store.load(IDENTITY)).toThrowError( DockerManagedBootstrapLegacyRecordRequiresAgentError, ); expect(readPinnedPrivateFile(target).text).toBe(serialized); @@ -460,7 +472,7 @@ describe("Docker managed bootstrap journal", () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-docker-journal-")); roots.push(root); const store = createFileDockerManagedBootstrapJournalStore(root); - expect(store.listUnfinished()).toEqual([]); + expect(loadUnfinished(store)).toEqual([]); const target = path.join( root, DOCKER_MANAGED_BOOTSTRAP_JOURNAL_DIRECTORY, @@ -496,7 +508,7 @@ describe("Docker managed bootstrap journal", () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-docker-journal-")); roots.push(root); const store = createFileDockerManagedBootstrapJournalStore(root); - expect(store.listUnfinished()).toEqual([]); + expect(loadUnfinished(store)).toEqual([]); const directory = path.join(root, DOCKER_MANAGED_BOOTSTRAP_JOURNAL_DIRECTORY); const misplacedJournal = path.join(directory, `${OTHER_IDENTITY}.json`); const misplacedFinalization = `${misplacedJournal}.finalized`; @@ -529,6 +541,6 @@ describe("Docker managed bootstrap journal", () => { "{}\n", { mode: 0o600 }, ); - expect(() => store.listUnfinished()).toThrow("unsupported entry"); + expect(() => store.listUnfinishedIdentities()).toThrow("unsupported entry"); }); }); diff --git a/src/lib/onboard/managed-bootstrap/docker-journal.ts b/src/lib/onboard/managed-bootstrap/docker-journal.ts index 9b4670196d6..240a1ef5362 100644 --- a/src/lib/onboard/managed-bootstrap/docker-journal.ts +++ b/src/lib/onboard/managed-bootstrap/docker-journal.ts @@ -29,6 +29,7 @@ export type DockerManagedBootstrapJournalPhase = | "staged" | "cutover" | "rollback-authorized" + | "owner-cleanup-required" | "shared-state-committed"; export interface DockerManagedBootstrapJournal { @@ -83,7 +84,7 @@ export type DockerManagedBootstrapFinalizationContext = Pick< export interface DockerManagedBootstrapJournalStore { create(journal: DockerManagedBootstrapJournal): void; load(bootstrapIdentity: string): DockerManagedBootstrapJournal | null; - listUnfinished(): readonly DockerManagedBootstrapJournal[]; + listUnfinishedIdentities(): readonly string[]; transition( bootstrapIdentity: string, expected: DockerManagedBootstrapJournalPhase, @@ -148,8 +149,10 @@ class DockerManagedBootstrapJournalExistsError extends Error { const ALLOWED_TRANSITIONS = new Set([ "staged->cutover", + "staged->owner-cleanup-required", "cutover->rollback-authorized", "cutover->shared-state-committed", + "rollback-authorized->owner-cleanup-required", ]); function fail(message: string): never { @@ -182,13 +185,30 @@ function exactSha256(value: unknown, label: string): string { function exactPhase(value: unknown): DockerManagedBootstrapJournalPhase { if ( - !["staged", "cutover", "rollback-authorized", "shared-state-committed"].includes(String(value)) + ![ + "staged", + "cutover", + "rollback-authorized", + "owner-cleanup-required", + "shared-state-committed", + ].includes(String(value)) ) { fail("phase is unsupported"); } return value as DockerManagedBootstrapJournalPhase; } +function exactLegacyPhase( + value: unknown, +): Exclude { + if ( + !["staged", "cutover", "rollback-authorized", "shared-state-committed"].includes(String(value)) + ) { + fail("legacy phase is unsupported"); + } + return value as Exclude; +} + function exactAgent(value: unknown): ManagedStartupAgent { if (!["openclaw", "hermes", "langchain-deepagents-code"].includes(String(value))) { fail("agent is unsupported"); @@ -246,7 +266,7 @@ function normalizeLegacyDockerManagedBootstrapJournal( if (!hasExactKeys(journal, expectedKeys)) fail("legacy journal schema is invalid"); const normalized = Object.freeze({ schemaVersion: 1 as const, - phase: exactPhase(journal.phase), + phase: exactLegacyPhase(journal.phase), bootstrapIdentity: exactSha256(journal.bootstrapIdentity, "bootstrap identity"), sandbox: exactSandbox(journal.sandbox), profileFingerprint: exactSha256(journal.profileFingerprint, "profile fingerprint"), @@ -304,7 +324,7 @@ function normalizeLegacyDockerManagedBootstrapJournal( if (!hasExactKeys(journal, expectedKeys)) fail("legacy journal schema is invalid"); const normalized = Object.freeze({ schemaVersion: 2 as const, - phase: exactPhase(journal.phase), + phase: exactLegacyPhase(journal.phase), bootstrapIdentity: exactSha256(journal.bootstrapIdentity, "bootstrap identity"), providerId: exactString(journal.providerId, "provider ID"), sandbox: exactSandbox(journal.sandbox), @@ -1169,7 +1189,7 @@ export function createFileDockerManagedBootstrapJournalStore( atomicWrite(directory, target, serializeDockerManagedBootstrapJournal(normalized), true); }, load, - listUnfinished() { + listUnfinishedIdentities() { assertDirectory(directory); const identities: string[] = []; for (const name of fs.readdirSync(directory)) { @@ -1186,13 +1206,7 @@ export function createFileDockerManagedBootstrapJournalStore( } fail(`journal directory contains an unsupported entry: ${name}`); } - return Object.freeze( - identities.sort().map((identity) => { - const journal = load(identity); - if (!journal) fail(`enumerated journal ${identity} disappeared`); - return journal; - }), - ); + return Object.freeze(identities.sort()); }, transition( bootstrapIdentity: string, diff --git a/src/lib/onboard/managed-bootstrap/docker-test-fixture.ts b/src/lib/onboard/managed-bootstrap/docker-test-fixture.ts index b3f53a1e7b2..52f5aeff499 100644 --- a/src/lib/onboard/managed-bootstrap/docker-test-fixture.ts +++ b/src/lib/onboard/managed-bootstrap/docker-test-fixture.ts @@ -61,6 +61,7 @@ export type DockerFixtureAcknowledgement = | "journal:create" | "journal:cutover" | "journal:completion" + | "journal:owner-cleanup-required" | "journal:remove" | "journal:rollback-authorized" | "journal:staged" @@ -69,6 +70,7 @@ export type DockerFixtureAcknowledgement = export type DockerFixtureOptions = { readonly agent?: ManagedStartupAgent; readonly dockerRemoveFailures?: readonly Error[]; + readonly dockerInspectUnknownIds?: readonly string[]; readonly dockerStartResults?: Readonly>; readonly journalCreateFailures?: readonly Error[]; readonly journalRemoveFailures?: readonly Error[]; @@ -76,8 +78,10 @@ export type DockerFixtureOptions = { Readonly> >; readonly lostAcknowledgements?: readonly DockerFixtureAcknowledgement[]; - readonly ownerId?: string; + readonly ownerId?: string | null; + readonly ownerLookupError?: Error; readonly sharedState?: "committed" | "none" | "pending"; + readonly sharedReceiptClearFailures?: readonly Error[]; }; function agentInputs(agent: ManagedStartupAgent = "hermes") { @@ -222,6 +226,8 @@ export function fixture(options: DockerFixtureOptions = {}) { const dockerRemoveFailures = [...(options.dockerRemoveFailures ?? [])]; const journalCreateFailures = [...(options.journalCreateFailures ?? [])]; const journalRemoveFailures = [...(options.journalRemoveFailures ?? [])]; + const sharedReceiptClearFailures = [...(options.sharedReceiptClearFailures ?? [])]; + const dockerInspectUnknownIds = new Set(options.dockerInspectUnknownIds ?? []); const lostAcknowledgements = new Set(options.lostAcknowledgements ?? []); const losesAcknowledgement = (operation: DockerFixtureAcknowledgement) => lostAcknowledgements.has(operation); @@ -245,7 +251,7 @@ export function fixture(options: DockerFixtureOptions = {}) { } }, load: () => copyJournal(), - listUnfinished: () => (journal ? [structuredClone(journal)] : []), + listUnfinishedIdentities: () => (journal ? [journal.bootstrapIdentity] : []), transition(_identity, expected, next) { const current = journal !== null && journal.phase === expected @@ -364,6 +370,9 @@ export function fixture(options: DockerFixtureOptions = {}) { return ok(original ? OLD_ID : ""); case "inspect": { const id = String(args[3] ?? ""); + if (dockerInspectUnknownIds.has(id)) { + return { status: 1, stderr: `injected unknown inspect state for ${id}` }; + } try { inspect(id); return ok(`[{"Id":"${id}"}]`); @@ -426,6 +435,10 @@ export function fixture(options: DockerFixtureOptions = {}) { events.push("shared:commit"); return ok(); case args.includes("--clear-shared-state-commit-receipt"): + { + const injectedFailure = sharedReceiptClearFailures.shift(); + if (injectedFailure) throw injectedFailure; + } sharedState = "none"; events.push("shared:clear"); return ok(); @@ -500,7 +513,12 @@ export function fixture(options: DockerFixtureOptions = {}) { ? { status: 1, stderr: "lost rm acknowledgement" } : ok(); }), - runCaptureOpenshell: vi.fn(() => `Name: alpha\nID: ${options.ownerId ?? "sandbox-alpha"}\n`), + runCaptureOpenshell: vi.fn(() => { + if (options.ownerLookupError) throw options.ownerLookupError; + return options.ownerId === null + ? "Name: alpha\n" + : `Name: alpha\nID: ${options.ownerId ?? "sandbox-alpha"}\n`; + }), runOpenshell: vi.fn(() => ok()), now: () => new Date("2026-07-31T12:30:00.000Z"), }; @@ -522,6 +540,10 @@ export function fixture(options: DockerFixtureOptions = {}) { get sharedState() { return sharedState; }, + removeOriginalExternally() { + original = null as unknown as DockerContainerInspect; + events.push(`external-rm:${OLD_ID}`); + }, }; } diff --git a/src/lib/onboard/managed-bootstrap/docker.ts b/src/lib/onboard/managed-bootstrap/docker.ts index fe1fdf0787a..6371145ccdd 100644 --- a/src/lib/onboard/managed-bootstrap/docker.ts +++ b/src/lib/onboard/managed-bootstrap/docker.ts @@ -59,6 +59,8 @@ import { type ManagedBootstrapObservedSnapshot, ManagedBootstrapOwnerCleanupRequiredError, type ManagedBootstrapPreparedReplacementHandle, + type ManagedBootstrapRecoveryFailure, + type ManagedBootstrapRecoveryReport, type ManagedBootstrapRecoveryReceipt, type ManagedBootstrapReplacementHandle, type ManagedBootstrapReplacementOptions, @@ -74,6 +76,7 @@ import { type DockerManagedBootstrapFinalizationRecord, type DockerManagedBootstrapJournal, DockerManagedBootstrapJournalAcknowledgementLostError, + DockerManagedBootstrapLegacyRecordRequiresAgentError, type DockerManagedBootstrapJournalStore, parseDockerManagedBootstrapJournal, serializeDockerManagedBootstrapFinalizationRecord, @@ -105,9 +108,45 @@ const REQUEST_TEMP_PREFIX = "nemoclaw-managed-bootstrap-request"; const COMPLETION_TEMP_PREFIX = "nemoclaw-managed-bootstrap-completion"; const COMPLETION_MAX_BYTES = 4096; const DOCKER_DRIVER_ID = "docker"; +const MAX_RECOVERY_FAILURE_DETAIL_BYTES = 8 * 1024; export const MANAGED_BOOTSTRAP_TRAMPOLINE_EXECUTABLE = "/usr/local/bin/nemoclaw-managed-bootstrap"; +function boundedRecoveryFailureDetail(error: unknown): string { + const raw = (error instanceof Error ? error.message : String(error)).replaceAll("\0", "�"); + const detail = raw.length > 0 ? raw : "Docker recovery failed without diagnostic detail"; + const bytes = Buffer.from(detail, "utf8"); + if (bytes.length <= MAX_RECOVERY_FAILURE_DETAIL_BYTES) return detail; + return bytes.subarray(0, MAX_RECOVERY_FAILURE_DETAIL_BYTES).toString("utf8"); +} + +function dockerManagedBootstrapRecoveryFailure( + bootstrapIdentity: string, + journal: DockerBootstrapTransaction | null, + error: unknown, +): ManagedBootstrapRecoveryFailure { + const classified = + error instanceof ManagedBootstrapOwnerCleanupRequiredError + ? { code: "owner-cleanup-required", retryable: true } + : error instanceof ManagedBootstrapDurableCommitCleanupPendingError + ? { code: "durable-cleanup-pending", retryable: true } + : error instanceof ManagedBootstrapCommitStateIndeterminateError + ? { code: "commit-state-indeterminate", retryable: true } + : error instanceof DockerManagedBootstrapLegacyRecordRequiresAgentError + ? { code: "legacy-agent-required", retryable: false } + : { code: "provider-recovery-failed", retryable: true }; + return Object.freeze({ + schemaVersion: MANAGED_BOOTSTRAP_SCHEMA_VERSION, + providerId: journal?.providerId ?? DOCKER_DRIVER_ID, + sourcePhase: journal?.phase ?? null, + sandbox: journal?.sandbox ?? null, + bootstrapIdentity, + code: classified.code, + retryable: classified.retryable, + detail: boundedRecoveryFailureDetail(error), + }); +} + type DockerCommandResult = { readonly status?: number | null; readonly stdout?: string | Buffer | null; @@ -1469,7 +1508,7 @@ function createDockerBootstrapJournalDurably( function transitionDockerBootstrapJournalDurably( journal: DockerBootstrapTransaction, - next: "cutover" | "rollback-authorized" | "shared-state-committed", + next: "cutover" | "rollback-authorized" | "owner-cleanup-required" | "shared-state-committed", deps: ResolvedDeps, ): DockerBootstrapTransaction { try { @@ -1862,19 +1901,71 @@ export function createDockerManagedBootstrapAdapter( } satisfies ManagedBootstrapFinalizationReceipt); return persistFinalization(handle, "rolled-back", null, receipt); }; + const requireExactOwnerCleanup = (journal: DockerBootstrapTransaction): void => { + const presence = probeExactDockerContainerAbsence(journal.originalRuntimeId, deps); + if (presence === "unknown") { + throw new ManagedBootstrapCommitStateIndeterminateError({ + bootstrapIdentity: journal.bootstrapIdentity, + runtimeId: journal.originalRuntimeId, + detail: "exact owner-cleanup runtime presence is unknown", + }); + } + if (presence === "absent") return; + const original = inspectExact(journal.originalRuntimeId, deps); + assertTransactionOriginal(journal, original); + if ( + dockerContainerName(original) !== journal.originalName || + normalizeDockerManagedBootstrapLaunchSpec(original).hash !== journal.originalSpecHash || + (journal.phase === "owner-cleanup-required" && !isExplicitlyStopped(original)) || + (journal.phase !== "owner-cleanup-required" && + !isExplicitlyStopped(original) && + !isStableRunning(original)) + ) { + throw new ManagedBootstrapCommitStateIndeterminateError({ + bootstrapIdentity: journal.bootstrapIdentity, + runtimeId: journal.originalRuntimeId, + detail: "owner-cleanup runtime does not match its exact restored durable authority", + }); + } + try { + removeOwnedWorkload(journal.sandbox, deps, journal.originalRuntimeId); + } catch (error) { + if (!(error instanceof ManagedBootstrapOwnerCleanupRequiredError)) throw error; + if (error.runtimeId !== journal.originalRuntimeId) { + throw new ManagedBootstrapCommitStateIndeterminateError({ + bootstrapIdentity: journal.bootstrapIdentity, + runtimeId: journal.originalRuntimeId, + detail: "owner cleanup retained a runtime other than the durable original", + }); + } + if (journal.phase !== "owner-cleanup-required") { + if (journal.phase !== "staged" && journal.phase !== "rollback-authorized") { + throw new ManagedBootstrapCommitStateIndeterminateError({ + bootstrapIdentity: journal.bootstrapIdentity, + runtimeId: journal.originalRuntimeId, + detail: `owner cleanup cannot be retained from durable phase ${journal.phase}`, + }); + } + const current = deps.journalStore.load(journal.bootstrapIdentity); + if (!current || !sameDockerBootstrapJournal(current, journal)) { + throw new ManagedBootstrapCommitStateIndeterminateError({ + bootstrapIdentity: journal.bootstrapIdentity, + runtimeId: journal.originalRuntimeId, + detail: "durable authority changed before owner cleanup was retained", + }); + } + transitionDockerBootstrapJournalDurably(journal, "owner-cleanup-required", deps); + } + throw error; + } + }; const completeRollbackTransaction = ( handle: ManagedBootstrapHeldWorkloadHandle, journal: DockerBootstrapTransaction, ): ManagedBootstrapFinalizationReceipt => { - let ownerCleanupFailure: { readonly error: unknown } | null = null; - try { - removeOwnedWorkload(handle.sandbox, deps, journal.originalRuntimeId); - } catch (error) { - ownerCleanupFailure = { error }; - } + requireExactOwnerCleanup(journal); const finalization = completedRollback(handle, false); removeDockerBootstrapJournalDurably(journal, deps); - if (ownerCleanupFailure) throw ownerCleanupFailure.error; return finalization; }; const completedCommit = ( @@ -1975,7 +2066,9 @@ export function createDockerManagedBootstrapAdapter( journal.commitReceipt !== null && sameManagedBootstrapCompletionReceipt(finalization.commitReceipt, journal.commitReceipt)) || (finalization.phase === "rolled-back" && - (journal.phase === "staged" || journal.phase === "rollback-authorized") && + (journal.phase === "staged" || + journal.phase === "rollback-authorized" || + journal.phase === "owner-cleanup-required") && finalization.commitReceipt === null); if ( !phaseMatches || @@ -2005,14 +2098,15 @@ export function createDockerManagedBootstrapAdapter( journal: DockerBootstrapTransaction, sourcePhase: DockerBootstrapTransaction["phase"], ): ManagedBootstrapRecoveryReceipt => { + requireExactOwnerCleanup(journal); const cleanupReceipt = Object.freeze({ schemaVersion: MANAGED_BOOTSTRAP_SCHEMA_VERSION, sandbox: journal.sandbox, bootstrapIdentity: journal.bootstrapIdentity, outcome: "rolled-back", - restoredRuntimeId: journal.originalRuntimeId, - restoredSpecHash: journal.originalSpecHash, - heldWorkloadRemoved: false, + restoredRuntimeId: null, + restoredSpecHash: null, + heldWorkloadRemoved: true, alreadyRolledBack: false, finalizedAt: deps.now().toISOString(), } satisfies ManagedBootstrapFinalizationReceipt); @@ -2104,7 +2198,17 @@ export function createDockerManagedBootstrapAdapter( } } if (sharedStatus === "committed") { - clearDockerManagedStartupSharedStateCommitReceipt(sharedTransaction, deps); + try { + clearDockerManagedStartupSharedStateCommitReceipt(sharedTransaction, deps); + } catch (error) { + throw new ManagedBootstrapDurableCommitCleanupPendingError({ + bootstrapIdentity: journal.bootstrapIdentity, + cleanupRuntimeId: journal.replacementRuntimeId, + detail: `the image-owned commit receipt could not be retired during restart recovery: ${ + error instanceof Error ? error.message : String(error) + }`, + }); + } } if (probeExactDockerContainerAbsence(journal.originalRuntimeId, deps) !== "absent") { throw new ManagedBootstrapDurableCommitCleanupPendingError({ @@ -2137,6 +2241,9 @@ export function createDockerManagedBootstrapAdapter( journal: DockerBootstrapTransaction, sourcePhase: DockerBootstrapTransaction["phase"], ): ManagedBootstrapRecoveryReceipt => { + if (journal.phase === "owner-cleanup-required") { + return finishRecoveredRollback(journal, sourcePhase); + } const original = inspectTransactionRuntime(journal, journal.originalRuntimeId, deps); if (!original) { throw new ManagedBootstrapCommitStateIndeterminateError({ @@ -2374,6 +2481,9 @@ export function createDockerManagedBootstrapAdapter( replacement, durablePreparation, ); + if (journal.phase === "owner-cleanup-required") { + return completeRollbackTransaction(handle, journal); + } const original = inspectTransactionRuntime(journal, journal.originalRuntimeId, deps); if (!original) { throw new ManagedBootstrapCommitStateIndeterminateError({ @@ -2881,17 +2991,34 @@ export function createDockerManagedBootstrapAdapter( return { async recoverUnfinishedTransactions() { const receipts: ManagedBootstrapRecoveryReceipt[] = []; - for (const journal of deps.journalStore.listUnfinished()) { - const sourcePhase = journal.phase; - const finalized = compactRecoveredFinalization(journal, sourcePhase); - receipts.push( - finalized ?? - (journal.phase === "shared-state-committed" - ? finishRecoveredCommit(journal, sourcePhase) - : finishRecoveredRollbackPhase(journal, sourcePhase)), - ); + const failures: ManagedBootstrapRecoveryFailure[] = []; + for (const bootstrapIdentity of deps.journalStore.listUnfinishedIdentities()) { + let journal: DockerBootstrapTransaction | null = null; + try { + journal = deps.journalStore.load(bootstrapIdentity); + if (!journal) { + throw new Error("durable journal disappeared after identity enumeration"); + } + const sourcePhase = journal.phase; + const finalized = compactRecoveredFinalization(journal, sourcePhase); + receipts.push( + finalized ?? + (journal.phase === "shared-state-committed" + ? finishRecoveredCommit(journal, sourcePhase) + : finishRecoveredRollbackPhase(journal, sourcePhase)), + ); + } catch (error) { + failures.push(dockerManagedBootstrapRecoveryFailure(bootstrapIdentity, journal, error)); + } } - return Object.freeze(receipts); + const byBootstrapIdentity = ( + left: ManagedBootstrapRecoveryReceipt | ManagedBootstrapRecoveryFailure, + right: ManagedBootstrapRecoveryReceipt | ManagedBootstrapRecoveryFailure, + ) => left.bootstrapIdentity.localeCompare(right.bootstrapIdentity); + return Object.freeze({ + receipts: Object.freeze(receipts.sort(byBootstrapIdentity)), + failures: Object.freeze(failures.sort(byBootstrapIdentity)), + } satisfies ManagedBootstrapRecoveryReport); }, async createHeldWorkload(input) { diff --git a/src/lib/onboard/managed-bootstrap/index.ts b/src/lib/onboard/managed-bootstrap/index.ts index f5f6f545869..3ffd6764b3f 100644 --- a/src/lib/onboard/managed-bootstrap/index.ts +++ b/src/lib/onboard/managed-bootstrap/index.ts @@ -10,7 +10,11 @@ export { type ManagedBootstrapAuthorityStore, type ManagedBootstrapExpectedPlan, type ManagedBootstrapPreparedTransaction, + type ManagedBootstrapRecoveryFailure, + type ManagedBootstrapRecoveryReport, type ManagedBootstrapRecoveryReceipt, + ManagedBootstrapRecoveryBlockedError, + enforceManagedBootstrapRecoveryForSandbox, prepareManagedBootstrapSequence, recoverManagedBootstrapTransactions, sameManagedBootstrapCompletionReceipt, diff --git a/src/lib/onboard/managed-bootstrap/runtime-create.ts b/src/lib/onboard/managed-bootstrap/runtime-create.ts index a98dcf71c90..60f1ab734e1 100644 --- a/src/lib/onboard/managed-bootstrap/runtime-create.ts +++ b/src/lib/onboard/managed-bootstrap/runtime-create.ts @@ -10,7 +10,7 @@ import type { ManagedBootstrapAuthorityStore, ManagedBootstrapCreateReceipt, ManagedBootstrapImageIdentity, - ManagedBootstrapRecoveryReceipt, + ManagedBootstrapRecoveryReport, } from "./adapter"; export interface ManagedBootstrapRuntimeCommandResult { @@ -130,7 +130,7 @@ export function createManagedBootstrapTerminalFinalizer( export interface ManagedBootstrapRuntimeCreateLifecycle { readonly launchArgv: readonly string[]; readonly patch: ManagedBootstrapRuntimePatch; - recoverUnfinished(): Promise; + recoverUnfinished(): Promise; prepareNetwork(): Promise; runCreate( launch: (input: { diff --git a/src/lib/onboard/runtime-provider/runtime-provider-contract.test.ts b/src/lib/onboard/runtime-provider/runtime-provider-contract.test.ts index 6628831a980..818ae30eb30 100644 --- a/src/lib/onboard/runtime-provider/runtime-provider-contract.test.ts +++ b/src/lib/onboard/runtime-provider/runtime-provider-contract.test.ts @@ -209,7 +209,7 @@ describe("RuntimeProviderBundle registry contract", () => { printReadinessFailureIfEnabled: vi.fn(), verifyGpuOrExit: vi.fn(async (verify) => verify("alpha")), }, - recoverUnfinished: vi.fn(async () => []), + recoverUnfinished: vi.fn(async () => ({ receipts: [], failures: [] })), prepareNetwork: vi.fn(async () => undefined), runCreate: vi.fn(), })); diff --git a/src/lib/onboard/sandbox-gpu-create-flow.test.ts b/src/lib/onboard/sandbox-gpu-create-flow.test.ts index a7362d037ce..e2be8548e33 100644 --- a/src/lib/onboard/sandbox-gpu-create-flow.test.ts +++ b/src/lib/onboard/sandbox-gpu-create-flow.test.ts @@ -62,6 +62,10 @@ import { setupGpuFlowMocks, VERIFIED_GPU_PROOF as VERIFIED_PROOF, } from "./__test-helpers__/sandbox-gpu-create-flow"; +import { + MANAGED_BOOTSTRAP_SCHEMA_VERSION, + type ManagedBootstrapRecoveryReport, +} from "./managed-bootstrap/adapter"; import type { ManagedBootstrapRuntimeCreateLifecycleInput, ManagedBootstrapRuntimePatch, @@ -201,7 +205,30 @@ describe("runSandboxGpuCreateFlow provider-owned managed create", () => { input.sandboxEnv = launch.sandboxEnv; input.sandboxStartupCommand = launch.sandboxStartupCommand; const patch = createPatch() as unknown as ManagedBootstrapRuntimePatch; - const recoverUnfinished = vi.fn(async () => []); + const recoveryReport = (sandboxName: string | null): ManagedBootstrapRecoveryReport => + Object.freeze({ + receipts: Object.freeze([]), + failures: Object.freeze([ + Object.freeze({ + schemaVersion: MANAGED_BOOTSTRAP_SCHEMA_VERSION, + providerId: "mxc", + sourcePhase: "provider-owned-cleanup", + sandbox: + sandboxName === null + ? null + : Object.freeze({ + sandboxName, + sandboxId: `mxc-${sandboxName}`, + driverId: "mxc", + }), + bootstrapIdentity: "e".repeat(64), + code: "mxc-recovery-retry", + retryable: true, + detail: "opaque MXC recovery detail", + }), + ]), + }); + const recoverUnfinished = vi.fn(async () => recoveryReport("bravo")); const prepareNetwork = vi.fn(async () => undefined); const createLifecycle = vi.fn( (lifecycleInput: ManagedBootstrapRuntimeCreateLifecycleInput) => ({ @@ -319,6 +346,19 @@ describe("runSandboxGpuCreateFlow provider-owned managed create", () => { expect(mocks.queryOpenShellDockerSandboxContainers).not.toHaveBeenCalled(); expect(mocks.queryOpenShellDockerSandboxRuntimeSnapshot).not.toHaveBeenCalled(); expect(mocks.enforceDockerGpuPatchPreserveNetwork).not.toHaveBeenCalled(); + + expect(vi.mocked(console.warn).mock.calls.flat().join("\n")).toContain( + "unrelated sandbox 'bravo'", + ); + recoverUnfinished.mockResolvedValueOnce(recoveryReport("alpha")); + prepareNetwork.mockClear(); + mocks.streamSandboxCreate.mockClear(); + + await expect(runSandboxGpuCreateFlow(input, deps)).rejects.toThrow( + "recovery blocks sandbox 'alpha'", + ); + expect(prepareNetwork).not.toHaveBeenCalled(); + expect(mocks.streamSandboxCreate).not.toHaveBeenCalled(); }); }); diff --git a/src/lib/onboard/sandbox-gpu-create-run-attempt.ts b/src/lib/onboard/sandbox-gpu-create-run-attempt.ts index 3210934ff57..9aa59c43118 100644 --- a/src/lib/onboard/sandbox-gpu-create-run-attempt.ts +++ b/src/lib/onboard/sandbox-gpu-create-run-attempt.ts @@ -14,6 +14,7 @@ import { reportSandboxCreateFailure } from "./created-sandbox-failure"; import * as dockerGpuLocalInference from "./docker-gpu-local-inference"; import type { SelectedDockerGpuRoute } from "./docker-gpu-route"; import { createDockerGpuSandboxCreatePatch } from "./docker-gpu-sandbox-create"; +import { enforceManagedBootstrapRecoveryForSandbox } from "./managed-bootstrap/adapter"; import type { ManagedBootstrapRuntimeSnapshot } from "./managed-bootstrap/runtime-create"; import { queryOpenShellDockerSandboxContainers, @@ -143,7 +144,12 @@ export function createSandboxGpuCreateAttemptRunner( backend: input.sandboxGpuConfig.hostGpuPlatform === "jetson" ? "jetson" : "generic", deps, }); - await managedLifecycle?.recoverUnfinished(); + const recovery = await managedLifecycle?.recoverUnfinished(); + if (recovery) { + enforceManagedBootstrapRecoveryForSandbox(recovery, input.sandboxName, (message) => + console.warn(` ⚠ ${message}`), + ); + } await managedLifecycle?.prepareNetwork(); const [createExecutable, ...createExecutableArgs] = managedLifecycle?.launchArgv ?? attemptArgv; if (!createExecutable) throw new Error("Sandbox create executable is missing."); From 6f812edf3a657c0ad147e596c6c78c4f44b98584 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Sun, 2 Aug 2026 11:44:18 -0700 Subject: [PATCH 2/4] test(onboard): reconcile journal identity enumeration Signed-off-by: Aaron Erickson --- src/lib/onboard/managed-bootstrap/docker-journal.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/onboard/managed-bootstrap/docker-journal.test.ts b/src/lib/onboard/managed-bootstrap/docker-journal.test.ts index 51cf74acdd4..a42af40f3da 100644 --- a/src/lib/onboard/managed-bootstrap/docker-journal.test.ts +++ b/src/lib/onboard/managed-bootstrap/docker-journal.test.ts @@ -542,7 +542,7 @@ describe("Docker managed bootstrap journal", () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-docker-journal-")); roots.push(root); const store = createFileDockerManagedBootstrapJournalStore(root); - expect(store.listUnfinished()).toEqual([]); + expect(loadUnfinished(store)).toEqual([]); const target = path.join( root, DOCKER_MANAGED_BOOTSTRAP_JOURNAL_DIRECTORY, From c4c4a36519600692e28d909efca7c2c8491b63f1 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Sun, 2 Aug 2026 12:21:49 -0700 Subject: [PATCH 3/4] fix(onboard): retain exact owner cleanup recovery Signed-off-by: Aaron Erickson --- src/lib/onboard/managed-bootstrap/README.md | 22 +- .../onboard/managed-bootstrap/adapter.test.ts | 22 ++ src/lib/onboard/managed-bootstrap/adapter.ts | 7 + .../managed-bootstrap/docker-journal.test.ts | 28 ++ .../managed-bootstrap/docker-recovery.test.ts | 281 ++++++++++++++++-- .../managed-bootstrap/docker-test-fixture.ts | 4 + .../onboard/managed-bootstrap/docker.test.ts | 17 +- src/lib/onboard/managed-bootstrap/docker.ts | 12 +- 8 files changed, 361 insertions(+), 32 deletions(-) diff --git a/src/lib/onboard/managed-bootstrap/README.md b/src/lib/onboard/managed-bootstrap/README.md index 77bece4661e..e64371a4fdc 100644 --- a/src/lib/onboard/managed-bootstrap/README.md +++ b/src/lib/onboard/managed-bootstrap/README.md @@ -53,6 +53,12 @@ records containing the provider and sandbox identities, plan and profile fingerprints, exact original and replacement IDs, rollback target, and phase. Exact commit and cleanup receipts are durable terminal records, so adapter recreation does not depend on process-local transaction sets or tombstone maps. +Rollback retains an `owner-cleanup-required` phase only after image-owned shared +state is restored and the exact replacement is absent. That phase keeps the +restored original quiescent and preserves the journal without a terminal +receipt until the owning sandbox service removes the exact runtime and the +provider proves its absence. Unknown runtime presence is a retryable durable +cleanup failure, never evidence of absence. The image-owned shared-state transaction uses the same identity-bound model: a commit atomically moves its pending manifest and backups into a durable receipt namespace, compacts that state to an exact commit receipt, and rejects rollback @@ -73,11 +79,17 @@ image-owned commit forward or durably authorizes rollback; rollback-authorized work completes exact restore and cleanup; and shared-state-committed work completes exact backup cleanup and commit. Recovery persists an identity-bound finalization receipt before removing the active journal, is idempotent across -another interruption, and returns normalized, provider-owned receipts in stable -identity order. The code reads mutable OpenShell names only to detect ownership -reuse, and unsafe name-only deletion returns a typed retention error. Multi-process -lease/arbitration remains an explicit production-activation gate. Activation -must also inject the selected gateway's canonical state root. +another interruption, and enumerates durable identities before loading each +record so one unreadable transaction does not hide other results. The provider +returns bounded `{ receipts, failures }` evidence; the coordinator validates, +copies, freezes, and orders both arrays without routing on provider phases or +failure codes. A failure for the requested sandbox name, or one whose sandbox +identity cannot be proven, blocks create. An exact failure for another sandbox +is warned and retained without blocking the requested create. The code reads +mutable OpenShell names only to detect ownership reuse, and unsafe name-only +deletion returns a typed retention error. Multi-process lease/arbitration +remains an explicit production-activation gate. Activation must also inject the +selected gateway's canonical state root. The runtime-provider bundle is the only bootstrap registration boundary. The candidate Docker surface owns create routing, replacement construction, diff --git a/src/lib/onboard/managed-bootstrap/adapter.test.ts b/src/lib/onboard/managed-bootstrap/adapter.test.ts index 8f05a1e54d5..91812e90c3b 100644 --- a/src/lib/onboard/managed-bootstrap/adapter.test.ts +++ b/src/lib/onboard/managed-bootstrap/adapter.test.ts @@ -820,6 +820,28 @@ describe("managed bootstrap adapter contract", () => { ); }); + it("rejects an unbounded provider recovery result before normalizing records", async () => { + const fixture = adapterFor("hermes"); + const candidate = { + schemaVersion: MANAGED_BOOTSTRAP_SCHEMA_VERSION, + providerId: "mxc", + sourcePhase: "provider-owned-cleanup", + sandbox: null, + bootstrapIdentity: IDENTITY, + code: "provider-owned-retry", + retryable: true, + detail: "opaque MXC recovery evidence", + } as const; + vi.mocked(fixture.adapter.recoverUnfinishedTransactions).mockResolvedValueOnce({ + receipts: [], + failures: Array.from({ length: 4097 }, () => candidate), + }); + + await expect(recoverManagedBootstrapTransactions(fixture.adapter)).rejects.toThrow( + "provider recovery returned too many records", + ); + }); + it("blocks same-name and identity-unknown failures while warning for unrelated sandboxes", () => { const failure = (bootstrapIdentity: string, sandboxName: string | null) => Object.freeze({ diff --git a/src/lib/onboard/managed-bootstrap/adapter.ts b/src/lib/onboard/managed-bootstrap/adapter.ts index b5e441b5d8f..08ff7a0f275 100644 --- a/src/lib/onboard/managed-bootstrap/adapter.ts +++ b/src/lib/onboard/managed-bootstrap/adapter.ts @@ -18,6 +18,7 @@ export const MANAGED_BOOTSTRAP_IDENTITY_BYTES = 32; const SHA256_RE = /^[a-f0-9]{64}$/u; const MANIFEST_DIGEST_RE = /^sha256:[a-f0-9]{64}$/u; const ENV_ASSIGNMENT_RE = /^[A-Za-z_][A-Za-z0-9_]*=/u; +const MAX_MANAGED_BOOTSTRAP_RECOVERY_RECORDS = 4096; const PROCESS_INJECTION_ENV_KEYS = new Set([ "BASHOPTS", "BASH_ENV", @@ -547,6 +548,12 @@ export async function recoverManagedBootstrapTransactions( ) { protocolFail("provider recovery must return bounded receipt and failure arrays"); } + if ( + candidates.receipts.length + candidates.failures.length > + MAX_MANAGED_BOOTSTRAP_RECOVERY_RECORDS + ) { + protocolFail("provider recovery returned too many records"); + } const receipts = candidates.receipts.map(normalizeRecoveryReceipt); const failures = candidates.failures.map(normalizeRecoveryFailure); const identities = [...receipts, ...failures].map(({ bootstrapIdentity }) => bootstrapIdentity); diff --git a/src/lib/onboard/managed-bootstrap/docker-journal.test.ts b/src/lib/onboard/managed-bootstrap/docker-journal.test.ts index a42af40f3da..87a169433d8 100644 --- a/src/lib/onboard/managed-bootstrap/docker-journal.test.ts +++ b/src/lib/onboard/managed-bootstrap/docker-journal.test.ts @@ -244,6 +244,26 @@ describe("Docker managed bootstrap journal", () => { expect(store.load(IDENTITY)).toBeNull(); }); + it("persists owner cleanup as a restart-safe non-terminal phase", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-docker-journal-")); + roots.push(root); + const first = createFileDockerManagedBootstrapJournalStore(root); + first.create(journal); + + const retained = first.transition(IDENTITY, "staged", "owner-cleanup-required"); + expect(retained.phase).toBe("owner-cleanup-required"); + expect(first.listUnfinishedIdentities()).toEqual([IDENTITY]); + + const restarted = createFileDockerManagedBootstrapJournalStore(root); + expect(restarted.load(IDENTITY)).toEqual(retained); + expect(restarted.listUnfinishedIdentities()).toEqual([IDENTITY]); + expect(() => + restarted.transition(IDENTITY, "owner-cleanup-required", "shared-state-committed"), + ).toThrow("unsupported"); + restarted.remove(IDENTITY, ["owner-cleanup-required"]); + expect(restarted.load(IDENTITY)).toBeNull(); + }); + it("recovers one durable cutover decision before journal replacement", () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-docker-journal-")); roots.push(root); @@ -462,6 +482,14 @@ describe("Docker managed bootstrap journal", () => { } }); + it("rejects owner cleanup as authority invented by a legacy journal", () => { + expect(() => + parseDockerManagedBootstrapJournal( + `${JSON.stringify({ ...legacyJournalV2(), phase: "owner-cleanup-required" })}\n`, + ), + ).toThrow("legacy phase is unsupported"); + }); + it("upgrades legacy finalization only with exact immutable transaction context", () => { const serialized = `${JSON.stringify(legacyFinalizationV1())}\n`; let missingContextFailure: unknown; diff --git a/src/lib/onboard/managed-bootstrap/docker-recovery.test.ts b/src/lib/onboard/managed-bootstrap/docker-recovery.test.ts index 48377775667..101605990a7 100644 --- a/src/lib/onboard/managed-bootstrap/docker-recovery.test.ts +++ b/src/lib/onboard/managed-bootstrap/docker-recovery.test.ts @@ -3,12 +3,17 @@ import { describe, expect, it } from "vitest"; +import { recoverManagedBootstrapTransactions } from "./adapter"; import { createDockerManagedBootstrapAdapter } from "./docker"; +import type { DockerManagedBootstrapJournalStore } from "./docker-journal"; import { authority, type DockerFixtureOptions, durablePreparation, fixture, + IDENTITY, + NEW_ID, + OLD_ID, } from "./docker-test-fixture"; async function prepareTransaction( @@ -32,6 +37,12 @@ async function prepareTransaction( }; } +function expectEventBefore(events: readonly string[], before: string, after: string): void { + expect(events).toContain(before); + expect(events).toContain(after); + expect(events.indexOf(before)).toBeLessThan(events.indexOf(after)); +} + describe("Docker managed bootstrap restart recovery", () => { it.each([ { @@ -54,7 +65,10 @@ describe("Docker managed bootstrap restart recovery", () => { readonly label: string; readonly options: DockerFixtureOptions; readonly phase: "cutover" | "staged"; - }[])("reconciles a process restart from the durable $label phase", async ({ options, phase }) => { + }[])("retains owner cleanup after a process restart from the durable $label phase", async ({ + options, + phase, + }) => { const fake = fixture(options); const transaction = await prepareTransaction(fake); @@ -69,17 +83,56 @@ describe("Docker managed bootstrap restart recovery", () => { expect(fake.journal?.phase).toBe(phase); const restarted = createDockerManagedBootstrapAdapter(fake.deps); - await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject([ - { sourcePhase: phase, outcome: "rolled-back" }, - ]); + await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject({ + receipts: [], + failures: [ + { + bootstrapIdentity: IDENTITY, + sourcePhase: "owner-cleanup-required", + code: "owner-cleanup-required", + retryable: true, + }, + ], + }); + expect(fake.journal?.phase).toBe("owner-cleanup-required"); + expect(fake.finalization).toBeNull(); + expect(fake.replacement).toBeNull(); + expect(fake.original.State?.Running).toBe(false); + expectEventBefore(fake.events, `rm:${NEW_ID}`, "journal:owner-cleanup-required"); + + const ownerTransitions = fake.events.filter( + (event) => event === "journal:owner-cleanup-required", + ).length; + await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject({ + receipts: [], + failures: [{ code: "owner-cleanup-required" }], + }); + expect(fake.events.filter((event) => event === "journal:owner-cleanup-required")).toHaveLength( + ownerTransitions, + ); + expect(fake.journal?.phase).toBe("owner-cleanup-required"); + expect(fake.finalization).toBeNull(); + + fake.removeOriginalExternally(); + await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject({ + receipts: [ + { + bootstrapIdentity: IDENTITY, + sourcePhase: "owner-cleanup-required", + outcome: "rolled-back", + }, + ], + failures: [], + }); expect(fake.journal).toBeNull(); expect(fake.finalization?.phase).toBe("rolled-back"); - expect(fake.replacement).toBeNull(); - expect(fake.original.State?.Running).toBe(true); - await expect(restarted.recoverUnfinishedTransactions()).resolves.toEqual([]); + await expect(restarted.recoverUnfinishedTransactions()).resolves.toEqual({ + receipts: [], + failures: [], + }); }); - it("finishes rollback-authorized recovery after shared-state rollback is interrupted", async () => { + it("publishes owner cleanup only after shared rollback, replacement cleanup, and restoration", async () => { const fake = fixture({ agent: "openclaw", journalTransitionFailures: { @@ -110,19 +163,70 @@ describe("Docker managed bootstrap restart recovery", () => { expect(fake.sharedState).toBe("pending"); const restarted = createDockerManagedBootstrapAdapter(fake.deps); - await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject([ - { sourcePhase: "rollback-authorized", outcome: "rolled-back" }, - ]); + await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject({ + receipts: [], + failures: [{ sourcePhase: "owner-cleanup-required", code: "owner-cleanup-required" }], + }); expect(fake.sharedState).toBe("none"); expect(fake.replacement).toBeNull(); - expect(fake.original.State?.Running).toBe(true); + expect(fake.original.State?.Running).toBe(false); + expect(fake.journal?.phase).toBe("owner-cleanup-required"); + expect(fake.finalization).toBeNull(); + expectEventBefore(fake.events, "shared:rollback", `rm:${NEW_ID}`); + expectEventBefore(fake.events, `rm:${NEW_ID}`, "journal:owner-cleanup-required"); + + fake.removeOriginalExternally(); + await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject({ + receipts: [{ outcome: "rolled-back", sourcePhase: "owner-cleanup-required" }], + failures: [], + }); }); - it("compacts a terminal commit journal after another restart interruption", async () => { + it("retains owner authority while exact runtime presence is unknown", async () => { + const fake = fixture({ + journalCreateFailures: [new Error("injected crash after durable staged fence")], + }); + const transaction = await prepareTransaction(fake); + await expect( + transaction.adapter.activateBootstrapReplacement({ + handle: transaction.handle, + snapshot: transaction.snapshot, + prepared: transaction.prepared, + durablePreparation: transaction.durable, + }), + ).rejects.toThrow("crash after durable staged fence"); + + const restarted = createDockerManagedBootstrapAdapter(fake.deps); + await restarted.recoverUnfinishedTransactions(); + expect(fake.journal?.phase).toBe("owner-cleanup-required"); + fake.setDockerInspectUnknown(OLD_ID, true); + + await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject({ + receipts: [], + failures: [ + { + sourcePhase: "owner-cleanup-required", + code: "commit-state-indeterminate", + retryable: true, + }, + ], + }); + expect(fake.journal?.phase).toBe("owner-cleanup-required"); + expect(fake.finalization).toBeNull(); + + fake.setDockerInspectUnknown(OLD_ID, false); + fake.removeOriginalExternally(); + await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject({ + receipts: [{ outcome: "rolled-back" }], + failures: [], + }); + }); + + it("retains durable commit authority when image receipt retirement fails", async () => { const fake = fixture({ agent: "langchain-deepagents-code", dockerRemoveFailures: [new Error("injected crash before exact Docker removal")], - journalRemoveFailures: [new Error("injected crash before terminal journal removal")], + sharedReceiptClearFailures: [new Error("injected image receipt cleanup failure")], sharedState: "pending", }); const transaction = await prepareTransaction(fake, "langchain-deepagents-code"); @@ -154,18 +258,155 @@ describe("Docker managed bootstrap restart recovery", () => { expect(fake.sharedState).toBe("committed"); const restarted = createDockerManagedBootstrapAdapter(fake.deps); - await expect(restarted.recoverUnfinishedTransactions()).rejects.toThrow( - "crash before terminal journal removal", - ); + await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject({ + receipts: [], + failures: [ + { + sourcePhase: "shared-state-committed", + code: "durable-cleanup-pending", + retryable: true, + }, + ], + }); + expect(fake.journal?.phase).toBe("shared-state-committed"); + expect(fake.finalization).toBeNull(); + expect(fake.sharedState).toBe("committed"); + + await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject({ + receipts: [{ outcome: "committed", sourcePhase: "shared-state-committed" }], + failures: [], + }); + expect(fake.journal).toBeNull(); + expect(fake.finalization?.phase).toBe("committed"); + expect(fake.sharedState).toBe("none"); + }); + + it("compacts a terminal commit journal after another restart interruption", async () => { + const fake = fixture({ + agent: "langchain-deepagents-code", + dockerRemoveFailures: [new Error("injected crash before exact Docker removal")], + journalRemoveFailures: [new Error("injected crash before terminal journal removal")], + sharedState: "pending", + }); + const transaction = await prepareTransaction(fake, "langchain-deepagents-code"); + const replacement = await transaction.adapter.activateBootstrapReplacement({ + handle: transaction.handle, + snapshot: transaction.snapshot, + prepared: transaction.prepared, + durablePreparation: transaction.durable, + }); + const completion = await transaction.adapter.awaitBootstrap({ + handle: transaction.handle, + snapshot: transaction.snapshot, + replacement, + timeoutSecs: 1, + }); + + await expect( + transaction.adapter.finalizeBootstrap({ + outcome: "commit", + handle: transaction.handle, + snapshot: transaction.snapshot, + prepared: transaction.prepared, + durablePreparation: transaction.durable, + replacement, + completion, + }), + ).rejects.toThrow("crash before exact Docker removal"); + + const restarted = createDockerManagedBootstrapAdapter(fake.deps); + await expect(restarted.recoverUnfinishedTransactions()).resolves.toMatchObject({ + receipts: [], + failures: [ + { + sourcePhase: "shared-state-committed", + code: "provider-recovery-failed", + detail: "injected crash before terminal journal removal", + }, + ], + }); expect(fake.journal?.phase).toBe("shared-state-committed"); expect(fake.finalization?.phase).toBe("committed"); const resumed = createDockerManagedBootstrapAdapter(fake.deps); - await expect(resumed.recoverUnfinishedTransactions()).resolves.toMatchObject([ - { sourcePhase: "shared-state-committed", outcome: "committed" }, - ]); + await expect(resumed.recoverUnfinishedTransactions()).resolves.toMatchObject({ + receipts: [{ sourcePhase: "shared-state-committed", outcome: "committed" }], + failures: [], + }); expect(fake.journal).toBeNull(); expect(fake.sharedState).toBe("none"); expect(fake.replacement?.State?.Running).toBe(true); }); + + it("isolates identity-first failures and returns bounded lossless mixed evidence", async () => { + const fake = fixture({ + dockerRemoveFailures: [new Error("injected crash before exact Docker removal")], + journalRemoveFailures: [new Error("injected crash before terminal journal removal")], + sharedState: "pending", + }); + const transaction = await prepareTransaction(fake); + const replacement = await transaction.adapter.activateBootstrapReplacement({ + handle: transaction.handle, + snapshot: transaction.snapshot, + prepared: transaction.prepared, + durablePreparation: transaction.durable, + }); + const completion = await transaction.adapter.awaitBootstrap({ + handle: transaction.handle, + snapshot: transaction.snapshot, + replacement, + timeoutSecs: 1, + }); + await expect( + transaction.adapter.finalizeBootstrap({ + outcome: "commit", + handle: transaction.handle, + snapshot: transaction.snapshot, + prepared: transaction.prepared, + durablePreparation: transaction.durable, + replacement, + completion, + }), + ).rejects.toThrow("crash before exact Docker removal"); + await createDockerManagedBootstrapAdapter(fake.deps).recoverUnfinishedTransactions(); + expect(fake.finalization?.phase).toBe("committed"); + expect(fake.journal).not.toBeNull(); + + const badIdentity = "0".repeat(64); + const delegate = fake.deps.journalStore as DockerManagedBootstrapJournalStore; + const mixedStore: DockerManagedBootstrapJournalStore = { + ...delegate, + listUnfinishedIdentities: () => [badIdentity, IDENTITY], + load(bootstrapIdentity) { + if (bootstrapIdentity === badIdentity) { + throw new Error(`${"💥".repeat(3000)}\0tail`); + } + return delegate.load(bootstrapIdentity); + }, + }; + const adapter = createDockerManagedBootstrapAdapter({ ...fake.deps, journalStore: mixedStore }); + + const report = await recoverManagedBootstrapTransactions(adapter); + + expect(report.receipts).toMatchObject([ + { bootstrapIdentity: IDENTITY, sourcePhase: "shared-state-committed", outcome: "committed" }, + ]); + expect(report.failures).toMatchObject([ + { + bootstrapIdentity: badIdentity, + providerId: "docker", + sourcePhase: null, + sandbox: null, + code: "provider-recovery-failed", + }, + ]); + expect(report.failures[0]?.detail).not.toContain("\0"); + expect(Buffer.byteLength(report.failures[0]?.detail ?? "", "utf8")).toBeLessThanOrEqual(8192); + expect(Object.isFrozen(report)).toBe(true); + expect(Object.isFrozen(report.receipts)).toBe(true); + expect(Object.isFrozen(report.failures)).toBe(true); + expect(report.receipts.every(Object.isFrozen)).toBe(true); + expect(report.failures.every(Object.isFrozen)).toBe(true); + expect(fake.journal).toBeNull(); + }); }); diff --git a/src/lib/onboard/managed-bootstrap/docker-test-fixture.ts b/src/lib/onboard/managed-bootstrap/docker-test-fixture.ts index 52f5aeff499..c3406ba22d9 100644 --- a/src/lib/onboard/managed-bootstrap/docker-test-fixture.ts +++ b/src/lib/onboard/managed-bootstrap/docker-test-fixture.ts @@ -544,6 +544,10 @@ export function fixture(options: DockerFixtureOptions = {}) { original = null as unknown as DockerContainerInspect; events.push(`external-rm:${OLD_ID}`); }, + setDockerInspectUnknown(runtimeId: string, indeterminate: boolean) { + if (indeterminate) dockerInspectUnknownIds.add(runtimeId); + else dockerInspectUnknownIds.delete(runtimeId); + }, }; } diff --git a/src/lib/onboard/managed-bootstrap/docker.test.ts b/src/lib/onboard/managed-bootstrap/docker.test.ts index 8c64d46cf39..ea862c969c1 100644 --- a/src/lib/onboard/managed-bootstrap/docker.test.ts +++ b/src/lib/onboard/managed-bootstrap/docker.test.ts @@ -154,9 +154,9 @@ describe("Docker managed bootstrap adapter", () => { }), ).rejects.toBeInstanceOf(ManagedBootstrapOwnerCleanupRequiredError); expectEventBefore(fake.events, "journal:rollback-authorized", `rm:${NEW_ID}`); - expectEventBefore(fake.events, "finalization:rolled-back", "journal:removed"); - expect(fake.finalization).toMatchObject({ phase: "rolled-back" }); - expect(fake.journal).toBeNull(); + expectEventBefore(fake.events, `rm:${NEW_ID}`, "journal:owner-cleanup-required"); + expect(fake.finalization).toBeNull(); + expect(fake.journal?.phase).toBe("owner-cleanup-required"); expect(fake.replacement).toBeNull(); expect(fake.original.Name).toBe("/openshell-alpha"); expect(fake.original.State?.Running).toBe(false); @@ -198,8 +198,9 @@ describe("Docker managed bootstrap adapter", () => { }), ).rejects.toBeInstanceOf(ManagedBootstrapOwnerCleanupRequiredError); expectEventBefore(fake.events, "journal:rollback-authorized", `rm:${NEW_ID}`); - expect(fake.finalization).toMatchObject({ phase: "rolled-back" }); - expect(fake.journal).toBeNull(); + expectEventBefore(fake.events, `rm:${NEW_ID}`, "journal:owner-cleanup-required"); + expect(fake.finalization).toBeNull(); + expect(fake.journal?.phase).toBe("owner-cleanup-required"); }); it("fences rollback when image-owned shared state is already committed", async () => { @@ -328,8 +329,12 @@ describe("Docker managed bootstrap adapter", () => { completion: null, }), ).rejects.toBeInstanceOf(ManagedBootstrapOwnerCleanupRequiredError); - expect(fake.journal).toBeNull(); + expect(fake.journal?.phase).toBe("owner-cleanup-required"); + expect(fake.finalization).toBeNull(); expect(fake.replacement).toBeNull(); + expect(fake.original.State?.Running).toBe(false); + expectEventBefore(fake.events, "shared:rollback", `rm:${NEW_ID}`); + expectEventBefore(fake.events, `rm:${NEW_ID}`, "journal:owner-cleanup-required"); expect( vi.mocked(fake.deps.dockerRun!).mock.calls.some(([args]) => { const agentIndex = args.indexOf("--agent"); diff --git a/src/lib/onboard/managed-bootstrap/docker.ts b/src/lib/onboard/managed-bootstrap/docker.ts index c88a5315af1..f0e697c1384 100644 --- a/src/lib/onboard/managed-bootstrap/docker.ts +++ b/src/lib/onboard/managed-bootstrap/docker.ts @@ -117,7 +117,11 @@ function boundedRecoveryFailureDetail(error: unknown): string { const detail = raw.length > 0 ? raw : "Docker recovery failed without diagnostic detail"; const bytes = Buffer.from(detail, "utf8"); if (bytes.length <= MAX_RECOVERY_FAILURE_DETAIL_BYTES) return detail; - return bytes.subarray(0, MAX_RECOVERY_FAILURE_DETAIL_BYTES).toString("utf8"); + let bounded = bytes.subarray(0, MAX_RECOVERY_FAILURE_DETAIL_BYTES).toString("utf8"); + while (Buffer.byteLength(bounded, "utf8") > MAX_RECOVERY_FAILURE_DETAIL_BYTES) { + bounded = [...bounded].slice(0, -1).join(""); + } + return bounded; } function dockerManagedBootstrapRecoveryFailure( @@ -2080,6 +2084,7 @@ export function createDockerManagedBootstrapAdapter( detail: "terminal finalization does not match its retained durable journal", }); } + if (finalization.phase === "rolled-back") requireExactOwnerCleanup(journal); removeDockerBootstrapJournalDurably(journal, deps); return recoveredReceipt(journal, sourcePhase, finalization.cleanupReceipt); }; @@ -2997,6 +3002,11 @@ export function createDockerManagedBootstrapAdapter( : finishRecoveredRollbackPhase(journal, sourcePhase)), ); } catch (error) { + try { + journal = deps.journalStore.load(bootstrapIdentity) ?? journal; + } catch { + // Preserve the first per-record failure when the durable re-read also fails. + } failures.push(dockerManagedBootstrapRecoveryFailure(bootstrapIdentity, journal, error)); } } From 0901f67fe3954578e220ba4eb7cb11e3e6c386fc Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Sun, 2 Aug 2026 12:38:35 -0700 Subject: [PATCH 4/4] test(onboard): keep recovery fixtures linear Signed-off-by: Aaron Erickson --- .../onboard/managed-bootstrap/docker-journal.test.ts | 4 ++-- .../onboard/managed-bootstrap/docker-recovery.test.ts | 10 ++++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/lib/onboard/managed-bootstrap/docker-journal.test.ts b/src/lib/onboard/managed-bootstrap/docker-journal.test.ts index 87a169433d8..36b9917f8b5 100644 --- a/src/lib/onboard/managed-bootstrap/docker-journal.test.ts +++ b/src/lib/onboard/managed-bootstrap/docker-journal.test.ts @@ -34,8 +34,8 @@ function loadUnfinished( ): readonly DockerManagedBootstrapJournal[] { return store.listUnfinishedIdentities().map((identity) => { const record = store.load(identity); - if (!record) throw new Error(`enumerated journal ${identity} disappeared`); - return record; + expect(record, `enumerated journal ${identity} must remain loadable`).not.toBeNull(); + return record as DockerManagedBootstrapJournal; }); } const journal = Object.freeze({ diff --git a/src/lib/onboard/managed-bootstrap/docker-recovery.test.ts b/src/lib/onboard/managed-bootstrap/docker-recovery.test.ts index 101605990a7..14e6b9972e3 100644 --- a/src/lib/onboard/managed-bootstrap/docker-recovery.test.ts +++ b/src/lib/onboard/managed-bootstrap/docker-recovery.test.ts @@ -374,14 +374,16 @@ describe("Docker managed bootstrap restart recovery", () => { const badIdentity = "0".repeat(64); const delegate = fake.deps.journalStore as DockerManagedBootstrapJournalStore; + const failUnreadableRecord = (): never => { + throw new Error(`${"💥".repeat(3000)}\0tail`); + }; const mixedStore: DockerManagedBootstrapJournalStore = { ...delegate, listUnfinishedIdentities: () => [badIdentity, IDENTITY], load(bootstrapIdentity) { - if (bootstrapIdentity === badIdentity) { - throw new Error(`${"💥".repeat(3000)}\0tail`); - } - return delegate.load(bootstrapIdentity); + return bootstrapIdentity === badIdentity + ? failUnreadableRecord() + : delegate.load(bootstrapIdentity); }, }; const adapter = createDockerManagedBootstrapAdapter({ ...fake.deps, journalStore: mixedStore });