diff --git a/docs/diagrams/graph-inventory-room.mmd b/docs/diagrams/graph-inventory-room.mmd new file mode 100644 index 000000000..32c2cc786 --- /dev/null +++ b/docs/diagrams/graph-inventory-room.mmd @@ -0,0 +1,30 @@ +--- +title: Fresh run · inventory room +--- +stateDiagram-v2 + direction TB + classDef ok stroke-width:1.6px + classDef fail stroke-width:1.6px + + [*] --> count : fresh start, lease held + state count <> + count --> admit : [fewer than 64] + count --> archive : [64, a removed run] + count --> refused : [64 keep data] + archive --> count : oldest removed archived + admit --> [*] + refused --> [*] + + note right of archive + Same proof as graph archive: + every owned resource absent, + no pending journal. + end note + note right of refused + graph_retention_budget: + remove the data of a + project you no longer use. + end note + + class admit ok + class refused fail diff --git a/docs/diagrams/graph-inventory-room.png b/docs/diagrams/graph-inventory-room.png new file mode 100644 index 000000000..20a3c736a Binary files /dev/null and b/docs/diagrams/graph-inventory-room.png differ diff --git a/docs/diagrams/graph-inventory-room.svg b/docs/diagrams/graph-inventory-room.svg new file mode 100644 index 000000000..dc295b4d9 --- /dev/null +++ b/docs/diagrams/graph-inventory-room.svg @@ -0,0 +1,66 @@ +Fresh run · inventory roomfresh start, lease held[fewer than 64][64, a removed run][64 keep data]oldest removed archivedcountadmitarchiverefusedSame proof as graph archive:every owned resource absent,no pending journal.graph_retention_budget:remove the data of aproject you no longer use. \ No newline at end of file diff --git a/docs/guides/native-candidate.md b/docs/guides/native-candidate.md index 1c98cd0cc..791e2745c 100644 --- a/docs/guides/native-candidate.md +++ b/docs/guides/native-candidate.md @@ -1795,6 +1795,18 @@ hostname change mixed with other edits refuses with `graph_hostname_change` and service name. Every refusal says to revert the edit, or to run `hack down --remove-data` and then `hack up`. `hack restart` of a stopped graph refuses and points to `hack up`. +The home's active graph inventory (`run/graphs`) holds at most 64 runs. Removed +runs used to stay in it until an explicit `graph archive`, which no `hack` command +ran, so every `down --remove-data` and every failed fresh start used a place for +good, and the 65th fresh start refused for ever (HACK-2576). Now a start (or a source +job) that needs a new run and finds the inventory full archives removed runs itself, oldest first, under the +provider lease it already holds and with the same proof `graph archive` uses (every +owned resource absent, no pending journal). Runs that keep data are never archived; +when they alone fill the inventory, `hack up` refuses with `graph_retention_budget` +and says to remove the data of a project you no longer use. The archive keeps up to +256 runs; past that the refusal is `graph_archive_budget`. A project whose removed +run was archived this way before its `hack down --remove-data` confirmed the removal +still confirms it: inspection reads a removed run from the archive. For a shared-source graph that reconciliation does not select (live source, a carried cache scope, a pending source-device rebind or initializer cache release) and that was admitted with a retained compatibility contract, ordinary diff --git a/docs/versions/v5/native/limits.md b/docs/versions/v5/native/limits.md index c0f38de4c..087c0c724 100644 --- a/docs/versions/v5/native/limits.md +++ b/docs/versions/v5/native/limits.md @@ -9,6 +9,12 @@ Projects the pool was started with can run together. If a running pool does not share a project root, `hack up` refuses the start. Stop the pool and add the root before the next boot. A pool accepts up to eight project shares. +A native home keeps up to 64 graph runs. A run whose data was removed +(`hack down --remove-data`, or a fresh start that failed) is archived on its own +when a new run needs the room. Runs that keep their data are never archived; when +64 of them fill the home, `hack up` refuses with `graph_retention_budget` until you +remove the data of a project you no longer use. + ## Native startup limits See the [native startup settings and refusal codes](https://github.com/hack-dance/hack/blob/next/docs/native/limits.md#native-startup-limits) diff --git a/packages/runtime-core/src/provider/graph/admission.rs b/packages/runtime-core/src/provider/graph/admission.rs index b596ff0ec..8de3805df 100644 --- a/packages/runtime-core/src/provider/graph/admission.rs +++ b/packages/runtime-core/src/provider/graph/admission.rs @@ -72,11 +72,14 @@ fn check_using( for config in requested.values() { budget.add(config)?; } + if except.is_none() { + super::archive::make_room(candidate, engine)?; + } let runs = storage_inventory::runs(&candidate.state_root.join("run/graphs"))?; if runs.len() == 64 && except.is_none() { return Err(error( "graph_retention_budget", - "64 graph attempts are retained; explicit archival is required.", + "64 graph attempts that keep data are retained, so no fresh run fits; remove the data of a project you no longer use (`hack down --remove-data` there) and start again.", )); } for run in runs { diff --git a/packages/runtime-core/src/provider/graph/archive.rs b/packages/runtime-core/src/provider/graph/archive.rs index 746fcb023..36f392006 100644 --- a/packages/runtime-core/src/provider/graph/archive.rs +++ b/packages/runtime-core/src/provider/graph/archive.rs @@ -111,7 +111,16 @@ fn read_confirmation( /// reserved permanently; this operation neither deletes evidence nor permits execution replay. pub fn archive(candidate: &Candidate, run: &str) -> Result { let engine = Engine::connect_cleanup(candidate)?; - let (receipt, root) = load(candidate, &engine, run)?; + archive_with(candidate, &engine, run) +} + +/// [`archive`] under a provider lease the caller already holds. +fn archive_with( + candidate: &Candidate, + engine: &Engine<'_>, + run: &str, +) -> Result { + let (receipt, root) = load(candidate, engine, run)?; initializer_cache::require_resolved(&receipt)?; if receipt.phase != "removed" || root.join("state.pending").exists() @@ -122,8 +131,8 @@ pub fn archive(candidate: &Candidate, run: &str) -> Result Result) -> Result<(), CandidateError> { + let (mut count, removed) = archivable(&candidate.state_root.join("run/graphs"))?; + let mut skipped = 0; + for run in removed { + if count < ACTIVE_LIMIT { + break; + } + match archive_with(candidate, engine, &run) { + Ok(_) => count -= 1, + // A run that fails the removal proof stays where it is; any other error + // (the archive's own bound, the engine, the guest) is reported as it is. + Err(error) if error.code == "graph_archive_refused" => skipped += 1, + Err(error) => return Err(error), + } + } + if count >= ACTIVE_LIMIT && skipped > 0 { + return Err(error( + "graph_retention_budget", + "64 graph attempts are retained and not enough of the removed ones among them could be proven removed to make room; inspect them with hack doctor --native-cleanup inspect.", + )); + } + Ok(()) +} + +/// The active inventory's size and, when it is at the bound, its removed attempts, +/// oldest receipt first. A run with a pending journal, an unreadable or foreign +/// receipt, or any phase but `removed` is never selected. +fn archivable(parent: &std::path::Path) -> Result<(usize, Vec), CandidateError> { + if !parent.exists() && !parent.is_symlink() { + return Ok((0, Vec::new())); + } + state::check_private_directory(parent)?; + // Below the bound no receipt is read. + let entries: Vec<_> = fs::read_dir(parent) + .map_err(state::io)? + .take(ACTIVE_LIMIT + 1) + .collect::>() + .map_err(state::io)?; + let count = entries.len(); + if count < ACTIVE_LIMIT { + return Ok((count, Vec::new())); + } + let mut removed = Vec::new(); + for entry in entries { + let Some(run) = entry.file_name().to_str().map(str::to_owned) else { + continue; + }; + let state = entry.path().join("state.json"); + let pending = entry.path().join("state.pending"); + if !hex(&run, 32) || pending.exists() || pending.is_symlink() { + continue; + } + let Ok(receipt) = state::read::(&state) else { + continue; + }; + if receipt.phase == "removed" && receipt.run == run { + let modified = fs::symlink_metadata(&state) + .and_then(|metadata| metadata.modified()) + .map_err(state::io)?; + removed.push((modified, run)); + } + } + removed.sort(); + Ok((count, removed.into_iter().map(|(_, run)| run).collect())) +} + pub(super) fn verify_removed(engine: &Engine<'_>, receipt: &Receipt) -> Result<(), CandidateError> { for resource in receipt.resources.values() { if resource.cache.is_some() && resource.phase == "released" { diff --git a/packages/runtime-core/src/provider/graph/archive/tests.rs b/packages/runtime-core/src/provider/graph/archive/tests.rs index ffb955e6f..7a2d7663f 100644 --- a/packages/runtime-core/src/provider/graph/archive/tests.rs +++ b/packages/runtime-core/src/provider/graph/archive/tests.rs @@ -136,3 +136,71 @@ fn archived_reconciliation_reads_committed_enrollment_without_promoting_pending( state::write(&file, &receipt).unwrap(); assert!(read_reconciliation(&fixture.0, &run, &owner).is_err()); } + +/// HACK-2576: at 64 retained attempts, only fully removed ones are selected for +/// archival, oldest first; runs that keep data, pending journals and foreign +/// entries are never selected. Below the bound nothing is. +#[test] +fn a_full_inventory_selects_only_removed_attempts_oldest_first() { + let fixture = Fixture::new(); + let parent = fixture.0.state_root.join("run/graphs"); + let write = |run: &str, phase: &str, age: u64| { + let root = parent.join(run); + state::private_directory(&parent).unwrap(); + state::private_directory(&root).unwrap(); + state::write( + &root.join("state.json"), + &json!({"version":1,"run":run,"owner":"b".repeat(32),"namespace":"c".repeat(64), + "plan_id":"d".repeat(64),"phase":phase,"readiness":{},"resources":{}}), + ) + .unwrap(); + let time = std::time::SystemTime::now() - std::time::Duration::from_secs(age); + fs::File::options() + .write(true) + .open(root.join("state.json")) + .unwrap() + .set_modified(time) + .unwrap(); + }; + for index in 0..60 { + write(&format!("{index:032x}"), "stopped-data-retained", 10); + } + write(&format!("{:032x}", 100), "removed", 300); + write(&format!("{:032x}", 101), "removed", 100); + write(&format!("{:032x}", 102), "removed", 200); + assert_eq!(archivable(&parent).unwrap(), (63, Vec::new())); + // A removed run with a pending journal is never selected. + write(&format!("{:032x}", 103), "removed", 900); + fs::write( + parent.join(format!("{:032x}", 103)).join("state.pending"), + b"{}", + ) + .unwrap(); + let (count, selected) = archivable(&parent).unwrap(); + assert_eq!(count, 64); + assert_eq!( + selected, + vec![ + format!("{:032x}", 100), + format!("{:032x}", 102), + format!("{:032x}", 101) + ] + ); +} + +/// HACK-2576 review: a removed run that a fresh start archived may still be mapped by +/// its project's CLI, which confirms the removal by inspecting it. Inspection reads +/// the active directory while it exists, else the archive; with neither it stays on +/// the active path, so the existing "not found" refusals do not change. +#[test] +fn inspection_reads_an_archived_run_only_when_it_is_no_longer_active() { + let fixture = Fixture::new(); + let run = "a".repeat(32); + let active = directory(&fixture.0, &run).unwrap(); + let archived = path(&fixture.0, &run).unwrap(); + assert_eq!(inspection_root(&fixture.0, &run).unwrap(), active); + fixture.receipt(&archived, "removed"); + assert_eq!(inspection_root(&fixture.0, &run).unwrap(), archived); + fixture.receipt(&active, "removed"); + assert_eq!(inspection_root(&fixture.0, &run).unwrap(), active); +} diff --git a/packages/runtime-core/src/provider/graph/mod.rs b/packages/runtime-core/src/provider/graph/mod.rs index 8190603f0..d99dd6bb5 100644 --- a/packages/runtime-core/src/provider/graph/mod.rs +++ b/packages/runtime-core/src/provider/graph/mod.rs @@ -1930,6 +1930,22 @@ fn observed_service_state(resource: &Resource, value: &Value) -> Result Result { + let active = directory(candidate, run)?; + if active.exists() || active.is_symlink() { + return Ok(active); + } + let archived = archive::path(candidate, run)?; + if archived.exists() || archived.is_symlink() { + return Ok(archived); + } + Ok(active) +} + /// A foreground start binds its publication before it creates the journal, so /// the journal is checked on both sides of the publication check. #[cfg(target_os = "macos")] @@ -2068,7 +2084,15 @@ fn inspect_using( engine: &impl Inspection, run: &str, ) -> Result { - let (receipt, root) = load_at(directory(candidate, run)?, run, engine.incarnation())?; + let (receipt, root) = load_at(inspection_root(candidate, run)?, run, engine.incarnation())?; + if root.starts_with(candidate.state_root.join("run/graph-archive")) + && receipt.phase != "removed" + { + return Err(error( + "graph_confirmation_location", + "An archived graph attempt is inspected only once it is removed.", + )); + } let mut observations = BTreeMap::new(); let journal_incomplete = root.join("state.pending").exists() || root.join("state.pending").is_symlink() @@ -2195,6 +2219,24 @@ pub fn cleanup( /// receipt resumes. pub fn remove_retained_data(candidate: &Candidate, run: &str) -> Result { let engine = Engine::connect_cleanup(candidate)?; + // HACK-2576: a fresh start may already have archived this removed run (see + // `archive::make_room`); removing its data again is then complete as it is. + let active = directory(candidate, run)?; + if !active.exists() && !active.is_symlink() { + let (receipt, root) = load_at( + archive::path(candidate, run)?, + run, + engine.guest().incarnation(), + )?; + if receipt.phase == "removed" + && !root.join("state.pending").exists() + && !root.join("state.pending").is_symlink() + { + archive::verify_removed(&engine, &receipt)?; + return Ok(receipt); + } + return Err(not_retained()); + } let (receipt, root) = load(candidate, &engine, run)?; if receipt.relay_startup.is_some() || !["stopped-data-retained", "cleanup-intent", "removed"].contains(&receipt.phase.as_str()) @@ -2676,6 +2718,9 @@ pub(super) fn check_reservations( engine: &Engine<'_>, except: Option<&str>, ) -> Result<(), CandidateError> { + if except.is_none() { + archive::make_room(candidate, engine)?; + } let parent = candidate.state_root.join("run/graphs"); if parent.exists() || parent.is_symlink() { state::check_private_directory(&parent)?; @@ -2687,7 +2732,7 @@ pub(super) fn check_reservations( if entries.len() > 64 || (entries.len() == 64 && except.is_none()) { return Err(error( "graph_retention_budget", - "Graph receipt retention exceeds 64 attempts; explicit archival is required.", + "64 graph attempts that keep data are retained, so no fresh run fits; remove the data of a project you no longer use (`hack down --remove-data` there) and start again.", )); } for entry in entries {