diff --git a/docs/diagrams/foreground-loss-recovery.mmd b/docs/diagrams/foreground-loss-recovery.mmd index 4d03c0a76..59361a22d 100644 --- a/docs/diagrams/foreground-loss-recovery.mmd +++ b/docs/diagrams/foreground-loss-recovery.mmd @@ -16,7 +16,8 @@ stateDiagram-v2 state advice <> Lost --> advice advice --> Inspect : [fresh up, Requested] - advice --> Down : [run recorded] + advice --> Inspect : [relay unproven] + advice --> Down : [recorded, relay proven] advice --> Up : [fresh up, Preparing] Down --> Up : down --recover Up --> Recovered : hack up @@ -40,8 +41,10 @@ stateDiagram-v2 end note note left of Inspect A fresh up has no record - for down to retire yet: - none named. + for down to retire yet, and + a run with no port whose + relay never settled has no + owner proof: none named. INV NoNeedlessWithholding end note note right of Down diff --git a/docs/diagrams/foreground-loss-recovery.png b/docs/diagrams/foreground-loss-recovery.png index cda0d2398..3ce7351b5 100644 Binary files a/docs/diagrams/foreground-loss-recovery.png and b/docs/diagrams/foreground-loss-recovery.png differ diff --git a/docs/diagrams/foreground-loss-recovery.svg b/docs/diagrams/foreground-loss-recovery.svg index 2cdaa9235..3b0bb0a25 100644 --- a/docs/diagrams/foreground-loss-recovery.svg +++ b/docs/diagrams/foreground-loss-recovery.svg @@ -1,4 +1,4 @@ -ForegroundLossRecoveryRequestGraphReady [mapped]Serve / retire intent, lockDieDieDieDieWatch / release lockStartFails / same message[fresh up, Requested][run recorded][fresh up, Preparing]down --recoverhack upRequestedServingLostUpPreparingGraphReadyDeadInspectDownRecoveredImages, review, restoreselection; nothing requested.A restart holds its lock.Ready and mapped. A restartstill holds its cleanedintent and its lock.The watch and the start'sown error race; both printthe stage message.A fresh up has no recordfor down to retire yet:none named.INV NoNeedlessWithholdingStarts the pool; retires alost start (failed-retainedor restoring) or a readyrun, port or none, data kept.Removes containers a lostVM brought back.INV NoRefusedAdviceEvery named command isaccepted, for up and restart. \ No newline at end of file +]]>ForegroundLossRecoveryRequestGraphReady [mapped]Serve / retire intent, lockDieDieDieDieWatch / release lockStartFails / same message[fresh up, Requested][relay unproven][recorded, relay proven][fresh up, Preparing]down --recoverhack upRequestedServingLostUpPreparingGraphReadyDeadInspectDownRecoveredImages, review, restoreselection; nothing requested.A restart holds its lock.Ready and mapped. A restartstill holds its cleanedintent and its lock.The watch and the start'sown error race; both printthe stage message.A fresh up has no recordfor down to retire yet, anda run with no port whoserelay never settled has noowner proof: none named.INV NoNeedlessWithholdingStarts the pool; retires alost start (failed-retainedor restoring) or a readyrun, port or none, data kept.Removes containers a lostVM brought back.INV NoRefusedAdviceEvery named command isaccepted, for up and restart. \ No newline at end of file diff --git a/docs/guides/native-candidate.md b/docs/guides/native-candidate.md index 29f6b48dd..f7122ecf9 100644 --- a/docs/guides/native-candidate.md +++ b/docs/guides/native-candidate.md @@ -2903,7 +2903,21 @@ list the run's containers again, stopped. `hack up` then refuses with nothing started and data kept, and says to run `hack down --recover`, which removes them again on the running pool, then `hack up`. An earlier `hack down --recover` of that kind that ended before it confirmed the removal is durable makes `hack up` refuse at -once (`graph_lost_removal_pending`) and name the same two commands. +once (`graph_lost_removal_pending`) and name the same two commands. The pool that +`hack up` booted may go idle and stop before you run that down. `hack down +--recover` then starts the pool again for the repair (HACK-2731): the refused +`hack up` leaves a marker for that run beside its run mapping, and the runtime +reports an unconfirmed repair from its own marker. Earlier versions answered that +the runtime was not running, and the next `hack up` printed the same refusal +again. The marker grants nothing: the runtime still checks the receipt and every +container, and a verified stop removes it. A plain `hack down` does not start the +pool for it. + +A cleanup that removed containers or networks reports a storage flush that did not +confirm, by its deadline or with a failed guest command, as `graph_cleanup_uncertain` +("Run hack down again"). Any other failure keeps its own code: a VM that was +replaced meanwhile is `guest_identity_mismatch` and a changed runtime is +`runtime_changed` (HACK-2731), not a slow flush. A foreground `hack up` (or `hack restart`) watches its pool the same way (HACK-2096). When its provider VM dies or the pool stops under it, it prints which @@ -2916,6 +2930,11 @@ code 1, and what to run next, which depends on how far the start got: pool), then `hack up`, which starts it again. This holds with or without a published port: a run with no port has no bridge routes, and the runtime then proves its dead owner's relay by that relay's clean exit (HACK-2711). + That proof needs a settled relay startup: a run with no published port whose + host dependency services never released their startup is refused + (`relay_owner_refused`). The start asks the runtime once the VM is gone, and + for such a run it names no command and says to keep the native home for + inspection (HACK-2731); `hack down --recover` does not start the pool for it. - Before any service was requested (while it resolved, reviewed, built or pulled images, or selected the restore): for a run with a record (a resumed stopped run, or a restart's old run), the same `hack down --recover`, then diff --git a/packages/runtime-core/src/provider/graph/bridges/cleanup.rs b/packages/runtime-core/src/provider/graph/bridges/cleanup.rs index ac29927f8..d63e0cf9f 100644 --- a/packages/runtime-core/src/provider/graph/bridges/cleanup.rs +++ b/packages/runtime-core/src/provider/graph/bridges/cleanup.rs @@ -406,6 +406,27 @@ fn pinned_predecessor_eligible(receipt: &Receipt) -> bool { }) } +/// Whether a cross-boot dead-owner recovery of `receipt` can prove its dead relay +/// owner, as far as host files show (HACK-2731): the host bridge registry records +/// a slot for the run, so its routes prove it, or the run's relay startup settled, +/// which a selection without routes needs for either predecessor proof +/// ([`select_predecessor`]). Presentation only (`graph foreground-owner`): read +/// without a lease or the guest. An unreadable registry, one of another version, +/// or one another pool owner wrote (`owner`, the pool's owner token, which the +/// recovery's registry check also requires) counts as no slot, and the recovery +/// revalidates everything itself. +pub(crate) fn relay_owner_provable(candidate: &Candidate, owner: &str, receipt: &Receipt) -> bool { + pinned_predecessor_eligible(receipt) || run_holds_slot(candidate, owner, &receipt.run) +} + +fn run_holds_slot(candidate: &Candidate, owner: &str, run: &str) -> bool { + state::read_bounded::(&root(candidate).join("state.json"), 65536).is_ok_and(|store| { + store.version == 1 + && store.owner == owner + && store.slots.values().any(|slot| slot.run == run) + }) +} + fn predecessor_owner( receipt: &Receipt, previous: &str, diff --git a/packages/runtime-core/src/provider/graph/dead_owner_cleanup.rs b/packages/runtime-core/src/provider/graph/dead_owner_cleanup.rs index 7f489b8fa..7453db8da 100644 --- a/packages/runtime-core/src/provider/graph/dead_owner_cleanup.rs +++ b/packages/runtime-core/src/provider/graph/dead_owner_cleanup.rs @@ -3116,4 +3116,73 @@ mod tests { fs::remove_file(fixture.0.join("restore-history.json")).unwrap(); assert!(require_historical_recovery(&fixture.0, ¤t).is_err()); } + + #[test] + fn a_live_run_relay_owner_is_provable_by_its_bridge_slot_or_a_settled_relay() { + // HACK-2731: a run with no published port proves its dead relay owner only + // through a settled relay startup (`select_predecessor`), so + // `graph foreground-owner` reports `cross_boot_relay` false for one with + // neither a bridge slot nor a settled relay, and the CLI names no + // `hack down --recover` for it. + let fixture = super::super::retained_startup::tests::Fixture::new(); + let token = Owner::load(&fixture.candidate).unwrap().token; + let provable = |receipt: &Receipt| { + bridges::cleanup::relay_owner_provable(&fixture.candidate, &token, receipt) + }; + let mut receipt = fixture.receipt(); + receipt.phase = "ready-observed".into(); + assert!(!provable(&receipt)); + receipt.relay_startup = Some(serde_json::from_value(json!({"control_only":true,"guest_root":null,"control_root":"/private/owned","control_generation":"a".repeat(32),"artifact":"e".repeat(64),"services":{}})).unwrap()); + assert!(provable(&receipt)); + let mut unsettled = receipt.clone(); + unsettled.relay_startup.as_mut().unwrap().control_only = false; + assert!(!provable(&unsettled)); + assert_eq!( + foreground_owner(&fixture.candidate, &fixture.run).unwrap()["cross_boot_relay"], + false + ); + // A bridge slot of this run proves it through the run's routes, whatever + // the relay startup; another run's slot or a foreign registry does not. + let registry = fixture.candidate.state_root.join("run/bridge-assignments"); + state::private_directory(®istry).unwrap(); + let store = |run: &str, version: u32, owner: &str| { + json!({"version":version,"owner":owner,"next_launch_serial":0,"slots":{"1":{ + "reservation":"r","run":run,"service":"web","generation":"g", + "container_id":"c","network_id":"n","boot_id":"b","phase":"reserved"}}}) + }; + let write = |value: serde_json::Value| { + state::write(®istry.join("state.json"), &value).unwrap(); + }; + write(store(&receipt.run, 1, &token)); + assert!(provable(&unsettled)); + assert_eq!( + foreground_owner(&fixture.candidate, &fixture.run).unwrap()["cross_boot_relay"], + true + ); + write(store(&"f".repeat(32), 1, &token)); + assert!(!provable(&unsettled)); + write(store(&receipt.run, 2, &token)); + assert!(!provable(&unsettled)); + // #1279 review: a registry another pool owner wrote is foreign. + write(store(&receipt.run, 1, &"9".repeat(32))); + assert!(!provable(&unsettled)); + } + + #[test] + fn foreground_owner_reports_an_unconfirmed_lost_removal_repair() { + // HACK-2731: read from the repair's host marker, so `hack down --recover` + // starts a stopped pool to finish it. + let fixture = super::super::retained_startup::tests::Fixture::new(); + let pending = |fixture: &super::super::retained_startup::tests::Fixture| { + foreground_owner(&fixture.candidate, &fixture.run).unwrap()["lost_removal_pending"] + .clone() + }; + assert_eq!(pending(&fixture), false); + fs::write( + fixture.graph().join(super::super::LOST_REMOVAL_REPAIR), + b"{}", + ) + .unwrap(); + assert_eq!(pending(&fixture), true); + } } diff --git a/packages/runtime-core/src/provider/graph/mod.rs b/packages/runtime-core/src/provider/graph/mod.rs index f08db7118..5948f3729 100644 --- a/packages/runtime-core/src/provider/graph/mod.rs +++ b/packages/runtime-core/src/provider/graph/mod.rs @@ -2121,6 +2121,16 @@ pub fn foreground_owner(candidate: &Candidate, run: &str) -> Result) -> Result<(), CandidateError> { let deadline = std::time::Instant::now() + STORAGE_BARRIER_TIMEOUT; - let output = engine - .guest() - .execute_cleanup_until(STORAGE_BARRIER, &[], deadline) - .map_err(|_| storage_barrier_refused())?; - storage_barrier_confirmed(&output) + storage_barrier_outcome( + engine + .guest() + .execute_cleanup_until(STORAGE_BARRIER, &[], deadline), + ) +} + +/// Only a barrier that did not confirm is reported as one: the exec's deadline +/// or a lost reply (`agent_protocol_uncertain`), or a guest command that did not +/// complete with exit 0 (`guest_command_failed`). Every other error keeps its +/// own code and message, so a replaced VM (`guest_identity_mismatch`) or a +/// changed runtime (`runtime_changed`) is not reported as a slow flush +/// (HACK-2731). +fn storage_barrier_outcome(result: Result) -> Result<(), CandidateError> { + match result { + Ok(output) => storage_barrier_confirmed(&output), + Err(error) if STORAGE_BARRIER_UNCONFIRMED.contains(&error.code) => { + Err(storage_barrier_refused()) + } + Err(error) => Err(error), + } } +/// The exec errors of a barrier that did not confirm ([`storage_barrier_outcome`]). +const STORAGE_BARRIER_UNCONFIRMED: [&str; 2] = ["agent_protocol_uncertain", "guest_command_failed"]; + fn storage_barrier_refused() -> CandidateError { error( "graph_cleanup_uncertain", @@ -2819,6 +2848,31 @@ mod storage_barrier_tests { assert!(refused.message.contains("Run hack down again.")); } } + + #[test] + fn only_an_unconfirmed_barrier_reports_the_barrier_refusal() { + // A deadline or lost reply, and a guest command that did not exit 0, did + // not confirm the flush: they report the barrier's own refusal. + for code in STORAGE_BARRIER_UNCONFIRMED { + let refused = + storage_barrier_outcome(Err(CandidateError::new(code, "failed"))).unwrap_err(); + assert_eq!(refused.code, "graph_cleanup_uncertain"); + } + // A replaced VM or a changed runtime keeps its own code and message. + let kept_codes = [ + "guest_identity_mismatch", + "runtime_changed", + "provider_busy", + ]; + for code in kept_codes { + let kept = storage_barrier_outcome(Err(CandidateError::new(code, "kept"))).unwrap_err(); + assert_eq!(kept.code, code); + assert_eq!(kept.message, "kept"); + } + storage_barrier_outcome(Ok(STORAGE_BARRIER_DONE.into())).unwrap(); + let unconfirmed = storage_barrier_outcome(Ok(String::new())).unwrap_err(); + assert_eq!(unconfirmed.code, "graph_cleanup_uncertain"); + } } /// The compiled `Healthcheck` to compare with a container's, accepting one created before diff --git a/scripts/lib/tla-runtime-models.ts b/scripts/lib/tla-runtime-models.ts index af45c8899..f912bccfc 100644 --- a/scripts/lib/tla-runtime-models.ts +++ b/scripts/lib/tla-runtime-models.ts @@ -3984,11 +3984,12 @@ const contracts: readonly ModelContract[] = [ // pinned-relay (HACK-2711), no-cross-boot (HACK-2714), failed-only // (01ab67fa: only a `failed-retained` lost start) and withhold-requested // (#1253's message on the fixed runtime) restore one rule of the runtime or - // message before the VM-loss recovery fix. + // message before the VM-loss recovery fix. live-relay (HACK-2731) is + // #1273's message once ready, which ignored an unsettled relay startup. // restart-recovers is the reachability witness of a recovered restart. name: "foreground-loss-recovery", module: "ForegroundLossRecovery", - states: 416, + states: 596, invariant: "NoRefusedAdvice", fields: ['outcome = "refused"', 'lostAt = "Preparing"'], alternativeWitnesses: [['outcome = "refused"', 'lostAt = "Requested"']], @@ -4092,6 +4093,23 @@ const contracts: readonly ModelContract[] = [ ], ], }, + { + // HACK-2731 (#1273 review): the message once ready names + // `hack down --recover` for a run with no published port whose relay + // startup had not settled; the runtime refuses it + // (`relay_owner_refused`), since its no-route proof needs a settled + // relay. + name: "live-relay", + negative: true, + invariant: "NoRefusedAdvice", + fields: [ + 'outcome = "refused"', + "ports = FALSE", + "settled = FALSE", + 'msg = "downUp"', + 'lostAt = "GraphReady"', + ], + }, { // HACK-2714 (real VM, row 2): no cross-boot retirement of a start lost // before ready, so the down keeps `runtime_not_running`. diff --git a/src/backends/native-cross-boot-recovery.ts b/src/backends/native-cross-boot-recovery.ts index be6af5f8b..a57a813cd 100644 --- a/src/backends/native-cross-boot-recovery.ts +++ b/src/backends/native-cross-boot-recovery.ts @@ -1,3 +1,5 @@ +import { isRecord } from "../lib/guards.ts"; + /** * Which receipts of a run whose foreground owner and VM were lost the runtime's * cross-boot dead-owner recovery retires once `hack down --recover` has started @@ -38,19 +40,165 @@ export const NATIVE_CROSS_BOOT_START_PHASES: ReadonlySet = new Set([ /** * Whether the cross-boot recovery admits a receipt as `graph foreground-owner` - * reported it: a live phase, or a lost start the runtime itself admits. A - * pending same-boot recovery (`live_owner_recovery`) resumes only in its own - * boot, so it is never one. Whether the owner exited is the caller's check. + * reported it: a live phase whose dead relay owner the runtime can prove + * (`cross_boot_relay`: the run holds a bridge slot, or its relay startup + * settled; a run with no published port and an unsettled relay startup is + * refused with `relay_owner_refused`, HACK-2731), or a lost start the runtime + * itself admits. A pending same-boot recovery (`live_owner_recovery`) resumes + * only in its own boot, so it is never one. Whether the owner exited is the + * caller's check. */ export function nativeCrossBootRecoverable(selection: { readonly phase: string; readonly crossBootStart: boolean; + readonly crossBootRelay: boolean; readonly liveOwnerRecovery: string | null; }): boolean { return ( selection.liveOwnerRecovery === null && - (NATIVE_RECOVERABLE_LIVE_PHASES.has(selection.phase) || + ((NATIVE_RECOVERABLE_LIVE_PHASES.has(selection.phase) && + selection.crossBootRelay) || (NATIVE_CROSS_BOOT_START_PHASES.has(selection.phase) && selection.crossBootStart)) ); } + +/** + * Whether the cross-boot recovery refuses a live receipt only because it cannot + * prove the dead relay owner (`cross_boot_relay` false: no published port and + * an unsettled relay startup, HACK-2731). A receipt in any other phase is not + * refused for that reason: a ready-stage loss whose receipt is not live (a VM + * lost during the owner's own stop, `cleanup-intent` or `stopped-data-retained`) + * keeps the down advice, whose own paths handle that phase (#1279 review). + */ +export function nativeLiveRelayUnprovable(selection: { + readonly phase: string; + readonly crossBootRelay: boolean; +}): boolean { + return ( + NATIVE_RECOVERABLE_LIVE_PHASES.has(selection.phase) && + !selection.crossBootRelay + ); +} + +const RECEIPT_SHA = /^[a-f0-9]{64}$/; +const RECOVERY_CODE = /^[a-z][a-z0-9_]{0,63}$/; +const FOREGROUND_STATES = new Set(["absent", "running", "exited", "uncertain"]); + +/** What `graph foreground-owner` selected; it grants no recovery authority. */ +export type NativeForegroundOwnerSelection = { + readonly phase: string; + readonly receiptSha256: string; + readonly foreground: "absent" | "running" | "exited" | "uncertain"; + /** Original receipt digest of an interrupted same-boot dead-owner recovery. */ + readonly liveOwnerRecovery: string | null; + readonly deadOwnerRecovery: string | null; + /** Guest completion commit. Retirement still finishes and verifies reservation release. */ + readonly deadOwnerRecoveryComplete: boolean; + readonly deadOwnerRecoveryError: string | null; + readonly failedStartRecoverable: boolean; + /** + * The runtime's cross-boot recovery admits this receipt as a start lost before + * ready (`cross_boot_start`: a lost-start phase, a settled relay startup and no + * cleanup marker). Absent from an older runtime, which never admitted one. + */ + readonly crossBootStart: boolean; + /** + * That recovery can prove the dead owner's relay (`cross_boot_relay`): the + * run holds a bridge slot, or its relay startup settled (HACK-2731). Absent + * from an older runtime, which did not report it: true, as before. + */ + readonly crossBootRelay: boolean; + /** + * A lost-removal repair whose storage barrier has not confirmed + * (`lost_removal_pending`, HACK-2719), read from its host marker. Absent + * from an older runtime: false. + */ + readonly lostRemovalPending: boolean; +}; + +/** + * Parse a `graph foreground-owner` reply for `run`: the one parser of that + * reply, shared by `hack down` and a lost start's advice so the two cannot + * read it differently (#1273 review). Undefined for any reply that is not + * exactly a selection of this run and owner. + */ +export function parseNativeForegroundOwner( + value: unknown, + run: { readonly run: string; readonly owner: string } +): NativeForegroundOwnerSelection | undefined { + if ( + !isRecord(value) || + value.version !== 1 || + !optionalBoolean(value.failed_start_recoverable) || + !optionalBoolean(value.cross_boot_start) || + !optionalBoolean(value.cross_boot_relay) || + !optionalBoolean(value.lost_removal_pending) || + value.run !== run.run || + value.owner !== run.owner || + typeof value.phase !== "string" || + typeof value.receipt_sha256 !== "string" || + !RECEIPT_SHA.test(value.receipt_sha256) || + typeof value.foreground !== "string" || + !FOREGROUND_STATES.has(value.foreground) || + (value.foreground !== "running" && + !( + value.live_owner_recovery === null || + (typeof value.live_owner_recovery === "string" && + RECEIPT_SHA.test(value.live_owner_recovery)) + )) || + (value.foreground !== "running" && + !( + value.dead_owner_recovery === undefined || + value.dead_owner_recovery === null || + (typeof value.dead_owner_recovery === "string" && + RECEIPT_SHA.test(value.dead_owner_recovery)) + )) || + (value.foreground !== "running" && + !( + value.dead_owner_recovery_complete === undefined || + typeof value.dead_owner_recovery_complete === "boolean" + )) || + (value.foreground !== "running" && + !( + value.dead_owner_recovery_error === undefined || + value.dead_owner_recovery_error === null || + (typeof value.dead_owner_recovery_error === "string" && + RECOVERY_CODE.test(value.dead_owner_recovery_error)) + )) + ) { + return; + } + return { + phase: value.phase, + failedStartRecoverable: value.failed_start_recoverable === true, + crossBootStart: value.cross_boot_start === true, + crossBootRelay: value.cross_boot_relay !== false, + lostRemovalPending: value.lost_removal_pending === true, + receiptSha256: value.receipt_sha256, + foreground: + value.foreground as NativeForegroundOwnerSelection["foreground"], + liveOwnerRecovery: + value.foreground !== "running" && + typeof value.live_owner_recovery === "string" + ? value.live_owner_recovery + : null, + deadOwnerRecovery: + value.foreground !== "running" && + typeof value.dead_owner_recovery === "string" + ? value.dead_owner_recovery + : null, + deadOwnerRecoveryComplete: + value.foreground !== "running" && + value.dead_owner_recovery_complete === true, + deadOwnerRecoveryError: + value.foreground !== "running" && + typeof value.dead_owner_recovery_error === "string" + ? value.dead_owner_recovery_error + : null, + }; +} + +function optionalBoolean(value: unknown): boolean { + return value === undefined || typeof value === "boolean"; +} diff --git a/src/backends/native-project-down.ts b/src/backends/native-project-down.ts index b094b2cc5..cc97e190b 100644 --- a/src/backends/native-project-down.ts +++ b/src/backends/native-project-down.ts @@ -7,7 +7,9 @@ import { } from "../lib/project-env-config.ts"; import { NATIVE_RECOVERABLE_LIVE_PHASES, + type NativeForegroundOwnerSelection, nativeCrossBootRecoverable, + parseNativeForegroundOwner, } from "./native-cross-boot-recovery.ts"; import { awaitNativeEndedBootOwner } from "./native-ended-boot-owner.ts"; import { @@ -50,11 +52,13 @@ import { lostRemovalPending, } from "./native-project-retained.ts"; import { + clearNativeLostRemoval, describeNativeRunEnvironmentChange, loadNativeProjectRun, loadNativeRestartIntent, type NativeProjectRun, type NativeProjectRunScope, + nativeLostRemovalRecorded, nativeProjectStartupPending, nativeRunEnvironmentChange, removeNativeProjectRun, @@ -140,29 +144,7 @@ function verify( } } } -const RECEIPT_SHA = /^[a-f0-9]{64}$/; -const RECOVERY_CODE = /^[a-z][a-z0-9_]{0,63}$/; - -const FOREGROUND_STATES = new Set(["absent", "running", "exited", "uncertain"]); -/** What `graph foreground-owner` selected; it grants no recovery authority. */ -type ForegroundOwnerSelection = { - readonly phase: string; - readonly receiptSha256: string; - readonly foreground: "absent" | "running" | "exited" | "uncertain"; - /** Original receipt digest of an interrupted same-boot dead-owner recovery. */ - readonly liveOwnerRecovery: string | null; - readonly deadOwnerRecovery: string | null; - /** Guest completion commit. Retirement still finishes and verifies reservation release. */ - readonly deadOwnerRecoveryComplete: boolean; - readonly deadOwnerRecoveryError: string | null; - readonly failedStartRecoverable: boolean; - /** - * The runtime's cross-boot recovery admits this receipt as a start lost before - * ready (`cross_boot_start`: a lost-start phase, a settled relay startup and no - * cleanup marker). Absent from an older runtime, which never admitted one. - */ - readonly crossBootStart: boolean; -}; +type ForegroundOwnerSelection = NativeForegroundOwnerSelection; /** * The command a refusal names. Plain `hack down` reaches the same owner paths @@ -229,75 +211,11 @@ async function selectForegroundOwner(opts: { args: ["graph", "foreground-owner", "--run-id", opts.run.run, "--json"], timeoutMs: 15_000, }); - if ( - !isRecord(value) || - value.version !== 1 || - !optionalBoolean(value.failed_start_recoverable) || - !optionalBoolean(value.cross_boot_start) || - value.run !== opts.run.run || - value.owner !== opts.run.owner || - typeof value.phase !== "string" || - typeof value.receipt_sha256 !== "string" || - !RECEIPT_SHA.test(value.receipt_sha256) || - typeof value.foreground !== "string" || - !FOREGROUND_STATES.has(value.foreground) || - (value.foreground !== "running" && - !( - value.live_owner_recovery === null || - (typeof value.live_owner_recovery === "string" && - RECEIPT_SHA.test(value.live_owner_recovery)) - )) || - (value.foreground !== "running" && - !( - value.dead_owner_recovery === undefined || - value.dead_owner_recovery === null || - (typeof value.dead_owner_recovery === "string" && - RECEIPT_SHA.test(value.dead_owner_recovery)) - )) || - (value.foreground !== "running" && - !( - value.dead_owner_recovery_complete === undefined || - typeof value.dead_owner_recovery_complete === "boolean" - )) || - (value.foreground !== "running" && - !( - value.dead_owner_recovery_error === undefined || - value.dead_owner_recovery_error === null || - (typeof value.dead_owner_recovery_error === "string" && - RECOVERY_CODE.test(value.dead_owner_recovery_error)) - )) - ) { + const selection = parseNativeForegroundOwner(value, opts.run); + if (selection === undefined) { throw ownerRecoveryRefused(opts.verb); } - return { - phase: value.phase, - failedStartRecoverable: value.failed_start_recoverable === true, - crossBootStart: value.cross_boot_start === true, - receiptSha256: value.receipt_sha256, - foreground: value.foreground as ForegroundOwnerSelection["foreground"], - liveOwnerRecovery: - value.foreground !== "running" && - typeof value.live_owner_recovery === "string" - ? value.live_owner_recovery - : null, - deadOwnerRecovery: - value.foreground !== "running" && - typeof value.dead_owner_recovery === "string" - ? value.dead_owner_recovery - : null, - deadOwnerRecoveryComplete: - value.foreground !== "running" && - value.dead_owner_recovery_complete === true, - deadOwnerRecoveryError: - value.foreground !== "running" && - typeof value.dead_owner_recovery_error === "string" - ? value.dead_owner_recovery_error - : null, - }; -} - -function optionalBoolean(value: unknown): boolean { - return value === undefined || typeof value === "boolean"; + return selection; } /** @@ -830,7 +748,10 @@ export const NATIVE_RESTART_INTENT_UNREADABLE_NOTE = * retained * stop (whose unadmitted owner is retired without the pool) and an unreadable * selection are all false: the caller keeps its refusal and never starts a pool - * it could not then use. + * it could not then use. A ready run counts only when the runtime can prove its + * dead relay owner (`crossBootRelay`, HACK-2731). Two retained stops also need + * the pool: one with an interrupted frontend finalization (HACK-2456), and, + * for `hack down --recover`, one whose lost-removal repair is owed (HACK-2731). */ async function deadOwnerOfLiveRun(opts: { readonly runtime: NativeRuntimeSelection; @@ -838,6 +759,8 @@ async function deadOwnerOfLiveRun(opts: { readonly projectRoot: string; readonly run: NativeProjectRun; readonly invoke: typeof invokeNativeRuntime; + /** `hack down --recover`: an owed lost-removal repair also starts the pool. */ + readonly recover?: boolean; }): Promise { try { const selection = await selectForegroundOwner(opts); @@ -853,13 +776,29 @@ async function deadOwnerOfLiveRun(opts: { ) { return true; } + if ( + selection.foreground !== "absent" || + selection.phase !== "stopped-data-retained" + ) { + return false; + } + // A retained stop whose lost-removal repair is owed (HACK-2731): a retained + // start found containers a lost VM brought back (its marker), or a repair + // ended before its storage barrier confirmed (the runtime's marker). Only + // `hack down --recover` repairs it, on a running pool, and the pool that + // start booted may have gone idle and stopped since. + if ( + opts.recover === true && + (selection.lostRemovalPending || + (await nativeLostRemovalRecorded({ ...opts.scope, run: opts.run }))) + ) { + return true; + } // A recovery that stopped the graph and retired the owner's publication, // then failed in its frontend finalization (the shared HTTPS lease, HACK-2456 // seen on a real VM), leaves a retained stop with no owner and an // interrupted frontend lifetime. Finishing it needs a running pool. return ( - selection.foreground === "absent" && - selection.phase === "stopped-data-retained" && ( await inspectNativeProjectFinalizationLifetime({ scope: opts.scope, @@ -887,6 +826,8 @@ async function inspectOrStartStoppedPool(opts: { readonly projectRoot: string; readonly run: NativeProjectRun; readonly invoke: typeof invokeNativeRuntime; + /** `hack down --recover` (see {@link deadOwnerOfLiveRun}). */ + readonly recover?: boolean; /** Where the one-line wait notice goes; stderr by default. */ readonly notice?: (line: string) => void; readonly poolBootEnded?: (home: string) => Promise; @@ -1181,6 +1122,7 @@ async function nativeProjectDownOnce(opts: { let initial = await inspectOrStartStoppedPool({ inspect, startStoppedPool: opts.startStoppedPool === true, + recover: opts.recover === true, scope: opts.scope, runtime: opts.runtime, projectRoot: opts.scope.projectRoot, @@ -1356,12 +1298,20 @@ async function nativeProjectDownOnce(opts: { // `hack down --recover` only: see `lostContainerRemovals`. // Verify a stopped run, first removing containers a lost VM brought back. // The note prints only once the re-inspection verifies the stop. + // The retained start's lost-removal marker (HACK-2731), once the stop is + // verified with no container to remove again. Advisory: a marker a failed + // removal leaves costs one more pool start, never a wrong result. + const clearLostRemoval = () => + clearNativeLostRemoval(opts.scope).catch(() => undefined); const verifyStoppedRepairing = async (snapshot: unknown): Promise => { if (!(opts.recover === true && lostContainerRemovals(snapshot))) { verify(snapshot, run, true); if (stoppedRetained(snapshot) && lostRemovalPending(snapshot)) { throw new ClosedCliError(NATIVE_LOST_REMOVAL_PENDING); } + if (!lostContainerRemovals(snapshot)) { + await clearLostRemoval(); + } return; } try { @@ -1384,6 +1334,7 @@ async function nativeProjectDownOnce(opts: { throw error; } verify(await inspect(), run, true); + await clearLostRemoval(); (opts.notice ?? ((line: string) => process.stderr.write(`${line}\n`)))( NATIVE_LOST_REMOVAL_NOTE ); diff --git a/src/backends/native-project-retained-startup.ts b/src/backends/native-project-retained-startup.ts index da1961ae2..8eddb978b 100644 --- a/src/backends/native-project-retained-startup.ts +++ b/src/backends/native-project-retained-startup.ts @@ -6,10 +6,11 @@ import { confirmedNativeRetainedGraph, lostContainerRemovals, } from "./native-project-retained.ts"; -import type { - loadNativeProjectRun, - NativeProjectRun, - NativeProjectRunScope, +import { + type loadNativeProjectRun, + type NativeProjectRun, + type NativeProjectRunScope, + recordNativeLostRemoval, } from "./native-project-run.ts"; import { type invokeNativeRuntime, @@ -183,11 +184,21 @@ export async function reselectNativeRetainedStartup(opts: { run: opts.run, invoke: opts.invoke, runtimePhase: preflight.runtimePhase, + onLostRemoval: recordLostRemovalOf(opts.scope, opts.run), }); requireActive(opts.signal); return preflight.flags; } +/** The `onLostRemoval` of a retained start of `run` in `scope`: it records the + * lost-removal marker that `hack down --recover` reads (HACK-2731). */ +export function recordLostRemovalOf( + scope: NativeProjectRunScope, + run: NativeProjectRun +): () => Promise { + return () => recordNativeLostRemoval({ ...scope, run }); +} + /** On a running pool, the retained run's graph must still be its confirmed * retained stop before a start is requested for it. */ export async function confirmRunningRetainedGraph(opts: { @@ -196,6 +207,8 @@ export async function confirmRunningRetainedGraph(opts: { readonly run: NativeProjectRun; readonly invoke: typeof invokeNativeRuntime; readonly runtimePhase: "running" | "stopped"; + /** Called, best effort, before the lost-removal refusal (HACK-2731). */ + readonly onLostRemoval?: () => Promise; }): Promise { if (opts.runtimePhase !== "running") { return; @@ -208,10 +221,11 @@ export async function confirmRunningRetainedGraph(opts: { invoke: opts.invoke, }); if (!confirmedNativeRetainedGraph(observed, opts.run)) { - throw unconfirmedRetainedGraph( + throw await unconfirmedRetainedGraph( observed, opts.run, - "Native project already has an owned run mapping that is not safely stopped; inspect it before starting another run." + "Native project already has an owned run mapping that is not safely stopped; inspect it before starting another run.", + opts.onLostRemoval ); } } @@ -255,20 +269,25 @@ export async function verifyNativeResumedRetainedGraph(opts: { readonly projectRoot: string; readonly run: NativeProjectRun | null | undefined; readonly invoke: typeof invokeNativeRuntime; + /** Called, best effort, before the lost-removal refusal (HACK-2731). */ + readonly onLostRemoval?: () => Promise; }): Promise { if (!opts.run) { return; } const observed = await inspectNativeProjectGraph({ startupWait: true, - ...opts, + runtime: opts.runtime, + projectRoot: opts.projectRoot, + invoke: opts.invoke, run: opts.run.run, }); if (!confirmedNativeRetainedGraph(observed, opts.run)) { - throw unconfirmedRetainedGraph( + throw await unconfirmedRetainedGraph( observed, opts.run, - "Native resumed retained graph differs; no graph restore was requested." + "Native resumed retained graph differs; no graph restore was requested.", + opts.onLostRemoval ); } return { run: opts.run.run, snapshot: observed }; @@ -286,12 +305,16 @@ export const NATIVE_RETAINED_LOST_REMOVAL = "This run is stopped with its data kept, but stopped containers that its last hack down had removed are listed again, most likely because the VM was lost seconds after that down, before the removal reached the guest disk. Nothing was started. Run hack down --recover to remove them again (data kept), then hack up."; /** A retained graph that is not the confirmed stop: the lost-removal shape of - * this exact run names its repair, anything else keeps `fallback`. */ -function unconfirmedRetainedGraph( + * this exact run names its repair, anything else keeps `fallback`. The + * lost-removal shape is first recorded (`onLostRemoval`, best effort) so that + * `hack down --recover` starts the pool for the repair even after the pool + * this start booted has gone idle and stopped (HACK-2731). */ +async function unconfirmedRetainedGraph( observed: unknown, run: NativeProjectRun, - fallback: string -): ClosedCliError { + fallback: string, + onLostRemoval?: () => Promise +): Promise { const receipt = isRecord(observed) && isRecord(observed.receipt) ? observed.receipt : {}; const thisRun = @@ -299,9 +322,9 @@ function unconfirmedRetainedGraph( receipt.owner === run.owner && receipt.namespace === run.namespace && receipt.plan_id === run.planId; - return new ClosedCliError( - thisRun && lostContainerRemovals(observed) - ? NATIVE_RETAINED_LOST_REMOVAL - : fallback - ); + if (!(thisRun && lostContainerRemovals(observed))) { + return new ClosedCliError(fallback); + } + await onLostRemoval?.().catch(() => undefined); + return new ClosedCliError(NATIVE_RETAINED_LOST_REMOVAL); } diff --git a/src/backends/native-project-run.ts b/src/backends/native-project-run.ts index 704f5213a..ba19ca51b 100644 --- a/src/backends/native-project-run.ts +++ b/src/backends/native-project-run.ts @@ -460,7 +460,7 @@ async function verifyIgnore(ignore: string) { async function paths( opts: NativeProjectRunScope, create: boolean, - kind: "run" | "restart" | "down-hooks" = "run" + kind: "run" | "restart" | "down-hooks" | "lost-removal" = "run" ) { const identity = await scope(opts); const internal = join(identity.projectDir, ".internal"); @@ -2079,6 +2079,93 @@ export async function nativeProjectDownHookPaths( const p = await paths(opts, create, "down-hooks"); return { root: p.root, file: p.file, lock: p.lock }; } +/** The run a lost-removal marker names. */ +export type NativeLostRemovalRun = Pick< + NativeProjectRun, + "run" | "owner" | "namespace" | "planId" +>; + +function lostRemovalMarker(run: NativeLostRemovalRun): string { + return JSON.stringify({ + version: 1, + lostRemoval: { + run: run.run, + owner: run.owner, + namespace: run.namespace, + planId: run.planId, + }, + }); +} + +/** + * Note that a retained start found containers a lost VM brought back for + * `run` (HACK-2719): its receipt says they were removed, the guest lists them + * again, and only `hack down --recover` on a running pool removes them. The + * pool `hack up` booted may go idle and stop before the user runs that down; + * this marker lets the down start it again (HACK-2731). It is advisory: it + * grants nothing, the runtime revalidates the receipt and every container, and + * a stale marker costs one pool start, after which a verified stop clears it. + * A later marker replaces an earlier one. + */ +export async function recordNativeLostRemoval( + opts: NativeProjectRunScope & { readonly run: NativeLostRemovalRun } +): Promise { + const p = await paths(opts, true, "lost-removal"); + // Named after the marker, so a removed mapping can sweep a leftover. + const temp = `${p.file}.${randomUUID()}.tmp`; + try { + await write(temp, lostRemovalMarker(opts.run)); + await rename(temp, p.file); + await sync(p.root); + } finally { + await unlink(temp).catch(() => undefined); + } +} + +/** Whether a lost-removal marker names exactly `run`; unreadable is false. */ +export async function nativeLostRemovalRecorded( + opts: NativeProjectRunScope & { readonly run: NativeLostRemovalRun } +): Promise { + try { + const p = await paths(opts, false, "lost-removal"); + return JSON.stringify(await read(p.file)) === lostRemovalMarker(opts.run); + } catch { + return false; + } +} + +/** + * Remove the lost-removal marker once a down verified the run stopped, or once + * the run mapping it names is removed, with any temporary file an interrupted + * {@link recordNativeLostRemoval} left beside it. + */ +export async function clearNativeLostRemoval( + opts: NativeProjectRunScope +): Promise { + const p = await paths(opts, false, "lost-removal"); + const prefix = `${basename(p.file)}.`; + const names = [ + basename(p.file), + ...(await readdir(p.root)).filter( + (name) => name.startsWith(prefix) && name.endsWith(".tmp") + ), + ]; + let removed = false; + for (const name of names) { + try { + await unlink(join(p.root, name)); + removed = true; + } catch (error) { + if (!(isRecord(error) && error.code === "ENOENT")) { + throw error; + } + } + } + if (removed) { + await sync(p.root); + } +} + /** Establish excluded metadata before source identity is reviewed. */ export async function prepareNativeProjectRunStorage( opts: NativeProjectRunScope @@ -2350,6 +2437,9 @@ export async function removeNativeProjectRun( } catch { throw refused(); } + // The lost-removal marker names this mapping's run; it is advisory, so a + // marker that cannot be removed never refuses the removal (HACK-2731). + await clearNativeLostRemoval(opts).catch(() => undefined); } /** Record completion of down hooks as well as backend cleanup before a retry can resume. */ diff --git a/src/backends/native-project-start.ts b/src/backends/native-project-start.ts index 02474221d..5536adc86 100644 --- a/src/backends/native-project-start.ts +++ b/src/backends/native-project-start.ts @@ -48,7 +48,11 @@ import { import { nativeStartOutcomeUnknown } from "../lib/native-up-refusals.ts"; import { adaptNativeAwsEnvironment } from "./native-aws-environment.ts"; import { scheduleNativeAwsExpiryWarnings } from "./native-aws-expiry.ts"; -import { nativeCrossBootRecoverable } from "./native-cross-boot-recovery.ts"; +import { + nativeCrossBootRecoverable, + nativeLiveRelayUnprovable, + parseNativeForegroundOwner, +} from "./native-cross-boot-recovery.ts"; import type { NativeDependencyOwnerResolver } from "./native-dependency-owners.ts"; import { emptyNativeDependencyPlanId } from "./native-dependency-plan.ts"; import { @@ -199,6 +203,7 @@ import { selectNativeRetainedImages } from "./native-project-retained-images.ts" import { confirmRunningRetainedGraph, preflightNativeRetainedStartup, + recordLostRemovalOf, reselectNativeRetainedStartup, runtimeUpJoiningChangedPool, verifyNativeResumedRetainedGraph, @@ -2259,6 +2264,7 @@ async function selectNativeStartup(opts: { run: retained, invoke: opts.invoke, runtimePhase: preflight.runtimePhase, + onLostRemoval: recordLostRemovalOf(opts.scope, retained), }); } const restore = opts.restore ?? retained ?? undefined; @@ -3563,7 +3569,7 @@ async function startNativeProjectAttempt( * retained run, or a restart's old run). A fresh `up` has none until its * mapping is saved (HACK-2096). */ - readonly onSelected?: (recorded: boolean, run?: string) => void; + readonly onSelected?: (recorded: boolean, run?: NativeProjectRun) => void; /** * The first service of this run is being requested from the runtime. A * run lost from here until `onReady` is retired across the boot by @@ -3578,9 +3584,10 @@ async function startNativeProjectAttempt( * (HACK-2096). A fresh `up` that is ready but not yet mapped is still * `requested`: `down` would find no run. So is a started return before * its owner's ready line: it is mapped, but the runtime has not confirmed - * the start, and a loss there is HACK-2714's lost start. + * the start, and a loss there is HACK-2714's lost start. `run` is the + * saved mapping, for the lost-VM advice's selection (HACK-2731). */ - readonly onReady?: () => void; + readonly onReady?: (run: NativeProjectRun) => void; /** * The graph is confirmed stopped (its receipt shows nothing running or * reserved). From then on the start no longer needs its VM, and the pool @@ -3632,7 +3639,7 @@ async function startNativeProjectAttempt( endedBootOwnerWaitMs: deps.endedBootOwnerWaitMs, }); requireActiveStartup(opts.signal); - graph.onSelected?.(restore !== undefined, restore?.run); + graph.onSelected?.(restore !== undefined, restore); const runtimeMetadata = nativeRuntimeMetadataSelected({ selection: opts.runtimeMetadata, restore, @@ -4036,6 +4043,9 @@ async function startNativeProjectAttempt( projectRoot: opts.scope.projectRoot, run: extension ? undefined : retained, invoke: deps.invoke, + onLostRemoval: retained + ? recordLostRemovalOf(opts.scope, retained) + : undefined, }); const reviewedBranch = await prepareNativeReviewBranch({ runtime: opts.runtime, @@ -4550,7 +4560,7 @@ async function startNativeProjectAttempt( // The owner's ready line of a started return: confirmed and // mapped, so a loss from here is retired by `down --recover`. // This holds even when the graph owner settled meanwhile. - graph.onReady?.(); + graph.onReady?.(mapped.persistedMapping); if (serveSettled || httpsClosing) { return; } @@ -4710,7 +4720,7 @@ async function startNativeProjectAttempt( // `graph_foreground_owner_exited_unadmitted`, HACK-2714); it is // ready only at the owner's ready line (`allReady`). if (!returnAtStarted) { - graph.onReady?.(); + graph.onReady?.(persistedMapping); } // The HTTPS owner admits a lease only under the provider lease, for a // ready graph: a started return takes it at the owner's ready line. @@ -5093,10 +5103,12 @@ export async function startNativeProject( // How far the start got, for the lost-VM message (HACK-2096): preparing // (with or without a run record for `down --recover`), services requested, // or ready and mapped. - // The recorded run this start resumes, for the lost-start check below. - let selectedRun: string | undefined = opts.restore?.run; - // A recorded run lost after its services were requested: whether the runtime - // would retire it, asked once the VM was lost (#1273 review). + // The recorded run this start resumes, or once ready its saved mapping, for + // the lost-start check below. + let selectedRun: NativeProjectRun | undefined = opts.restore; + // A recorded run lost after its services were requested, or a ready one: + // whether the runtime would retire it, asked once the VM was lost (#1273 + // review, HACK-2731). const lostStage = () => nativeLostStartRetirable({ loss, @@ -5189,7 +5201,8 @@ export async function startNativeProject( recorded: loss.stage === "preparing" && loss.recorded, }; }, - onReady: () => { + onReady: (run) => { + selectedRun = run; loss = { stage: "ready" }; }, onStopped: () => { @@ -5235,8 +5248,14 @@ export class NativeForegroundVmLostError extends ClosedCliError { readonly loss: NativeForegroundLossStage; readonly cause: unknown; }) { + // The cause's own `hack down --recover` sentence goes wherever the stage + // message decides the command: a requested loss, and a ready one the + // runtime cannot retire (`retirable` false, #1279 review), whose message + // names no command. const cause = nativeLostVmCauseLine(opts.cause, { - dropRecoverAdvice: opts.loss.stage === "requested", + dropRecoverAdvice: + opts.loss.stage === "requested" || + (opts.loss.stage === "ready" && opts.loss.retirable === false), }); super( [ @@ -5285,52 +5304,69 @@ async function lostVmFailure(opts: { } /** - * A recorded run lost after its services were requested is retirable by - * `hack down --recover` only when the runtime's cross-boot recovery admits its - * receipt, by the same predicate the down uses to start the pool - * (`nativeCrossBootRecoverable`): a live phase (`started-observed` included: a - * restore that started every service, real VM at d19aa31a), or a lost start - * with `cross_boot_start` (settled relay and host dependency startup, no cleanup - * marker). The selection reads host files only, - * so it works with the VM gone. Any other stage is returned as it is; a failed - * or older selection leaves the run not retirable, so no refused command is - * named (#1273 review). + * Whether `hack down --recover` retires a run lost at `loss`, asked once the + * VM was lost, by the same predicate the down uses to start the pool + * (`nativeCrossBootRecoverable`) on the same parse of `graph foreground-owner` + * (`parseNativeForegroundOwner`). The selection reads host files only, so it + * works with the VM gone. + * + * - A recorded run lost after its services were requested: a live phase + * (`started-observed` included: a restore that started every service, real + * VM at d19aa31a) whose relay owner the runtime can prove, or a lost start + * with `cross_boot_start` (settled relay and host dependency startup, no + * cleanup marker). No run, or a failed or foreign selection, leaves it not + * retirable, so no refused command is named (#1273 review). + * - A ready run: retirable unless the selection shows a live receipt whose + * relay owner the runtime cannot prove (`nativeLiveRelayUnprovable`: + * `cross_boot_relay` false, no published port and an unsettled host relay + * startup, HACK-2731). Any other phase (a VM lost during the owner's own + * stop leaves `cleanup-intent` or `stopped-data-retained`), an unknown run + * or a failed read keeps the down advice it always had (#1279 review). + * + * Any other stage is returned as it is. */ export async function nativeLostStartRetirable(opts: { readonly loss: NativeForegroundLossStage; readonly runtime: NativeRuntimeSelection; readonly projectRoot: string; - readonly run: string | undefined; + readonly run: Pick | undefined; readonly invoke: typeof invokeNativeRuntime; }): Promise { - if (opts.loss.stage !== "requested" || !opts.loss.recorded) { + const recorded = + opts.loss.stage === "ready" || + (opts.loss.stage === "requested" && opts.loss.recorded); + if (!recorded) { return opts.loss; } - if (opts.run === undefined) { - return { ...opts.loss, retirable: false }; + const run = opts.run; + const selection = + run === undefined + ? undefined + : parseNativeForegroundOwner( + await opts + .invoke({ + runtime: opts.runtime, + cwd: opts.projectRoot, + args: [ + "graph", + "foreground-owner", + "--run-id", + run.run, + "--json", + ], + timeoutMs: 5000, + }) + .catch(() => undefined), + run + ); + if (opts.loss.stage === "ready") { + return selection === undefined + ? opts.loss + : { ...opts.loss, retirable: !nativeLiveRelayUnprovable(selection) }; } - const selected = await opts - .invoke({ - runtime: opts.runtime, - cwd: opts.projectRoot, - args: ["graph", "foreground-owner", "--run-id", opts.run, "--json"], - timeoutMs: 5000, - }) - .catch(() => undefined); return { ...opts.loss, - retirable: - isRecord(selected) && - selected.run === opts.run && - typeof selected.phase === "string" && - nativeCrossBootRecoverable({ - phase: selected.phase, - crossBootStart: selected.cross_boot_start === true, - liveOwnerRecovery: - typeof selected.live_owner_recovery === "string" - ? selected.live_owner_recovery - : null, - }), + retirable: selection !== undefined && nativeCrossBootRecoverable(selection), }; } @@ -5368,6 +5404,8 @@ export function restartPreflightLossStage(opts: { export async function routeNativeLostVm(opts: { readonly home: string; readonly loss: NativeForegroundLossStage; + /** The loss stage as the runtime sees it once the VM was lost (HACK-2731). */ + readonly resolveLoss?: () => Promise; readonly signal?: AbortSignal; readonly run: () => Promise; /** Test seams: the pool record read and the classification. */ @@ -5397,6 +5435,7 @@ export async function routeNativeLostVm(opts: { home: opts.home, bootId, loss: opts.loss, + resolveLoss: opts.resolveLoss, classify: opts.classify, }); throw lost ?? error; diff --git a/src/backends/native-start-pool-watch.ts b/src/backends/native-start-pool-watch.ts index 5b17cb1ad..b64081a35 100644 --- a/src/backends/native-start-pool-watch.ts +++ b/src/backends/native-start-pool-watch.ts @@ -67,7 +67,10 @@ export type NativeStartPoolEnd = { * reported ready by the runtime and mapped. `recorded` as for `preparing`: * a resumed retained run or a restart's replacement has a run record. * - `ready`: the runtime reported the graph ready (receipt `ready-observed`) - * and the run mapping is saved. + * and the run mapping is saved. `retirable` is false when the runtime's + * selection, read once the VM was lost, shows it cannot prove the dead + * owner's relay (a run with no published port whose host relay startup had + * not settled, HACK-2731); unknown keeps the down advice. */ export type NativeForegroundLossStage = | { readonly stage: "preparing"; readonly recorded: boolean } @@ -82,7 +85,7 @@ export type NativeForegroundLossStage = */ readonly retirable?: boolean; } - | { readonly stage: "ready" }; + | { readonly stage: "ready"; readonly retirable?: boolean }; /** * What a foreground start prints when its VM is lost (HACK-2096): which VM, that @@ -110,6 +113,9 @@ export type NativeForegroundLossStage = * whose host dependency startup had not settled (#1273 review: the runtime * refuses it). The message names no command and says to keep the native home * for inspection. + * - `ready` that the runtime cannot retire (`retirable` false: no published + * port and an unsettled host relay startup, which the runtime refuses with + * `relay_owner_refused`; HACK-2731): no command either, as for `requested`. */ export function nativeForegroundPoolEndMessage( end: NativeStartPoolEnd, @@ -129,12 +135,27 @@ export function nativeForegroundPoolEndMessage( return [ lost, "This foreground start ends now with exit code 1; the run's data is kept.", - loss.stage === "requested" && !(loss.recorded && loss.retirable === true) - ? UNRECORDED_REQUESTED_ADVICE - : LOSS_ADVICE[loss.stage], + lossAdvice(loss), ].join("\n"); } +/** What to run next for a loss at `loss`, or why nothing can be run yet. */ +function lossAdvice(loss: NativeForegroundLossStage): string { + if ( + loss.stage === "requested" && + !(loss.recorded && loss.retirable === true) + ) { + return UNRECORDED_REQUESTED_ADVICE; + } + if (loss.stage === "ready" && loss.retirable === false) { + return UNPROVABLE_READY_ADVICE; + } + return LOSS_ADVICE[loss.stage]; +} + +const UNPROVABLE_READY_ADVICE = + "It was lost once it was ready, but the runtime cannot prove which relay owner it had (the run publishes no port and its host relay startup had not settled), so no hack command can retire it yet. Keep this native home unchanged for inspection; hack ps --json shows what the run left."; + const UNRECORDED_REQUESTED_ADVICE = "It was lost before its services were ready, and no hack command can retire a run lost at that point yet. Keep this native home unchanged for inspection; hack ps --json shows what the run left."; diff --git a/src/commands/project.ts b/src/commands/project.ts index 5086e6c41..29007759a 100644 --- a/src/commands/project.ts +++ b/src/commands/project.ts @@ -170,6 +170,7 @@ import { preflightNativeProjectSource } from "../backends/native-project-source- import { NativeStartupCanceledError, type NativeStartupProgress, + nativeLostStartRetirable, restartPreflightLossStage, routeNativeLostVm, startNativeProject, @@ -7598,12 +7599,24 @@ async function restartNativeImageProject({ // its intent or stops anything) gets the stage message (HACK-2096 real-VM // row 6). The old run is still the live run, so a loss is retired like a // ready one; a retry of a cleaned restart has its old run stopped; a - // prepared one has an unconfirmed stop, which no command retires yet. - preflight: async (run, { cleanedRetry, preparedRetry, signal }) => - await routeNativeLostVm({ + // prepared one has an unconfirmed stop, which no command retires yet. A + // live old run with no published port and an unsettled relay startup + // cannot be retired either, as the runtime's selection then shows + // (HACK-2731). + preflight: async (run, { cleanedRetry, preparedRetry, signal }) => { + const loss = restartPreflightLossStage({ cleanedRetry, preparedRetry }); + return await routeNativeLostVm({ home: startup.runtime.home, signal, - loss: restartPreflightLossStage({ cleanedRetry, preparedRetry }), + loss, + resolveLoss: () => + nativeLostStartRetirable({ + loss, + runtime: native, + projectRoot: startup.scope.projectRoot, + run, + invoke: invokeNativeRuntime, + }), run: async () => { await preflightNativeProjectSource({ runtime: native, @@ -7632,7 +7645,8 @@ async function restartNativeImageProject({ recoverStopped: recovery !== undefined, }); }, - }), + }); + }, down: async () => { dropEnvFingerprint(); const code = await handleDown({ diff --git a/tests/models/tla/README.md b/tests/models/tla/README.md index a9e4f7fdb..4c68c2e30 100644 --- a/tests/models/tla/README.md +++ b/tests/models/tla/README.md @@ -825,7 +825,18 @@ runtime retires (`CrossBootStart`, HACK-2714). That start's receipt (`left`) is owner died without it (killed, crashed, or taken down with the CLI); the runtime admits both, since a restore's failure path changes only that phase. Both need the dead owner's relay proved: by the run's routes, or without a published port by the relay's clean -exit (`RouteProof = "exit"`, HACK-2711). It refuses brought-back containers it +exit (`RouteProof = "exit"`, HACK-2711), which needs a settled relay startup +(`settled`, HACK-2731; a start lost before ready needs it whatever its ports). +`Unsettled` lets a relay startup be left unsettled when the VM dies after +services were requested, and `LiveRelayAdvice` makes the message once ready +check it, as `graph foreground-owner`'s `cross_boot_relay` lets the CLI do. +Out of scope: once ready, the model's receipt is always the ready one. A VM lost +during the owner's own stop (a Ctrl-C), with the receipt at `cleanup-intent` or +`stopped-data-retained`, is not modelled. The CLI withholds the command there +only for a live receipt whose relay is unprovable (`nativeLiveRelayUnprovable`); +any other phase keeps the down advice, and the unit tests cover those phases +(#1279 review). +It refuses brought-back containers it does not remove. `hack up` refuses a pending restart and an unconfirmed cleanup; `hack restart` refuses while its lock is held and a stopped run with nothing pending. @@ -836,7 +847,7 @@ nothing pending. | Control | Result | | --- | --- | -| `positive` | `NoRefusedAdvice`, `NoNeedlessWithholding`, `NoFalseLoss` and `NoMissedLoss` hold across 416 reachable states, with and without a published port, whether a lost start's owner unwound or not, whichever of the watch and the start error ends the start, whether the record still says `running` or is stuck mid-stop when the VM dies, and when an ordinary failure on a live VM ends it. A recorded run lost after its services were requested is told `hack down --recover`, then `hack up`. | +| `positive` | `NoRefusedAdvice`, `NoNeedlessWithholding`, `NoFalseLoss` and `NoMissedLoss` hold across 596 reachable states, with and without a published port, with a relay startup settled or not when the VM dies, whether a lost start's owner unwound or not, whichever of the watch and the start error ends the start, whether the record still says `running` or is stuck mid-stop when the VM dies, and when an ordinary failure on a live VM ends it. A recorded run lost after its services were requested is told `hack down --recover`, then `hack up`, when its relay startup settled; a run lost once ready is told the same unless it publishes no port and its relay startup had not settled (HACK-2731), where it is told no command. | | `negative` | PR #1253 at `cd0ebff10`: the message names `hack restart` while an intent is pending and `hack down --recover` otherwise, at every stage; the lost start leaves the restart lock held; `hack down --recover` keeps the intent and the brought-back containers; a start error keeps its own text. `NoRefusedAdvice` fails. | | `keep-intent` | Only `hack down --recover` keeps the cleaned intent: a lost restart is sent to `hack up`, which refuses the pending restart. | | `leak-lock` | Only the lock stays held after the watch's exit: `hack down --recover` cannot retire the intent under it, and `hack up` refuses. | @@ -845,6 +856,7 @@ nothing pending. | `generic-error` | PR #1253 at `a8705a39` on a real VM: the start's error wins the race with its own text. Image preparation's "retry `hack up`" is refused by a pending restart or an unconfirmed cleanup. | | `keep-leftover` | Real-VM row 8 before HACK-2719: no storage barrier, and `hack down --recover` does not remove the brought-back containers, so it cannot confirm the cleanup, and the named sequence stops there. | | `pinned-relay` | HACK-2711 (the runtime before this fix): a run with no published port proves its dead owner's relay only by a published endpoint, which the owner's unwind removed. `hack down --recover` refuses (`relay_owner_refused`) once the run was requested: `NoRefusedAdvice` fails. | +| `live-relay` | #1273's message (HACK-2731): it checks relay settlement only for a start lost before ready. A run lost once ready with no published port and an unsettled relay startup is told `hack down --recover`, which the runtime refuses (`relay_owner_refused`: its no-route proof needs a settled relay): `NoRefusedAdvice` fails. | | `no-cross-boot` | HACK-2714 (the runtime before this fix): no cross-boot retirement of a start lost before ready, so a recorded run lost at `Requested` and told down, then up, is refused (`runtime_not_running`): `NoRefusedAdvice` fails. | | `failed-only` | `01ab67fa` (review of #1273): the runtime admits only a `failed-retained` lost start. An owner that died mid-restore without its unwind leaves `restoring`, and the `hack down --recover` the message names is refused: `NoRefusedAdvice` fails. | | `withhold-requested` | PR #1253's message on the fixed runtime: a recorded run lost at `Requested` is told no command, though `hack down --recover` and `hack up` now work: `NoNeedlessWithholding` fails. | diff --git a/tests/models/tla/foreground-loss-recovery/ForegroundLossRecovery.tla b/tests/models/tla/foreground-loss-recovery/ForegroundLossRecovery.tla index a1474f0c0..e40838c06 100644 --- a/tests/models/tla/foreground-loss-recovery/ForegroundLossRecovery.tla +++ b/tests/models/tla/foreground-loss-recovery/ForegroundLossRecovery.tla @@ -27,6 +27,10 @@ \* `ports`: the project publishes a port, so its run holds bridge routes once \* ready. A run without one has no route to prove its relay owner by, only the \* relay owner's own publication, which the owner's unwind removes (HACK-2711). +\* `settled`: whether the run's relay and host dependency startup had settled +\* when the VM died (every dependency service released or completed). An owner +\* that dies with a host dependency service still `Prepared` or `Provisioned` +\* leaves it unsettled (HACK-2731), which `Unsettled` lets the model choose. \* `left`: what the dead owner of a recorded run lost at Requested left in its \* receipt: "failed" when its own unwind ran (`failed-retained`), "restoring" \* when it died without unwinding (killed, crashed, or taken down with the CLI @@ -64,6 +68,14 @@ \* RouteProof = "exit": a run with no route proves its dead owner's relay by \* the relay's clean exit (HACK-2711); "pinned": only a still-published \* relay endpoint counts, which a no-port run's unwound owner no longer has. +\* Either proof needs a settled relay startup; routes do not. +\* Unsettled: a relay startup may be left unsettled when the VM dies after +\* services were requested (HACK-2731). +\* LiveRelayAdvice: the message once ready names `hack down --recover` only +\* when the runtime can prove the dead owner's relay (`cross_boot_relay`: +\* routes, or a settled relay startup; this fix). FALSE is #1273, which +\* checked settlement only for a start lost before ready +\* (`cross_boot_start`). \* ClassifyRule = "veto": a start error counts as a lost VM from the pool \* record (a gone provider pid in any phase, or an ended boot); only a \* `running` record with a live pid vetoes a lost-provider code (this @@ -79,12 +91,13 @@ EXTENDS Naturals, Sequences CONSTANTS MessageRule, ErrorRule, ReleaseLock, RetireIntent, RepairLeftover, - ClassifyRule, StorageBarrier, CrossBootStart, RouteProof + ClassifyRule, StorageBarrier, CrossBootStart, RouteProof, Unsettled, + LiveRelayAdvice VARIABLES kind, recorded, ports, start, lostAt, endedBy, leftover, stale, - left, receipt, intent, lock, msg, todo, outcome + left, settled, receipt, intent, lock, msg, todo, outcome vars == <> + left, settled, receipt, intent, lock, msg, todo, outcome>> Commands == {"down", "up", "restart"} Stages == {"Preparing", "Requested", "GraphReady", "Serving"} @@ -99,6 +112,7 @@ TypeOK == /\ leftover \in BOOLEAN /\ stale \in BOOLEAN /\ left \in {"none", "failed", "restoring"} + /\ settled \in BOOLEAN /\ receipt \in {"none", "stopped", "unready", "ready"} /\ intent \in {"none", "cleaned"} /\ lock \in BOOLEAN @@ -117,13 +131,14 @@ Init == /\ kind = "restart" => recorded /\ ports \in BOOLEAN /\ start = "Preparing" /\ lostAt = "none" /\ endedBy = "none" - /\ leftover = FALSE /\ stale = FALSE /\ left = "none" + /\ leftover = FALSE /\ stale = FALSE /\ left = "none" /\ settled = TRUE /\ receipt = IF recorded THEN "stopped" ELSE "none" /\ intent = IF kind = "restart" THEN "cleaned" ELSE "none" /\ lock = (kind = "restart") /\ msg = "none" /\ todo = <<>> /\ outcome = "pending" -Frozen == <> \* The first service of this run is requested (`graph.onRequested`). @@ -160,6 +175,8 @@ Die == /\ stale' \in BOOLEAN /\ left' \in IF recorded /\ start = "Requested" THEN {"failed", "restoring"} ELSE {"none"} + /\ settled' \in IF Unsettled /\ start # "Preparing" + THEN BOOLEAN ELSE {TRUE} /\ UNCHANGED <> @@ -170,10 +187,17 @@ StageMessage(at) == [] at = "Requested" -> "inspect" [] OTHER -> "downUp" -\* This fix: a recorded run lost at Requested is retired like one lost once -\* ready; a fresh `up` lost there has no record for the down to find. +\* A recorded run lost at Requested is retired like one lost once ready, when +\* the runtime admits that start (`cross_boot_start`, which needs a settled +\* relay startup); a fresh `up` lost there has no record for the down to find. +\* With LiveRelayAdvice, a run lost once ready that publishes no port and whose +\* relay startup had not settled names no command (HACK-2731). RecoverMessage(at) == - IF at = "Requested" /\ recorded THEN "downUp" ELSE StageMessage(at) + CASE at = "Requested" /\ recorded -> + IF settled THEN "downUp" ELSE "inspect" + [] at \in {"GraphReady", "Serving"} /\ LiveRelayAdvice + /\ ~ports /\ ~settled -> "inspect" + [] OTHER -> StageMessage(at) Message(at) == CASE MessageRule = "recover" -> RecoverMessage(at) @@ -204,7 +228,7 @@ End(by, m, lockAfter) == /\ lock' = lockAfter /\ outcome' = IF Steps(m) = <<>> THEN "ok" ELSE "pending" /\ UNCHANGED <> + settled, receipt, intent>> \* The pool watch sees the lost VM, prints the message, runs `beforeLostExit` \* (the restart's lock release) and exits 1; nothing else of the start runs. @@ -234,8 +258,8 @@ OrdinaryFail == /\ start' = "Lost" /\ lostAt' = start /\ endedBy' = "ordinary" /\ todo' = <<>> /\ outcome' = "ok" /\ lock' = FALSE - /\ UNCHANGED <> + /\ UNCHANGED <> \* `hack down --recover` depends on where the start was lost, not on what the \* message said. Lost while preparing, the record (if any) is still the @@ -244,16 +268,19 @@ OrdinaryFail == \* with data kept: once ready and mapped always, and lost in between only a \* recorded run, with the recovery of a lost start (CrossBootStart, HACK-2714). \* Either needs the dead owner's relay proved: by the run's routes, or with no -\* published port by the relay's clean exit (RouteProof, HACK-2711). +\* published port by the relay's clean exit (RouteProof, HACK-2711), which +\* needs a settled relay startup (HACK-2731). A lost start also needs it +\* settled whatever its ports (`cross_boot_start`). \* Containers a lost VM brought back fail the confirmation unless the down \* removes them again. -RelayProved == ports \/ RouteProof = "exit" +RelayProved == ports \/ (settled /\ RouteProof = "exit") LostStartAdmitted == \/ CrossBootStart = "restoring" \/ CrossBootStart = "failed" /\ left = "failed" Retirable == CASE lostAt = "Preparing" -> TRUE - [] lostAt = "Requested" -> recorded /\ LostStartAdmitted /\ RelayProved + [] lostAt = "Requested" -> + recorded /\ LostStartAdmitted /\ settled /\ RelayProved [] OTHER -> RelayProved DownAccepts == /\ Retirable @@ -286,6 +313,7 @@ Step == THEN "none" ELSE IF c = "restart" THEN "none" ELSE intent /\ UNCHANGED <> Next == Request \/ GraphReady \/ Serve \/ Die \/ Watch \/ StartFails @@ -296,11 +324,15 @@ Spec == Init /\ [][Next]_vars NoRefusedAdvice == outcome # "refused" \* The message withholds a command only when none can work: the run was lost \* after its services were requested and before it was ready and mapped, and -\* no cross-boot recovery retires it (a fresh `up`, or the runtime before -\* HACK-2714). +\* no cross-boot recovery retires it (a fresh `up`, the runtime before +\* HACK-2714, or a start whose relay startup had not settled), or once ready +\* when the run publishes no port and its relay startup had not settled +\* (HACK-2731). NoNeedlessWithholding == msg = "inspect" => - lostAt = "Requested" /\ ~(recorded /\ CrossBootStart # "none") + \/ lostAt = "Requested" + /\ ~(recorded /\ CrossBootStart # "none" /\ settled) + \/ lostAt \in {"GraphReady", "Serving"} /\ ~ports /\ ~settled \* Reachability witness (expected to fail): a lost restart is recovered by \* following its message. NoRestartRecovery == diff --git a/tests/models/tla/foreground-loss-recovery/code-without-veto.cfg b/tests/models/tla/foreground-loss-recovery/code-without-veto.cfg index df89403b4..69376029a 100644 --- a/tests/models/tla/foreground-loss-recovery/code-without-veto.cfg +++ b/tests/models/tla/foreground-loss-recovery/code-without-veto.cfg @@ -9,5 +9,7 @@ CONSTANTS StorageBarrier = FALSE CrossBootStart = "none" RouteProof = "exit" + Unsettled = FALSE + LiveRelayAdvice = TRUE INVARIANTS TypeOK NoRefusedAdvice NoNeedlessWithholding NoFalseLoss NoMissedLoss CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/foreground-loss-recovery/failed-only.cfg b/tests/models/tla/foreground-loss-recovery/failed-only.cfg index a6407d255..62e4a2615 100644 --- a/tests/models/tla/foreground-loss-recovery/failed-only.cfg +++ b/tests/models/tla/foreground-loss-recovery/failed-only.cfg @@ -9,5 +9,7 @@ CONSTANTS StorageBarrier = TRUE CrossBootStart = "failed" RouteProof = "exit" + Unsettled = FALSE + LiveRelayAdvice = TRUE INVARIANTS TypeOK NoRefusedAdvice NoNeedlessWithholding NoFalseLoss NoMissedLoss CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/foreground-loss-recovery/generic-error.cfg b/tests/models/tla/foreground-loss-recovery/generic-error.cfg index b98321ec0..15a7f66cc 100644 --- a/tests/models/tla/foreground-loss-recovery/generic-error.cfg +++ b/tests/models/tla/foreground-loss-recovery/generic-error.cfg @@ -9,5 +9,7 @@ CONSTANTS StorageBarrier = FALSE CrossBootStart = "none" RouteProof = "exit" + Unsettled = FALSE + LiveRelayAdvice = TRUE INVARIANTS TypeOK NoRefusedAdvice NoNeedlessWithholding NoFalseLoss CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/foreground-loss-recovery/intent-message.cfg b/tests/models/tla/foreground-loss-recovery/intent-message.cfg index e4af4f5eb..1f9520245 100644 --- a/tests/models/tla/foreground-loss-recovery/intent-message.cfg +++ b/tests/models/tla/foreground-loss-recovery/intent-message.cfg @@ -9,5 +9,7 @@ CONSTANTS StorageBarrier = FALSE CrossBootStart = "none" RouteProof = "exit" + Unsettled = FALSE + LiveRelayAdvice = TRUE INVARIANTS TypeOK NoRefusedAdvice NoNeedlessWithholding NoFalseLoss NoMissedLoss CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/foreground-loss-recovery/keep-intent.cfg b/tests/models/tla/foreground-loss-recovery/keep-intent.cfg index 9ce4abbea..e10b5f44c 100644 --- a/tests/models/tla/foreground-loss-recovery/keep-intent.cfg +++ b/tests/models/tla/foreground-loss-recovery/keep-intent.cfg @@ -9,5 +9,7 @@ CONSTANTS StorageBarrier = FALSE CrossBootStart = "none" RouteProof = "exit" + Unsettled = FALSE + LiveRelayAdvice = TRUE INVARIANTS TypeOK NoRefusedAdvice NoNeedlessWithholding NoFalseLoss NoMissedLoss CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/foreground-loss-recovery/keep-leftover.cfg b/tests/models/tla/foreground-loss-recovery/keep-leftover.cfg index effafdaa4..242dd5253 100644 --- a/tests/models/tla/foreground-loss-recovery/keep-leftover.cfg +++ b/tests/models/tla/foreground-loss-recovery/keep-leftover.cfg @@ -9,5 +9,7 @@ CONSTANTS StorageBarrier = FALSE CrossBootStart = "none" RouteProof = "exit" + Unsettled = FALSE + LiveRelayAdvice = TRUE INVARIANTS TypeOK NoRefusedAdvice NoNeedlessWithholding NoFalseLoss NoMissedLoss CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/foreground-loss-recovery/leak-lock.cfg b/tests/models/tla/foreground-loss-recovery/leak-lock.cfg index d9dde05f4..12e827ad9 100644 --- a/tests/models/tla/foreground-loss-recovery/leak-lock.cfg +++ b/tests/models/tla/foreground-loss-recovery/leak-lock.cfg @@ -9,5 +9,7 @@ CONSTANTS StorageBarrier = FALSE CrossBootStart = "none" RouteProof = "exit" + Unsettled = FALSE + LiveRelayAdvice = TRUE INVARIANTS TypeOK NoRefusedAdvice NoNeedlessWithholding NoFalseLoss NoMissedLoss CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/foreground-loss-recovery/live-relay.cfg b/tests/models/tla/foreground-loss-recovery/live-relay.cfg new file mode 100644 index 000000000..ce6477cae --- /dev/null +++ b/tests/models/tla/foreground-loss-recovery/live-relay.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + MessageRule = "recover" + ErrorRule = "stage" + ReleaseLock = TRUE + RetireIntent = TRUE + RepairLeftover = TRUE + ClassifyRule = "veto" + StorageBarrier = TRUE + CrossBootStart = "restoring" + RouteProof = "exit" + Unsettled = TRUE + LiveRelayAdvice = FALSE +INVARIANTS TypeOK NoRefusedAdvice NoNeedlessWithholding NoFalseLoss NoMissedLoss +CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/foreground-loss-recovery/negative.cfg b/tests/models/tla/foreground-loss-recovery/negative.cfg index 890ea7ed2..803206fe0 100644 --- a/tests/models/tla/foreground-loss-recovery/negative.cfg +++ b/tests/models/tla/foreground-loss-recovery/negative.cfg @@ -9,5 +9,7 @@ CONSTANTS StorageBarrier = FALSE CrossBootStart = "none" RouteProof = "exit" + Unsettled = FALSE + LiveRelayAdvice = TRUE INVARIANTS TypeOK NoRefusedAdvice NoNeedlessWithholding NoFalseLoss CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/foreground-loss-recovery/no-cross-boot.cfg b/tests/models/tla/foreground-loss-recovery/no-cross-boot.cfg index dcadfc815..27563d7eb 100644 --- a/tests/models/tla/foreground-loss-recovery/no-cross-boot.cfg +++ b/tests/models/tla/foreground-loss-recovery/no-cross-boot.cfg @@ -9,5 +9,7 @@ CONSTANTS StorageBarrier = TRUE CrossBootStart = "none" RouteProof = "exit" + Unsettled = FALSE + LiveRelayAdvice = TRUE INVARIANTS TypeOK NoRefusedAdvice NoNeedlessWithholding NoFalseLoss NoMissedLoss CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/foreground-loss-recovery/pinned-relay.cfg b/tests/models/tla/foreground-loss-recovery/pinned-relay.cfg index 2bc525865..c1e3ec923 100644 --- a/tests/models/tla/foreground-loss-recovery/pinned-relay.cfg +++ b/tests/models/tla/foreground-loss-recovery/pinned-relay.cfg @@ -9,5 +9,7 @@ CONSTANTS StorageBarrier = TRUE CrossBootStart = "restoring" RouteProof = "pinned" + Unsettled = FALSE + LiveRelayAdvice = TRUE INVARIANTS TypeOK NoRefusedAdvice NoNeedlessWithholding NoFalseLoss NoMissedLoss CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/foreground-loss-recovery/positive.cfg b/tests/models/tla/foreground-loss-recovery/positive.cfg index 270e97fbd..229af526a 100644 --- a/tests/models/tla/foreground-loss-recovery/positive.cfg +++ b/tests/models/tla/foreground-loss-recovery/positive.cfg @@ -9,5 +9,7 @@ CONSTANTS StorageBarrier = TRUE CrossBootStart = "restoring" RouteProof = "exit" + Unsettled = TRUE + LiveRelayAdvice = TRUE INVARIANTS TypeOK NoRefusedAdvice NoNeedlessWithholding NoFalseLoss NoMissedLoss CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/foreground-loss-recovery/restart-recovers.cfg b/tests/models/tla/foreground-loss-recovery/restart-recovers.cfg index 41e5aafb1..18f2dc218 100644 --- a/tests/models/tla/foreground-loss-recovery/restart-recovers.cfg +++ b/tests/models/tla/foreground-loss-recovery/restart-recovers.cfg @@ -9,5 +9,7 @@ CONSTANTS StorageBarrier = TRUE CrossBootStart = "restoring" RouteProof = "exit" + Unsettled = FALSE + LiveRelayAdvice = TRUE INVARIANTS TypeOK NoRestartRecovery CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/foreground-loss-recovery/transitional-veto.cfg b/tests/models/tla/foreground-loss-recovery/transitional-veto.cfg index 3622ec845..28a51abd3 100644 --- a/tests/models/tla/foreground-loss-recovery/transitional-veto.cfg +++ b/tests/models/tla/foreground-loss-recovery/transitional-veto.cfg @@ -9,5 +9,7 @@ CONSTANTS StorageBarrier = FALSE CrossBootStart = "none" RouteProof = "exit" + Unsettled = FALSE + LiveRelayAdvice = TRUE INVARIANTS TypeOK NoRefusedAdvice NoNeedlessWithholding NoFalseLoss NoMissedLoss CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/foreground-loss-recovery/withhold-preparing.cfg b/tests/models/tla/foreground-loss-recovery/withhold-preparing.cfg index b4fc9faf6..c4e00b64d 100644 --- a/tests/models/tla/foreground-loss-recovery/withhold-preparing.cfg +++ b/tests/models/tla/foreground-loss-recovery/withhold-preparing.cfg @@ -9,5 +9,7 @@ CONSTANTS StorageBarrier = FALSE CrossBootStart = "none" RouteProof = "exit" + Unsettled = FALSE + LiveRelayAdvice = TRUE INVARIANTS TypeOK NoRefusedAdvice NoNeedlessWithholding NoFalseLoss NoMissedLoss CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/foreground-loss-recovery/withhold-requested.cfg b/tests/models/tla/foreground-loss-recovery/withhold-requested.cfg index 86af6082b..cb3759c1d 100644 --- a/tests/models/tla/foreground-loss-recovery/withhold-requested.cfg +++ b/tests/models/tla/foreground-loss-recovery/withhold-requested.cfg @@ -9,5 +9,7 @@ CONSTANTS StorageBarrier = TRUE CrossBootStart = "restoring" RouteProof = "exit" + Unsettled = FALSE + LiveRelayAdvice = TRUE INVARIANTS TypeOK NoRefusedAdvice NoNeedlessWithholding NoFalseLoss NoMissedLoss CHECK_DEADLOCK FALSE diff --git a/tests/native-project-down.test.ts b/tests/native-project-down.test.ts index 626be25df..c22e53c24 100644 --- a/tests/native-project-down.test.ts +++ b/tests/native-project-down.test.ts @@ -37,7 +37,9 @@ import { type NativeProjectRun, type NativeProjectRunScope, type NativeRestartIntent, + nativeLostRemovalRecorded, nativeRestartOperationLock, + recordNativeLostRemoval, removeNativeProjectRun, retireCleanedNativeRestart, saveNativeProjectRun, @@ -2809,6 +2811,19 @@ test.each([ phase: "ready-observed", extra: { live_owner_recovery: "a".repeat(64) }, }, + // HACK-2731: a live run with no published port and an unsettled relay + // startup, whose dead relay owner the runtime cannot prove + // (`relay_owner_refused` once the pool is started). + { + foreground: "exited", + phase: "ready-observed", + extra: { cross_boot_relay: false }, + }, + { + foreground: "exited", + phase: "started-observed", + extra: { cross_boot_relay: false }, + }, ] as { foreground: string; phase: string; @@ -3864,6 +3879,122 @@ test.each([ expect(NATIVE_LOST_REMOVAL_UNREPAIRABLE).not.toContain("run hack up"); }); +/** + * HACK-2731: `hack up` booted the pool, found containers a lost VM brought back + * and named `hack down --recover`; the pool then went idle and stopped before + * the user ran it. The down starts the pool again for the repair, from the + * retained start's marker or the runtime's marker of a repair whose storage + * barrier never confirmed. Before, it kept `runtime_not_running`, and the next + * `hack up` booted the pool and printed the same message again. + */ +async function idleLostRemovalDown(opts: { + readonly recover: boolean; + /** The retained start recorded the brought-back containers, for this run. */ + readonly marker?: NativeProjectRun; + /** The runtime's marker: an earlier repair's barrier never confirmed. */ + readonly pending?: boolean; +}) { + const fx = await fixture(); + if (opts.marker) { + await recordNativeLostRemoval({ ...fx.scope, run: opts.marker }); + } + const calls: string[] = []; + let pool = false; + let cleaned = false; + const result = await nativeProjectDown({ + ...fx, + recover: opts.recover, + notice: () => undefined, + invoke: async (request) => { + const command = request.args[1]!; + calls.push(command); + if (command === "up") { + pool = true; + return { phase: "running" }; + } + if (command === "foreground-owner") { + return { + ...ownerSelection("absent", "stopped-data-retained"), + lost_removal_pending: opts.pending === true && !cleaned, + }; + } + if (!pool) { + throw poolStoppedError(); + } + if (command === "cleanup") { + cleaned = true; + return {}; + } + if (command === "managed-hostname-authority") { + return { authority: { present: false } }; + } + expect(command).toBe("inspect"); + return { + ...lostRemovalSnapshot(cleaned || opts.pending ? "absent" : "exited"), + ...(opts.pending && !cleaned ? { lost_removal_pending: true } : {}), + }; + }, + }).then( + (value) => value, + (error: unknown) => error + ); + return { result, calls, scope: fx.scope }; +} + +test.each([ + { name: "the retained start's marker", marker: run, pending: false }, + { name: "the runtime's unconfirmed barrier", pending: true }, +] as { + name: string; + marker?: NativeProjectRun; + pending: boolean; +}[])("down --recover starts a stopped pool for an owed lost-removal repair ($name)", async ({ + marker, + pending, +}) => { + const { result, calls, scope } = await idleLostRemovalDown({ + recover: true, + marker, + pending, + }); + expect(result).toMatchObject({ + status: "stopped", + dataPreserved: true, + runtimeStarted: true, + }); + expect(calls.slice(0, 3)).toEqual(["inspect", "foreground-owner", "up"]); + expect(calls.filter((call) => call === "up")).toHaveLength(1); + expect(calls.filter((call) => call === "cleanup")).toHaveLength(1); + // The verified stop retires the marker, so a later down starts nothing. + expect(await nativeLostRemovalRecorded({ ...scope, run })).toBe(false); +}); + +test.each([ + // A plain down does not repair brought-back containers. + { name: "a plain down", recover: false, marker: run }, + // Nothing owed: no marker, or one for another run. + { name: "no marker", recover: true }, + { + name: "another run's marker", + recover: true, + marker: { ...run, run: "f".repeat(32) }, + }, +] as { + name: string; + recover: boolean; + marker?: NativeProjectRun; +}[])("a down of a stopped retained run on a stopped pool starts nothing for $name", async ({ + recover, + marker, +}) => { + const { result, calls } = await idleLostRemovalDown({ recover, marker }); + expect(result).toBeInstanceOf(NativeRuntimeRequestError); + expect((result as NativeRuntimeRequestError).nativeCode).toBe( + "runtime_not_running" + ); + expect(calls).not.toContain("up"); +}); + test("retiring a cleaned restart is a no-op without one", async () => { const fx = await fixture(); expect( diff --git a/tests/native-project-retained-startup.test.ts b/tests/native-project-retained-startup.test.ts index 4bbf924fc..7d6303c07 100644 --- a/tests/native-project-retained-startup.test.ts +++ b/tests/native-project-retained-startup.test.ts @@ -224,6 +224,62 @@ test("a resumed or running retained graph with containers a lost VM brought back ); }); +// HACK-2731: the refusal first records the lost removal, so `hack down +// --recover` starts the pool for the repair even after the pool this start +// booted went idle. Only that shape records it, and a failed record still +// refuses with the same message. +test("only the lost-removal refusal records the lost removal for hack down --recover", async () => { + const recorded: string[] = []; + const onLostRemoval = async () => { + recorded.push("lost-removal"); + }; + await expectClosedRefusal( + verifyNativeResumedRetainedGraph({ + runtime, + projectRoot: scope.projectRoot, + run, + invoke: async () => lostRemovalGraph(), + onLostRemoval, + }), + NATIVE_RETAINED_LOST_REMOVAL + ); + await expectClosedRefusal( + confirmRunningRetainedGraph({ + runtime, + projectRoot: scope.projectRoot, + run, + invoke: async () => lostRemovalGraph(), + runtimePhase: "running", + onLostRemoval, + }), + NATIVE_RETAINED_LOST_REMOVAL + ); + expect(recorded).toEqual(["lost-removal", "lost-removal"]); + await expectClosedRefusal( + verifyNativeResumedRetainedGraph({ + runtime, + projectRoot: scope.projectRoot, + run, + invoke: async () => lostRemovalGraph("9".repeat(32)), + onLostRemoval, + }), + "Native resumed retained graph differs; no graph restore was requested." + ); + expect(recorded).toHaveLength(2); + await expectClosedRefusal( + verifyNativeResumedRetainedGraph({ + runtime, + projectRoot: scope.projectRoot, + run, + invoke: async () => lostRemovalGraph(), + onLostRemoval: async () => { + throw new Error("unwritable"); + }, + }), + NATIVE_RETAINED_LOST_REMOVAL + ); +}); + test("a changed pool is retried only for a retained start, once (HACK-2732)", async () => { const changed = () => new NativeRuntimeRequestError({ diff --git a/tests/native-project-run.test.ts b/tests/native-project-run.test.ts index ece486d7e..3c5afcb10 100644 --- a/tests/native-project-run.test.ts +++ b/tests/native-project-run.test.ts @@ -13,10 +13,13 @@ import { import { tmpdir } from "node:os"; import { join } from "node:path"; import { + clearNativeLostRemoval, loadNativeProjectRun as load, + nativeLostRemovalRecorded, nativeRunEnvironmentAvailable, nativeRunEnvironmentMarkers, normalizeNativeProfiles, + recordNativeLostRemoval, removeNativeProjectRun as remove, saveNativeProjectRun as save, } from "../src/backends/native-project-run.ts"; @@ -48,6 +51,41 @@ async function fixture() { await mkdir(nativeHome); return { projectRoot, projectDir, nativeHome, branch: null }; } +// HACK-2731 (#1279 review): the lost-removal marker names exactly one run, and +// removing that run's mapping removes it, with a temporary file an interrupted +// record left beside it. Other files in the folder stay. +test("removing a run mapping removes its lost-removal marker and leftovers", async () => { + const opts = await fixture(); + await save({ ...opts, run }); + await recordNativeLostRemoval({ ...opts, run }); + expect(await nativeLostRemovalRecorded({ ...opts, run })).toBe(true); + expect( + await nativeLostRemovalRecorded({ + ...opts, + run: { ...run, run: "e".repeat(32) }, + }) + ).toBe(false); + // A later record replaces the marker rather than refusing. + await recordNativeLostRemoval({ ...opts, run }); + const root = join(opts.projectDir, ".internal", "native-runs"); + const marker = (await readdir(root)).find((name) => + name.endsWith(".lost-removal.json") + ); + expect(marker).toBeDefined(); + await writeFile(join(root, `${marker}.interrupted.tmp`), "{}", { + mode: 0o600, + }); + await writeFile(join(root, "unrelated.tmp"), "{}", { mode: 0o600 }); + await remove({ ...opts, expected: run }); + expect(await load(opts)).toBeNull(); + expect(await nativeLostRemovalRecorded({ ...opts, run })).toBe(false); + const left = await readdir(root); + expect(left.some((name) => name.startsWith(marker as string))).toBe(false); + expect(left).toContain("unrelated.tmp"); + // Clearing nothing is not an error. + await clearNativeLostRemoval(opts); +}); + test("exclusive project/branch mapping roundtrips and exact cleanup preserves other branch", async () => { const opts = await fixture(); expect(await load(opts)).toBeNull(); diff --git a/tests/native-project-start.test.ts b/tests/native-project-start.test.ts index 2dedcedf7..c8d5a601b 100644 --- a/tests/native-project-start.test.ts +++ b/tests/native-project-start.test.ts @@ -89,6 +89,8 @@ import { classifyNativeLostProvider, NATIVE_START_POOL_CHECK_MS, NATIVE_START_POOL_GRACE_MS, + type NativeForegroundLossStage, + nativeForegroundPoolEndMessage, watchNativeStartPool, } from "../src/backends/native-start-pool-watch.ts"; import type { NativeStartupLogTail } from "../src/backends/native-startup-logs.ts"; @@ -8758,6 +8760,25 @@ test("a failed exited-provider recovery says so, then keeps the original refusal ).toHaveLength(1); }); +/** The run a lost start's selection is read for, and a full reply for it. */ +const lostRun = { run: "1".repeat(32), owner: "2".repeat(32) }; +function foregroundOwnerReply( + selected: Record +): Record { + return { + version: 1, + run: lostRun.run, + owner: lostRun.owner, + receipt_sha256: "c".repeat(64), + foreground: "exited", + live_owner_recovery: null, + ...selected, + }; +} +const lostRuntime = { home: "/unused" } as Parameters< + typeof nativeLostStartRetirable +>[0]["runtime"]; + test.each([ { name: "settled", @@ -8784,6 +8805,18 @@ test.each([ retirable: true, }, { name: "ready", selected: { phase: "ready-observed" }, retirable: true }, + // HACK-2731: a live run with no published port and an unsettled relay + // startup, which the runtime refuses (`relay_owner_refused`). + { + name: "started, relay unprovable", + selected: { phase: "started-observed", cross_boot_relay: false }, + retirable: false, + }, + { + name: "started, relay provable", + selected: { phase: "started-observed", cross_boot_relay: true }, + retirable: true, + }, // A pending same-boot recovery resumes only in its own boot. { name: "same-boot recovery pending", @@ -8797,49 +8830,270 @@ test.each([ }, // An older runtime that does not report it, or a failed selection. { name: "older runtime", selected: { phase: "restoring" }, retirable: false }, - { name: "no phase", selected: {}, retirable: false }, + { name: "no phase", selected: { phase: undefined }, retirable: false }, { name: "failed selection", selected: undefined, retirable: false }, + // HACK-2731: the reply is read by the down's own parser, so a reply the down + // refuses never names it. Before, each of these was read as retirable. + { + name: "another version", + selected: { phase: "ready-observed", version: 2 }, + retirable: false, + }, + { + name: "another owner", + selected: { phase: "ready-observed", owner: "9".repeat(32) }, + retirable: false, + }, + { + name: "pending recovery not a digest", + selected: { phase: "ready-observed", live_owner_recovery: "pending" }, + retirable: false, + }, + { + name: "pending recovery not a string", + selected: { phase: "ready-observed", live_owner_recovery: 7 }, + retirable: false, + }, + { + name: "no receipt digest", + selected: { phase: "ready-observed", receipt_sha256: undefined }, + retirable: false, + }, ])("a recorded run lost before ready is retirable only as the runtime admits it ($name)", async ({ selected, retirable, }) => { - const runId = "1".repeat(32); const calls: string[][] = []; const loss = await nativeLostStartRetirable({ loss: { stage: "requested", recorded: true }, - runtime: { home: "/unused" } as Parameters< - typeof nativeLostStartRetirable - >[0]["runtime"], + runtime: lostRuntime, projectRoot: "/unused", - run: runId, + run: lostRun, invoke: (async (request: { args: readonly string[] }) => { calls.push([...request.args]); if (selected === undefined) { throw new Error("selection failed"); } - return { version: 1, run: runId, ...selected }; + return foregroundOwnerReply(selected); }) as unknown as Parameters[0]["invoke"], }); expect(loss).toEqual({ stage: "requested", recorded: true, retirable }); expect(calls).toEqual([ - ["graph", "foreground-owner", "--run-id", runId, "--json"], + ["graph", "foreground-owner", "--run-id", lostRun.run, "--json"], ]); }); -test("only a recorded requested loss asks the runtime", async () => { +test.each([ + // HACK-2731: the ready-stage advice had the same gap before #1273. + { + name: "relay unprovable", + reply: foregroundOwnerReply({ + phase: "ready-observed", + foreground: "running", + cross_boot_relay: false, + }), + expected: { stage: "ready", retirable: false }, + }, + { + name: "relay provable", + reply: foregroundOwnerReply({ + phase: "ready-observed", + foreground: "running", + cross_boot_relay: true, + }), + expected: { stage: "ready", retirable: true }, + }, + // An older runtime does not report it: retired as before. + { + name: "older runtime", + reply: foregroundOwnerReply({ + phase: "ready-observed", + foreground: "running", + }), + expected: { stage: "ready", retirable: true }, + }, + // #1279 review: a ready-stage loss whose receipt is not live (a VM lost + // during the owner's own stop) is not refused for its relay, so it keeps the + // down advice, whatever `cross_boot_relay` says. + { + name: "owner's stop, cleanup-intent with a dead-owner hint", + reply: foregroundOwnerReply({ + phase: "cleanup-intent", + cross_boot_relay: true, + dead_owner_recovery: "d".repeat(64), + }), + expected: { stage: "ready", retirable: true }, + }, + { + name: "owner's stop, cleanup-intent, relay unprovable", + reply: foregroundOwnerReply({ + phase: "cleanup-intent", + cross_boot_relay: false, + }), + expected: { stage: "ready", retirable: true }, + }, + { + name: "stopped retained", + reply: foregroundOwnerReply({ + phase: "stopped-data-retained", + foreground: "absent", + cross_boot_relay: true, + }), + expected: { stage: "ready", retirable: true }, + }, + // A pending same-boot recovery is not a relay refusal either. + { + name: "same-boot recovery pending", + reply: foregroundOwnerReply({ + phase: "ready-observed", + live_owner_recovery: "a".repeat(64), + cross_boot_relay: true, + }), + expected: { stage: "ready", retirable: true }, + }, + // A failed or foreign read keeps the down advice a ready run always had. + { + name: "failed selection", + reply: undefined, + expected: { stage: "ready" }, + }, + { + name: "foreign selection", + reply: foregroundOwnerReply({ + phase: "ready-observed", + owner: "9".repeat(32), + }), + expected: { stage: "ready" }, + }, +])("a ready run lost with its VM is retirable unless its relay owner is unprovable ($name)", async ({ + reply, + expected, +}) => { + const loss = await nativeLostStartRetirable({ + loss: { stage: "ready" }, + runtime: lostRuntime, + projectRoot: "/unused", + run: lostRun, + invoke: (async () => { + if (reply === undefined) { + throw new Error("selection failed"); + } + return reply; + }) as unknown as Parameters[0]["invoke"], + }); + expect(loss).toEqual(expected as NativeForegroundLossStage); +}); + +// A restart lost in its preflight has the ready stage (its old run is still +// the live run) and goes through the same selection (#1279 review). +test.each([ + { + name: "relay unprovable", + selected: { phase: "ready-observed", cross_boot_relay: false }, + retirable: false, + }, + { + name: "relay provable", + selected: { phase: "ready-observed", cross_boot_relay: true }, + retirable: true, + }, + { + name: "cleanup-intent", + selected: { phase: "cleanup-intent", cross_boot_relay: false }, + retirable: true, + }, + { + name: "stopped retained", + selected: { phase: "stopped-data-retained", foreground: "absent" }, + retirable: true, + }, +])("a restart lost in its preflight withholds the down only for an unprovable live relay ($name)", async ({ + selected, + retirable, +}) => { + const loss = restartPreflightLossStage({ + cleanedRetry: false, + preparedRetry: false, + }); + expect(loss).toEqual({ stage: "ready" }); + const resolved = await nativeLostStartRetirable({ + loss, + runtime: lostRuntime, + projectRoot: "/unused", + run: lostRun, + invoke: (async () => + foregroundOwnerReply(selected)) as unknown as Parameters< + typeof nativeLostStartRetirable + >[0]["invoke"], + }); + expect(resolved).toEqual({ stage: "ready", retirable }); + const message = nativeForegroundPoolEndMessage( + { bootId: "b".repeat(32) }, + resolved + ); + expect(message.includes("Run hack down --recover")).toBe(retirable); +}); + +// #1279 review (Codex P2): the start's own error (here the final inspection's +// unconfirmed cleanup) recommends `hack down --recover`. Its cause line must +// not name that command when the stage message says none can retire the run. +test.each([ + { name: "unprovable ready", loss: { stage: "ready", retirable: false } }, + { name: "provable ready", loss: { stage: "ready", retirable: true } }, + { name: "ready, not read", loss: { stage: "ready" } }, +] as { + name: string; + loss: NativeForegroundLossStage; +}[])("a lost VM's cause line names the down only where the stage message does ($name)", ({ + loss, +}) => { + const end = { bootId: "b".repeat(32), providerPid: 4242 }; + const cause = new Error( + "Native foreground exit cleanup is unconfirmed; runtime and bridge state may be retained. Run hack down --recover to resume this run's confirmed cleanup with data retained. Native exit diagnostic: process_identity_unavailable." + ); + const lost = new NativeForegroundVmLostError({ end, loss, cause }); + const withheld = loss.stage === "ready" && loss.retirable === false; + const cleanup = + "Native foreground exit cleanup is unconfirmed; runtime and bridge state may be retained."; + const diagnostic = "Native exit diagnostic: process_identity_unavailable."; + expect(lost.message).toBe( + [ + nativeForegroundPoolEndMessage(end, loss), + withheld + ? `(cause: ${cleanup} ${diagnostic})` + : `(cause: ${cleanup} Run hack down --recover to resume this run's confirmed cleanup with data retained. ${diagnostic})`, + ].join("\n") + ); + expect(lost.message.includes("hack down --recover")).toBe(!withheld); +}); + +test("a ready run whose relay owner is unprovable is told no command", () => { + const end = { bootId: "b".repeat(32) }; + const named = nativeForegroundPoolEndMessage(end, { stage: "ready" }); + expect(named).toContain("Run hack down --recover"); + expect( + nativeForegroundPoolEndMessage(end, { stage: "ready", retirable: true }) + ).toBe(named); + const withheld = nativeForegroundPoolEndMessage(end, { + stage: "ready", + retirable: false, + }); + expect(withheld).not.toContain("hack down"); + expect(withheld).not.toContain("hack up"); + expect(withheld).toContain("Keep this native home unchanged"); +}); + +test("only a recorded requested loss, or a ready one, asks the runtime", async () => { const invoke = (async () => { throw new Error("not asked"); }) as unknown as Parameters[0]["invoke"]; const base = { - runtime: { home: "/unused" } as Parameters< - typeof nativeLostStartRetirable - >[0]["runtime"], + runtime: lostRuntime, projectRoot: "/unused", - run: "1".repeat(32), + run: lostRun, invoke, }; for (const loss of [ - { stage: "ready" } as const, { stage: "preparing", recorded: true } as const, { stage: "requested", recorded: false } as const, ]) { @@ -8852,6 +9106,14 @@ test("only a recorded requested loss asks the runtime", async () => { loss: { stage: "requested", recorded: true }, }) ).toEqual({ stage: "requested", recorded: true, retirable: false }); + // A ready run whose mapping is unknown keeps its advice. + expect( + await nativeLostStartRetirable({ + ...base, + run: undefined, + loss: { stage: "ready" }, + }) + ).toEqual({ stage: "ready" }); }); test("a restart preflight's loss stage follows the restart it retries", () => {