From 8757134e8fd8aa86c477439cb7d1ef4062417c7c Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:42:58 +0000 Subject: [PATCH 01/33] perf(native): overlap distinct image archive preparation --- docs/reference/timings.md | 2 + docs/reference/v5-model-coverage.md | 1 + packages/runtime-core/src/main.rs | 26 ++ .../runtime-core/src/provider/image_ensure.rs | 304 +++++++++++++++--- .../src/provider/image_tag_store.rs | 4 +- packages/runtime-core/src/timings.rs | 2 +- scripts/lib/tla-runtime-models.ts | 8 + src/backends/native-project-start.ts | 173 +++++++++- src/backends/native-runtime-client.ts | 21 +- src/lib/native-detached-up.ts | 22 +- .../models/tla/native-image-batch/COVERAGE.md | 22 ++ .../tla/native-image-batch/ImageBatch.tla | 60 ++++ .../tla/native-image-batch/image-batch.mmd | 24 ++ .../tla/native-image-batch/image-batch.svg | 66 ++++ .../tla/native-image-batch/negative.cfg | 3 + .../tla/native-image-batch/positive.cfg | 3 + tests/native-project-start.test.ts | 46 +++ 17 files changed, 712 insertions(+), 75 deletions(-) create mode 100644 tests/models/tla/native-image-batch/COVERAGE.md create mode 100644 tests/models/tla/native-image-batch/ImageBatch.tla create mode 100644 tests/models/tla/native-image-batch/image-batch.mmd create mode 100644 tests/models/tla/native-image-batch/image-batch.svg create mode 100644 tests/models/tla/native-image-batch/negative.cfg create mode 100644 tests/models/tla/native-image-batch/positive.cfg diff --git a/docs/reference/timings.md b/docs/reference/timings.md index 82026a6db..f6fce1ab1 100644 --- a/docs/reference/timings.md +++ b/docs/reference/timings.md @@ -80,6 +80,8 @@ when a completed load receipt and live readback satisfy `ensure-image`. of attempted HTTP sends in that runtime command, including registry authentication, retries and redirects. A fresh loaded selection reports zero. `image.tag.record` covers the local receipt read without network transfer. +A batch ensure also includes `attrs.image_index`, the zero-based position in +the batch request, so overlapping spans can be attributed to each image. ## Growing the vocabulary diff --git a/docs/reference/v5-model-coverage.md b/docs/reference/v5-model-coverage.md index 99a437ab2..be769c4ec 100644 --- a/docs/reference/v5-model-coverage.md +++ b/docs/reference/v5-model-coverage.md @@ -72,6 +72,7 @@ must be attached to the eventual exact integration revision. | Dependency rebind, automatic refresh, incomplete initializer, terminal reuse | dependency-rebind, dependency-auto-refresh, stopped-pool-startup, restore-history | Dependency claim/readiness, saved execution, restore history and source convergence tests | Actual installer failure, cache corruption, retained application state and resource plateau. | | Private environment allocation lifetime: staged values and private file members, crash between record and stage, retirement with the container | **Coverage gap:** no maintained model covers environment or credential delivery; file members share the existing allocation, intent record and retirement, so the state machine is unchanged | `packages/runtime-core/src/provider/environment.rs` (preparation bounds, staging layout, verification), `managed_environment.rs` (envelope v2 refusals, forwarding), `graph/launcher.rs` (read-only binds, overlap refusals) and `environment_recovery.rs` retirement tests | Live VM evidence that only the owning UID reads a member, writes fail read-only and the member is absent after cleanup; refresh or rotation of delivered files is not implemented. | | One pool, many project roots: share-set changes, boot mounts, per-project share selection, removal of a referenced share | multi-root-share | `provider::share_update` (journaled stopped-pool add/remove, record before owner), `project_share::{check_request, check_boot, validate_set}`, `OwnedGuest::project_share_for`; `share_update` and `project_share` unit tests | Real provider boot with an updated mount record, virtio-fs device limits and live multi-project graphs on a host VM. Cross-project cleanup is abstracted to one run's own resources. | +| Concurrent image acquisition and import | [native-image-batch](../../tests/models/tla/native-image-batch/COVERAGE.md) | Three workers may prepare independent archives. The importer is exclusive and a failed worker prevents graph start. | Four jobs with cancellation. Byte budgets, registry requests and real guest behavior need separate evidence. | | Cached image presence before archive reads | [native-image-presence](../../tests/models/tla/native-image-presence/COVERAGE.md) | `image_load::load_waiting` requires live exact image and platform readback for receipt reuse and verifies the archive on any upload path. Explicit archive loads retain their early hash. | One request, one archive, one lease, one boot. Expiry and registry availability may change before tag selection. Guest eviction may precede readback or create. Guest ownership, filesystem behavior, interrupted imports and performance require separate runtime evidence. | | Native image builds: unleased build versus engine stop, crash mid-build, storage recreation, foreign or forged images, reclamation versus retained graph references | native-build-retention | `provider::image_build` (shared build fence, per-key lock, incarnation/boot/engine recheck and label check at adoption, dead-attempt recording) and `image_build::reclaim` (owned labels, current receipts, retained graph state scan, engine non-force removal); `image_build` regressions | One key and namespace; a build client orphaned by a killed `hack-native` is not modeled (the client inherits the build fence and per-key lock, so both stay held until it exits: `image_build::tests::a_killed_coordinator_leaves_its_client_fenced`); real BuildKit, engine removal semantics and guest storage are host evidence. | | Runtime service per native home (HACK-2460, design): start race, crash at any step, version skew and drain, lost replies, resends on new connections, one-shot fallback, inspection of started but unfinished work | runtime-service | Process half implemented as a library; nothing starts or calls it yet. `TakeLock`, `LoseRace` and `Bind` map to `service::start` (a lock on the private `run/service/` directory, then `service.lock`, each checked against its path and held for the process's whole life, drain included; an existing socket is probed and kept if anything answers). `IdleExit`, `Retire`, `RefuseDraining` and `ExitDrained` map to `run`, `refuse_queued` and `shut_down`, with `settle` releasing ownership only after a complete drain. The tests in `packages/runtime-core/src/service/tests.rs` walk each action (concurrent starts, lock replacement while serving and while draining, stale and live sockets, idle exit with a held session, retire, connections queued at shutdown, drain timeout). `Crash` gets its real-process SIGKILL test in the next slice. Intent records, admission of mutations, skew, fallback and inspection are not implemented; each later slice adds the regression that walks its actions, behind `HACK_RUNTIME_SERVICE` (default `off`) | Implemented slice assumes the `run/service/` directory itself is not replaced (replacing `service.lock` is covered) and that the process exits after a drain that ran out of its 10 s bound; it refuses, never serves, connections queued at stop. Assumption each mutation slice must meet: its inspector distinguishes proven absence from missing evidence (for example work a provider accepted but has not yet made visible), and missing evidence yields "unknown", never "not done"; the model makes dispatched work visible at once. Liveness, several leases, cancellation of joined attempts, event cursors, dashboard authentication, the idle-exit queue race and intent-write durability are not modelled. | diff --git a/packages/runtime-core/src/main.rs b/packages/runtime-core/src/main.rs index 3129be283..984b0238c 100644 --- a/packages/runtime-core/src/main.rs +++ b/packages/runtime-core/src/main.rs @@ -1046,6 +1046,32 @@ fn run() -> Result<(), CandidateError> { Path::new(archive), )?)?; } + ["runtime", "ensure-images", "--json", flags @ ..] => { + use std::io::Read; + let mut input = Vec::new(); + std::io::stdin() + .take(65_537) + .read_to_end(&mut input) + .map_err(|_| { + CandidateError::new("invalid_arguments", "Cannot read the image batch.") + })?; + let jobs: Vec<( + String, + hack_runtime_core::provider::image_platform::PlatformPolicy, + )> = serde_json::from_slice(&input) + .map_err(|_| CandidateError::new("invalid_arguments", "Invalid image batch."))?; + if input.len() > 65_536 || jobs.len() > 64 { + return Err(CandidateError::new( + "invalid_arguments", + "Image batch exceeds its input bound.", + )); + } + print_json(&hack_runtime_core::provider::image_ensure::ensure_batch( + &discover_candidate(&requested)?, + &jobs, + &image_policy(flags)?, + ))?; + } [ "runtime", command @ ("ensure-image" | "cache-image"), diff --git a/packages/runtime-core/src/provider/image_ensure.rs b/packages/runtime-core/src/provider/image_ensure.rs index f48692ae7..96be2546d 100644 --- a/packages/runtime-core/src/provider/image_ensure.rs +++ b/packages/runtime-core/src/provider/image_ensure.rs @@ -11,15 +11,68 @@ use crate::{Candidate, CandidateError, reject_aliased_state}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::{ + collections::BTreeMap, fs, io::Read, os::unix::fs::{MetadataExt, OpenOptionsExt}, path::{Path, PathBuf}, + sync::{Arc, Condvar, Mutex, MutexGuard}, }; /// Content-addressed archives one candidate's cache may hold. const MAX_ARCHIVES: usize = 64; /// A new slot needs at least this much remaining cache budget. const MIN_SLOT: u64 = 1024 * 1024; +const IMAGE_WORKERS: usize = 3; + +#[derive(Default)] +struct CacheState { + lease: Option, + reservations: BTreeMap, +} + +#[derive(Default)] +struct ImageCache { + state: Mutex, + changed: Condvar, + importer: Mutex<()>, + pins: Mutex>>>, +} + +impl ImageCache { + fn enter(&self, root: &Path) -> Result, CandidateError> { + let mut cache = self.state.lock().unwrap(); + if cache.lease.is_none() { + let lease = state::Lock::acquire(root)?; + let staging = root.with_file_name("image-staging"); + if staging.try_exists().map_err(state::io)? { + state::check_private_directory(&staging)?; + fs::remove_dir_all(&staging).map_err(state::io)?; + } + cache.lease = Some(lease); + } + cache.lease.as_ref().unwrap().verify_path(root)?; + Ok(cache) + } +} + +struct Reservation<'a> { + cache: &'a ImageCache, + key: String, + path: PathBuf, +} + +impl Drop for Reservation<'_> { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + self.cache + .state + .lock() + .unwrap() + .reservations + .remove(&self.key); + self.cache.changed.notify_all(); + } +} fn refused(message: impl Into) -> CandidateError { CandidateError::new("image_cache", message) } @@ -251,6 +304,8 @@ pub(super) fn publish_proof( platform: PlatformPolicy, proof: ®istry_image::ManifestProof, ) -> Result<(), CandidateError> { + static PROOF_WRITER: Mutex<()> = Mutex::new(()); + let _writer = PROOF_WRITER.lock().unwrap(); let path = manifest_path(candidate, pin, platform); state::private_directory( path.parent() @@ -307,9 +362,49 @@ pub fn ensure_with( policy, platform, true, + (&ImageCache::default(), None), ) } +/// Distinct references can prepare archives together. Only the existing loader imports. +pub fn ensure_batch( + candidate: &Candidate, + jobs: &[(String, PlatformPolicy)], + policy: &ImagePolicy, +) -> Vec<(usize, Result, u64)> { + let cache = ImageCache::default(); + let queue = std::sync::atomic::AtomicUsize::new(0); + let finished = Mutex::new(Vec::with_capacity(jobs.len())); + std::thread::scope(|scope| { + for _ in 0..IMAGE_WORKERS.min(jobs.len()) { + scope.spawn(|| { + loop { + let index = queue.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let Some((reference, platform)) = jobs.get(index) else { + break; + }; + let started = std::time::Instant::now(); + let result = timed_acquire( + Step::ImageEnsure, + candidate, + reference, + policy, + *platform, + true, + (&cache, Some(index)), + ); + finished.lock().unwrap().push(( + index, + result, + started.elapsed().as_millis() as u64, + )); + } + }); + } + }); + finished.into_inner().unwrap() +} + pub use super::image_tag_store::{present as present_tags, status as tag_status}; /// Resolve and verify an archive for `hack pull` without requiring a running guest. @@ -326,6 +421,7 @@ pub fn cache( policy, platform, false, + (&ImageCache::default(), None), ) } @@ -336,12 +432,14 @@ fn timed_acquire( policy: &ImagePolicy, platform: PlatformPolicy, import: bool, + (cache, index): (&ImageCache, Option), ) -> Result { measure_attributed(step, None, |_, attrs| { let (result, count) = registry_image::count_requests(|| { - acquire_for_use(candidate, reference, policy, platform, import) + acquire_for_use(candidate, reference, policy, platform, import, cache) }); attrs.registry_requests = Some(count); + attrs.image_index = index.map(|index| index as u64); result }) } @@ -352,6 +450,7 @@ fn acquire_for_use( policy: &ImagePolicy, platform: PlatformPolicy, import: bool, + cache: &ImageCache, ) -> Result { let content_id = reference.strip_prefix("sha256:").is_some_and(hex); if content_id && !import { @@ -417,8 +516,8 @@ fn acquire_for_use( reference, policy, platform, - import, observer.as_ref(), + cache, tag, ); match (result, previous) { @@ -429,8 +528,8 @@ fn acquire_for_use( reference, policy, platform, - import, observer.as_ref(), + cache, Some(*previous), ) } @@ -443,13 +542,21 @@ fn acquire_selection( reference: &str, policy: &ImagePolicy, platform: PlatformPolicy, - import: bool, observer: Option<&engine::Observer<'_>>, + cache: &ImageCache, mut tag: Option, ) -> Result { let mut ensured = match tag.as_mut() { - Some(tag) if import => tag.confirm(|tag| { - confirm_selection(candidate, reference, policy, platform, observer, Some(tag)) + Some(tag) if observer.is_some() => tag.confirm(|tag| { + confirm_selection( + candidate, + reference, + policy, + platform, + observer, + cache, + Some(tag), + ) })?, _ => confirm_selection( candidate, @@ -457,10 +564,11 @@ fn acquire_selection( policy, platform, observer, + cache, tag.as_ref(), )?, }; - if !import { + if observer.is_none() { ensured.phase = "archive-verified"; } ensured.tag_resolution = tag.map(|tag| EnsuredTag { @@ -480,6 +588,7 @@ fn confirm_selection( policy: &ImagePolicy, platform: PlatformPolicy, observer: Option<&engine::Observer<'_>>, + cache: &ImageCache, tag: Option<&image_tag_store::TagResolution>, ) -> Result { let requested_platform = platform; @@ -561,8 +670,8 @@ fn confirm_selection( if offline && observer.is_some() { return Err(no_archive()); } - ensure_pinned_resolving( - candidate, + ensure_pinned_coordinated( + (candidate, cache), &pinned, policy, platform, @@ -634,7 +743,7 @@ fn confirm_selection( }; Ok(ensured) } -/// [`ensure_pinned_resolving`] for a cache that must never need to resolve the published +/// [`ensure_pinned_coordinated`] for a cache that must never need to resolve the published /// platform: every case it covers has its preferred entry cached, or none. #[cfg(test)] fn ensure_pinned( @@ -650,8 +759,8 @@ fn ensure_pinned( ) -> Result, load: impl FnOnce(&Candidate, &Path, &str, &str, ImagePlatform) -> Result<(), CandidateError>, ) -> Result { - ensure_pinned_resolving( - candidate, + ensure_pinned_coordinated( + (candidate, &ImageCache::default()), reference, policy, platform, @@ -671,8 +780,8 @@ fn ensure_pinned( /// Ensure one pinned reference under `platform`. `resolve` names the platform the pinned /// image itself selects under a policy; it is consulted only when the cache holds a later /// preference but not an earlier one. -fn ensure_pinned_resolving( - candidate: &Candidate, +fn ensure_pinned_coordinated( + (candidate, coordinator): (&Candidate, &ImageCache), reference: &str, policy: &ImagePolicy, platform: PlatformPolicy, @@ -687,8 +796,17 @@ fn ensure_pinned_resolving( ) -> Result { let reference = canonical(reference)?; let root = candidate.state_root.join("artifacts/images"); - let _lock = state::Lock::acquire(&root)?; - let (count, bytes) = measure(Step::ImageCacheInventory, None, |_| usage(candidate, &root))?; + let pin = coordinator + .pins + .lock() + .unwrap() + .entry(reference.clone()) + .or_default() + .clone(); + let _pin = pin.lock().unwrap(); + let mut state = coordinator.enter(&root)?; + let inventory = || measure(Step::ImageCacheInventory, None, |_| usage(candidate, &root)); + let mut occupied = inventory()?; // A cached entry is reused only for the platform the pinned image itself selects under // the policy. The first preference is published whenever its entry exists. A later // preference's entry (amd64 under `PreferNative`, perhaps left by an explicit `Amd64` @@ -719,28 +837,39 @@ fn ensure_pinned_resolving( let reused = existing.is_some(); let (dir, receipt) = if let Some((dir, entry_platform)) = existing { let receipt = inspect_entry(candidate, &dir, &reference, entry_platform)?; + drop(state); (dir, receipt) } else { - let limit = policy - .archive_limit - .min(policy.cache_limit.saturating_sub(bytes)); - if count >= MAX_ARCHIVES || limit < MIN_SLOT { - return Err(refused( - "Image cache admission requires a free slot within 64 archives and the configured cache budget; no automatic deletion.", - )); - } - // Acquire into the first candidate's slot; a different confirmed platform moves the - // complete entry to its own address below, still under the cache lock. - let first = platform.candidates()[0]; - let mut dir = root.join(entry_key(&reference, first)); - state::private_directory(&dir)?; - let acquired = match acquire(&reference, &dir.join("image.tar"), platform, limit) { - Ok(value) => value, - Err(error) => { - let _ = fs::remove_dir(&dir); - return Err(error); + let limit = loop { + let (count, bytes) = occupied; + let limit = policy + .archive_limit + .min(policy.cache_limit.saturating_sub(bytes)); + if count >= MAX_ARCHIVES || limit < MIN_SLOT { + return Err(refused( + "Image cache admission requires a free slot within 64 archives and the configured cache budget; no automatic deletion.", + )); + } + let reserved: u64 = state.reservations.values().sum(); + if count + state.reservations.len() < MAX_ARCHIVES + && policy.cache_limit.saturating_sub(bytes + reserved) >= limit + { + break limit; } + state = coordinator.changed.wait(state).unwrap(); + occupied = inventory()?; }; + let staging = root.with_file_name("image-staging").join(key(&reference)); + state::private_directory(&staging)?; + state.reservations.insert(reference.clone(), limit); + let reservation = Reservation { + cache: coordinator, + key: reference.clone(), + path: staging, + }; + drop(state); + let dir = &reservation.path; + let acquired = acquire(&reference, &dir.join("image.tar"), platform, limit)?; if !platform.candidates().contains(&acquired.platform) { return Err(refused( "Acquired image platform is outside the requested platform policy.", @@ -766,19 +895,23 @@ fn ensure_pinned_resolving( return Err(refused("New archive differs from its acquisition receipt.")); } state::write(&dir.join("receipt.json"), &receipt)?; - if acquired.platform != first { - let target = root.join(entry_key(&reference, acquired.platform)); - if target.try_exists().map_err(state::io)? { - return Err(refused( - "Conflicting image cache entry; no entry was adopted or removed.", - )); - } - fs::rename(&dir, &target).map_err(state::io)?; - dir = target; + let state = coordinator.enter(&root)?; + let target = root.join(entry_key(&reference, acquired.platform)); + if target.try_exists().map_err(state::io)? { + return Err(refused( + "Conflicting image cache entry; no entry was adopted or removed.", + )); } - (dir, receipt) + fs::rename(dir, &target).map_err(state::io)?; + fs::File::open(&root) + .and_then(|dir| dir.sync_all()) + .map_err(state::io)?; + drop(state); + drop(reservation); + (target, receipt) }; - // The loader checks the owned guest even when the acquisition receipt is reusable. + // Keep the import lease and the loader’s own live recheck unchanged. + let _import = coordinator.importer.lock().unwrap(); load(candidate, &dir.join("image.tar"), &receipt, reused)?; Ok(EnsuredImage { pinned_reference: reference, @@ -839,6 +972,75 @@ mod tests { platform: platform.candidates()[0], }) } + #[test] + fn next_cache_writer_recovers_staging_left_by_interrupt() { + let f = Fixture::new(); + let root = f.1.state_root.join("artifacts/images"); + let staged = root.with_file_name("image-staging").join(key(&pin(1))); + state::private_directory(&staged).unwrap(); + fs::write(staged.join("partial"), b"fixture").unwrap(); + let coordinator = ImageCache::default(); + let _cache = coordinator.enter(&root).unwrap(); + assert!(!staged.exists()); + assert_eq!(usage(&f.1, &root).unwrap(), (0, 0)); + } + + #[test] + fn a_failed_fetch_can_settle_while_another_verified_archive_imports() { + let f = Fixture::new(); + let cache = ImageCache::default(); + let policy = ImagePolicy::default(); + let (fetching, started) = std::sync::mpsc::channel(); + let (importing, import_started) = std::sync::mpsc::channel(); + let timeout = std::time::Duration::from_secs(5); + std::thread::scope(|scope| { + let candidate = &f.1; + let cache = &cache; + let policy = &policy; + let first = scope.spawn(move || { + ensure_pinned_coordinated( + (candidate, cache), + &pin(1), + policy, + PlatformPolicy::Native, + |_, _| panic!("no platform lookup"), + |reference, path, platform, limit| { + started.recv_timeout(timeout).unwrap(); + acquire(reference, path, platform, limit) + }, + |_, _, _, _| { + importing.send(()).unwrap(); + Ok(()) + }, + ) + }); + let second = scope.spawn(move || { + ensure_pinned_coordinated( + (candidate, cache), + &pin(2), + policy, + PlatformPolicy::Native, + |_, _| panic!("no platform lookup"), + |_, path, _, _| { + fetching.send(()).unwrap(); + import_started.recv_timeout(timeout).unwrap(); + fs::write(path, "partial").unwrap(); + Err(refused("fixture acquisition failed")) + }, + |_, _, _, _| panic!("a failed acquisition cannot import"), + ) + }); + assert!(first.join().unwrap().is_ok()); + assert_eq!( + second.join().unwrap().unwrap_err().message, + "fixture acquisition failed" + ); + }); + let root = f.1.state_root.join("artifacts"); + assert_eq!(fs::read_dir(root.join("image-staging")).unwrap().count(), 0); + assert_eq!(usage(&f.1, &root.join("images")).unwrap(), (1, 7)); + } + #[test] fn warm_pin_reuses_archive_but_always_invokes_existing_loader() { let f = Fixture::new(); @@ -1228,8 +1430,8 @@ mod tests { // natively instead of reusing the emulated entry. let resolved = Cell::new(0); let asked = Cell::new(None); - let preferred = ensure_pinned_resolving( - &f.1, + let preferred = ensure_pinned_coordinated( + (&f.1, &ImageCache::default()), &pin(1), &ImagePolicy::default(), PlatformPolicy::PreferNative, @@ -1277,8 +1479,8 @@ mod tests { |_, _, _, _, _| Ok(()), ) .unwrap(); - let reused = ensure_pinned_resolving( - &f.1, + let reused = ensure_pinned_coordinated( + (&f.1, &ImageCache::default()), &pin(2), &ImagePolicy::default(), PlatformPolicy::PreferNative, @@ -1294,8 +1496,8 @@ mod tests { assert_eq!(reused.platform, ImagePlatform::LinuxAmd64); // A failed resolution refuses before any acquisition or load. assert!( - ensure_pinned_resolving( - &f.1, + ensure_pinned_coordinated( + (&f.1, &ImageCache::default()), &pin(2), &ImagePolicy::default(), PlatformPolicy::PreferNative, diff --git a/packages/runtime-core/src/provider/image_tag_store.rs b/packages/runtime-core/src/provider/image_tag_store.rs index 0536d7a2f..faee36d0f 100644 --- a/packages/runtime-core/src/provider/image_tag_store.rs +++ b/packages/runtime-core/src/provider/image_tag_store.rs @@ -428,12 +428,12 @@ fn resolve_pending( let report_wait = std::env::var_os("HACK_INTERNAL_REPORT_IMAGE_WAIT") .is_some_and(|value| value == "1"); if report_wait { - eprintln!("hack.image-wait:begin"); + eprintln!("hack.image-wait:begin {canonical}"); } let lock = state::Lock::acquire_existing_waiting(&root, std::time::Duration::from_secs(590)); if report_wait { - eprintln!("hack.image-wait:end"); + eprintln!("hack.image-wait:end {canonical}"); } lock.map_err(|error| { if error.code == "provider_busy" { diff --git a/packages/runtime-core/src/timings.rs b/packages/runtime-core/src/timings.rs index 06375c409..51fa863e7 100644 --- a/packages/runtime-core/src/timings.rs +++ b/packages/runtime-core/src/timings.rs @@ -111,7 +111,7 @@ macro_rules! attributes { }; } attributes! { - service_index:u64, attempt:u64, registry_requests:u64, engine_requests:u64, dropped:u64, + service_index:u64, image_index:u64, attempt:u64, registry_requests:u64, engine_requests:u64, dropped:u64, services:u64, wave:u64, syncs:u64, waited_on_index:u64, generation:u64, waited_on_cap:bool, blocked:bool, service_index_stable:bool, anchor_fresh:bool, admission_reused:bool, diff --git a/scripts/lib/tla-runtime-models.ts b/scripts/lib/tla-runtime-models.ts index db5cadc83..7033febb5 100644 --- a/scripts/lib/tla-runtime-models.ts +++ b/scripts/lib/tla-runtime-models.ts @@ -3053,6 +3053,14 @@ const contracts: readonly ModelContract[] = [ }, ], }, + { + name: "native-image-batch", + module: "ImageBatch", + states: 3233, + invariant: "Safe", + action: "Import", + fields: ['phase = <<"import", "import", "queued", "queued">>'], + }, { name: "native-image-presence", module: "ImagePresence", diff --git a/src/backends/native-project-start.ts b/src/backends/native-project-start.ts index f95aa1888..69b44bd39 100644 --- a/src/backends/native-project-start.ts +++ b/src/backends/native-project-start.ts @@ -18,7 +18,7 @@ import { nativeDetachedUpShellVariables, nativeShellForwardingNotice, reportNativeImageDownloadWait, - reportNativeImageTagOffline, + reportNativeImageNotice, } from "../lib/native-detached-up.ts"; import { describeNativeProcessRefusals, @@ -812,6 +812,174 @@ async function ensureNativeProjectImage(opts: { offline: offlineTagNotice(ensured), }; } +/** Feed independent references to the runtime cache coordinator. */ +async function pinNativeImageBatch( + opts: Parameters[0] +): Promise { + const report = (line: string) => { + if (!reportNativeImageNotice(line)) { + opts.warn(line); + } + }; + const jobs = new Map< + string, + { + reference: string; + input: string; + names: string[]; + policy: NativeEmulationPolicy | undefined; + specs: Record[]; + } + >(); + for (const [name, spec] of Object.entries(opts.specs)) { + if (!nativeServiceActive(spec, opts.profiles)) { + continue; + } + if ( + typeof spec.image !== "string" || + IMAGE.test(spec.image) || + spec.build !== undefined + ) { + continue; + } + const reference = opts.canonicalImages.get(spec.image) ?? spec.image; + const policy = nativeEmulationPolicy(opts.amd64Emulation, name); + const job = jobs.get(reference); + if (job && job.policy !== policy) { + // The existing path binds both platform policies to one command pin. + return; + } + if (job) { + job.specs.push(spec); + job.names.push(name); + } else { + jobs.set(reference, { + reference, + input: spec.image, + policy, + specs: [spec], + names: [name], + }); + } + } + if (jobs.size < 2 || opts.imageTagMode) { + return; + } + const pending = [...jobs.values()]; + const failures: Error[] = []; + const confirmed = new Set(); + for (let offset = 0; offset < pending.length; offset += 3) { + const wave = pending.slice(offset, offset + 3); + const waiting = new Set(); + const reply = await opts.invoke({ + runtime: opts.runtime, + cwd: opts.projectRoot, + args: ["runtime", "ensure-images", "--json", ...nativeImagePolicyArgs()], + privateInput: new TextEncoder().encode( + JSON.stringify(wave.map((job) => [job.input, job.policy ?? "native"])) + ), + signal: opts.signal, + onImageWait: (active, reference) => { + if (!(reference && wave.some((job) => job.reference === reference))) { + return; + } + if (active) { + waiting.add(reference); + } else { + waiting.delete(reference); + } + reportNativeImageDownloadWait(waiting.values().next().value ?? null); + }, + timeoutMs: NATIVE_IMAGE_ENSURE_TIMEOUT_MS, + }); + if (!Array.isArray(reply) || reply.length !== wave.length) { + throw unconfirmed("the runtime image batch"); + } + const seen = new Set(); + for (const pair of reply) { + if ( + !(Array.isArray(pair) && Number.isInteger(pair[0])) || + seen.has(pair[0]) + ) { + throw unconfirmed("the runtime image batch"); + } + const [index, result, elapsed] = pair; + const job = wave[index]; + if ( + !( + job && + isRecord(result) && + Number.isSafeInteger(elapsed) && + elapsed >= 0 + ) + ) { + throw unconfirmed("the runtime image batch"); + } + seen.add(index); + const image = result.Ok; + if ( + !( + isRecord(image) && + typeof image.image_id === "string" && + IMAGE.test(image.image_id) && + ensuredPlatformAccepted(image.platform, job.policy) + ) + ) { + const error = isRecord(result.Err) ? result.Err : undefined; + report(`${job.reference} · image preparation failed · ${elapsed} ms`); + if ( + error?.code === "image_tag_offline_missing" || + error?.code === "image_archive_offline_missing" || + error?.code === "image_tag_download_busy" + ) { + failures.push( + await nativeImageBlocker({ + runtime: opts.runtime, + projectRoot: opts.projectRoot, + missing: job.reference, + references: pending.map((image) => image.reference), + confirmed, + downloading: error.code === "image_tag_download_busy", + reason: + typeof error.cause_code === "string" + ? error.cause_code + : undefined, + invoke: opts.invoke, + }) + ); + } else { + const reason = nativeImageRegistryReason(error?.cause_code); + const names = job.names.filter((name) => SERVICE_NAME.test(name)); + const affected = names.length + ? ` for service${names.length > 1 ? "s" : ""} ${names.join(", ")} field image` + : ""; + const detail = + error?.code === "registry_image_not_found" + ? `Native image acquisition failed${affected} (registry_image_not_found); the selected image ${job.reference} was not found.` + : `Image unavailable: ${job.reference}${reason ? ` (${reason})` : ""}`; + failures.push(new ClosedCliError(detail)); + } + continue; + } + confirmed.add(job.reference); + report(`${job.reference} · image verified in guest · ${elapsed} ms`); + const notice = offlineTagNotice(image); + if (notice && !reportNativeImageNotice(notice)) { + report(notice); + } + for (const spec of job.specs) { + spec.image = image.image_id; + } + } + } + if (failures.length === 1) { + throw failures[0]; + } + if (failures.length) { + throw new ClosedCliError(failures.map((error) => error.message).join("\n")); + } +} + /** Keep image acquisition separate from graph admission and preserve cancellation between requests. */ async function pinNativeProjectImages(opts: { readonly runtime: NativeRuntimeSelection; @@ -828,6 +996,7 @@ async function pinNativeProjectImages(opts: { readonly warn: (line: string) => void; readonly invoke: typeof invokeNativeRuntime; }): Promise { + await pinNativeImageBatch(opts); const reportedOffline = new Set(); const confirmed = new Set(); const references = [...new Set(opts.canonicalImages.values())]; @@ -926,7 +1095,7 @@ async function pinNativeProjectImages(opts: { } const noticeKey = `${reference}\n${ensured.imageId}`; if (ensured.offline && !reportedOffline.has(noticeKey)) { - if (!reportNativeImageTagOffline(ensured.offline)) { + if (!reportNativeImageNotice(ensured.offline)) { opts.warn(ensured.offline); } reportedOffline.add(noticeKey); diff --git a/src/backends/native-runtime-client.ts b/src/backends/native-runtime-client.ts index 0da7b8784..9e24ddeeb 100644 --- a/src/backends/native-runtime-client.ts +++ b/src/backends/native-runtime-client.ts @@ -778,7 +778,7 @@ export async function invokeNativeRuntime(opts: { readonly cwd: string; readonly timeoutMs?: number; readonly signal?: AbortSignal; - readonly onImageWait?: (waiting: boolean) => void; + readonly onImageWait?: (waiting: boolean, reference?: string) => void; readonly privateInput?: Uint8Array; /** Graph exec and run-service return command exit status alongside JSON. */ readonly serviceExecResponse?: boolean; @@ -1354,7 +1354,7 @@ async function readNativeFailure( signal?: AbortSignal, limit = MAX_NATIVE_FAILURE_BYTES, startupLogs = false, - onImageWait?: (waiting: boolean) => void + onImageWait?: (waiting: boolean, reference?: string) => void ): Promise { const reader = stream.getReader(); const cancel = () => { @@ -1364,7 +1364,7 @@ async function readNativeFailure( if (signal?.aborted) { cancel(); } - let waiting = false; + const waiting = new Set(); let bytes = 0; let text = ""; const decoder = new TextDecoder(); @@ -1383,13 +1383,18 @@ async function readNativeFailure( if (newline === -1) { break; } - const state = text.slice(0, newline); + const [state, reference] = text.slice(0, newline).split(" ", 2); if ( state === "hack.image-wait:begin" || state === "hack.image-wait:end" ) { - waiting = state.endsWith(":begin"); - onImageWait(waiting); + const active = state.endsWith(":begin"); + if (active) { + waiting.add(reference); + } else { + waiting.delete(reference); + } + onImageWait(active, reference); } else { break; } @@ -1408,8 +1413,8 @@ async function readNativeFailure( } catch { return; } finally { - if (waiting) { - onImageWait?.(false); + for (const reference of waiting) { + onImageWait?.(false, reference); } signal?.removeEventListener("abort", cancel); reader.releaseLock(); diff --git a/src/lib/native-detached-up.ts b/src/lib/native-detached-up.ts index cec8baa9e..bd867f575 100644 --- a/src/lib/native-detached-up.ts +++ b/src/lib/native-detached-up.ts @@ -66,7 +66,7 @@ let publishImageBlocker: | ((detail: NativeImageBlockerDetail) => Promise) | undefined; let publishImageDownloadWait: ((reference: string | null) => void) | undefined; -let publishImageTagOffline: ((notice: string) => void) | undefined; +let publishImageNotice: ((notice: string) => void) | undefined; let publishProfileNotice: ((notice: NativeProfileNotice) => void) | undefined; let publishBranchDropped: ((details: BranchDroppedSites) => void) | undefined; let publishHotReload: ((notice: NativeHotReloadNotice) => void) | undefined; @@ -585,19 +585,19 @@ export function reportNativeImageDownloadWait(reference: string | null): void { publishImageDownloadWait?.(reference); } -export function reportNativeImageTagOffline(notice: string): boolean { - if (!publishImageTagOffline) { +export function reportNativeImageNotice(notice: string): boolean { + if (!publishImageNotice) { return false; } - publishImageTagOffline(notice); + publishImageNotice(notice); return true; } -function writeImageTagOffline(value: unknown): boolean { +function writeImageNotice(value: unknown): boolean { if ( !( isRecord(value) && - value.kind === "image-tag-offline" && + value.kind === "image-notice" && typeof value.notice === "string" && value.notice.length <= 512 && [...value.notice].every((character) => { @@ -615,7 +615,7 @@ function writeImageTagOffline(value: unknown): boolean { /** Prints any validated owner notice; true when `value` was one. */ function writeOwnerNotice(value: unknown): boolean { return ( - writeImageTagOffline(value) || + writeImageNotice(value) || writeProfileNotice(value) || writeBranchDropped(value) || writeHotReload(value) @@ -728,7 +728,7 @@ export async function runNativeDetachedOwner(opts: { readonly kind: "image-download-wait"; readonly reference: string | null; } - | { readonly kind: "image-tag-offline"; readonly notice: string } + | { readonly kind: "image-notice"; readonly notice: string } | { readonly kind: "prestart-refusal"; readonly data: PrestartRefusal } | { readonly kind: "progress"; @@ -792,9 +792,9 @@ export async function runNativeDetachedOwner(opts: { void send({ kind: "image-download-wait", reference }); } }; - publishImageTagOffline = (notice) => { + publishImageNotice = (notice) => { if (!stopping) { - send({ kind: "image-tag-offline", notice }); + send({ kind: "image-notice", notice }); } }; publishProfileNotice = (notice) => { @@ -840,7 +840,7 @@ export async function runNativeDetachedOwner(opts: { publishReady = undefined; publishShellVariables = undefined; publishProfileNotice = undefined; - publishImageTagOffline = undefined; + publishImageNotice = undefined; publishImageDownloadWait = undefined; publishImageBlocker = undefined; publishBranchDropped = undefined; diff --git a/tests/models/tla/native-image-batch/COVERAGE.md b/tests/models/tla/native-image-batch/COVERAGE.md new file mode 100644 index 000000000..89db87564 --- /dev/null +++ b/tests/models/tla/native-image-batch/COVERAGE.md @@ -0,0 +1,22 @@ +# Native image batch + +[State chart](image-batch.svg) + +Four distinct image jobs share three workers, an archive coordinator and one +importer. A failed fetch or import prevents graph start. Cancel stops the +workers and preserves an in-flight import as unknown until reconciliation. +TLC explores 3,233 states. Removing importer exclusion violates Safe. + +| Model action | Runtime transition | +| --- | --- | +| Fetch | `image_ensure::ensure_batch` takes a job, and `ensure_pinned_coordinated` reserves cache capacity before acquisition. | +| Archive | The existing registry verification writes a private archive. The cache coordinator checks the receipt and publishes the complete entry under the cache lease. | +| Import / Confirm | One worker takes the importer mutex, then the existing loader checks and takes the provider lease as needed. Tag publication follows guest confirmation. | +| Fail / Start | Every completed job returns a result. The frontend refuses graph startup if any result fails. | +| Cancel | The frontend cancels its owned batch process. The next cache writer recovers owned staging under the same lease. The existing import journal fences an uncertain upload. | + +The model abstracts byte budgets, tag locking, archive layout, multiple +commands, guest observation and filesystem crashes. The Rust overlap control +forces a second fetch to start before the first can finish, then fails the +second acquisition while the first imports. It checks cache cleanup and the +first archive's receipt. diff --git a/tests/models/tla/native-image-batch/ImageBatch.tla b/tests/models/tla/native-image-batch/ImageBatch.tla new file mode 100644 index 000000000..fbc6f6d12 --- /dev/null +++ b/tests/models/tla/native-image-batch/ImageBatch.tla @@ -0,0 +1,60 @@ +-------------------------- MODULE ImageBatch -------------------------- +EXTENDS Naturals, FiniteSets +CONSTANT AllowParallelImports +Jobs == 1..4 +VARIABLES phase, verified, graph, canceled +vars == <> +Workers == {j \in Jobs : phase[j] \in {"fetch", "ready", "import"}} +Imports == {j \in Jobs : phase[j] = "import"} +Init == + /\ phase = [j \in Jobs |-> "queued"] + /\ verified = {} + /\ graph = FALSE + /\ canceled = FALSE +Fetch(j) == + /\ ~canceled /\ phase[j] = "queued" /\ Cardinality(Workers) < 3 + /\ phase' = [phase EXCEPT ![j] = "fetch"] + /\ UNCHANGED <> +Archive(j) == + /\ ~canceled /\ phase[j] = "fetch" + /\ phase' = [phase EXCEPT ![j] = "ready"] + /\ verified' = verified \cup {j} + /\ UNCHANGED <> +Fail(j) == + /\ ~canceled /\ phase[j] \in {"fetch", "import"} + /\ phase' = [phase EXCEPT ![j] = "failed"] + /\ UNCHANGED <> +Import(j) == + /\ ~canceled /\ phase[j] = "ready" + /\ Imports = {} \/ AllowParallelImports + /\ phase' = [phase EXCEPT ![j] = "import"] + /\ UNCHANGED <> +Confirm(j) == + /\ ~canceled /\ phase[j] = "import" + /\ phase' = [phase EXCEPT ![j] = "confirmed"] + /\ UNCHANGED <> +Cancel == + /\ ~graph /\ ~canceled + /\ canceled' = TRUE + /\ phase' = [j \in Jobs |-> CASE phase[j] = "import" -> "unknown" + [] phase[j] \in {"queued", "fetch", "ready"} -> "stopped" + [] OTHER -> phase[j]] + /\ UNCHANGED <> +Start == + /\ ~graph /\ ~canceled /\ \A j \in Jobs : phase[j] = "confirmed" + /\ graph' = TRUE + /\ UNCHANGED <> +Stop == + /\ canceled \/ graph \/ (Workers = {} /\ \A j \in Jobs : phase[j] # "queued") + /\ UNCHANGED vars +Next == + (\E j \in Jobs : Fetch(j) \/ Archive(j) \/ Fail(j) \/ Import(j) \/ Confirm(j)) + \/ Cancel \/ Start \/ Stop +Spec == Init /\ [][Next]_vars +Safe == + /\ Cardinality(Workers) <= 3 + /\ Cardinality(Imports) <= 1 + /\ \A j \in Jobs : phase[j] \in {"ready", "import", "confirmed", "unknown"} => j \in verified + /\ graph => (\A j \in Jobs : phase[j] = "confirmed") + /\ canceled => Workers = {} /\ ~graph +============================================================================= diff --git a/tests/models/tla/native-image-batch/image-batch.mmd b/tests/models/tla/native-image-batch/image-batch.mmd new file mode 100644 index 000000000..b297d24f5 --- /dev/null +++ b/tests/models/tla/native-image-batch/image-batch.mmd @@ -0,0 +1,24 @@ +--- +title: Bounded image preparation and import +--- +stateDiagram-v2 + direction TB + [*] --> queued + queued --> fetch: Worker available + fetch --> ready: Archive verified + fetch --> failed: Preparation failed + ready --> import: Importer available + import --> confirmed: Exact guest readback + import --> failed: Import refused + fetch --> stopped: Cancel + ready --> stopped: Cancel + import --> unknown: Cancel + confirmed --> [*] + failed --> [*] + stopped --> [*] + unknown --> [*] + class queued,ready wait + class fetch,import live + class confirmed ok + class failed,unknown fail + class stopped idle diff --git a/tests/models/tla/native-image-batch/image-batch.svg b/tests/models/tla/native-image-batch/image-batch.svg new file mode 100644 index 000000000..972921f10 --- /dev/null +++ b/tests/models/tla/native-image-batch/image-batch.svg @@ -0,0 +1,66 @@ +Bounded image preparation and importWorker availableArchive verifiedPreparation failedImporter availableExact guest readbackImport refusedCancelCancelCancelqueuedfetchreadyfailedimportconfirmedstoppedunknown \ No newline at end of file diff --git a/tests/models/tla/native-image-batch/negative.cfg b/tests/models/tla/native-image-batch/negative.cfg new file mode 100644 index 000000000..d1148216d --- /dev/null +++ b/tests/models/tla/native-image-batch/negative.cfg @@ -0,0 +1,3 @@ +SPECIFICATION Spec +CONSTANT AllowParallelImports = TRUE +INVARIANT Safe diff --git a/tests/models/tla/native-image-batch/positive.cfg b/tests/models/tla/native-image-batch/positive.cfg new file mode 100644 index 000000000..5eef0e061 --- /dev/null +++ b/tests/models/tla/native-image-batch/positive.cfg @@ -0,0 +1,3 @@ +SPECIFICATION Spec +CONSTANT AllowParallelImports = FALSE +INVARIANT Safe diff --git a/tests/native-project-start.test.ts b/tests/native-project-start.test.ts index d0fa71570..46f3a7eb7 100644 --- a/tests/native-project-start.test.ts +++ b/tests/native-project-start.test.ts @@ -142,6 +142,49 @@ async function fixture(withEnvironment = true) { }, }), invoke: async (opts) => { + if (opts.args[1] === "ensure-images") { + const jobs = JSON.parse( + new TextDecoder().decode(opts.privateInput) + ) as [string, string][]; + return await Promise.all( + jobs.map(async ([reference, policy], index) => { + try { + const args = [ + "runtime", + "ensure-image", + "--reference", + reference, + ...(policy === "native" ? [] : ["--emulation", policy]), + "--json", + ]; + return [ + index, + { + Ok: await dependencies.invoke!({ + ...opts, + args, + privateInput: undefined, + }), + }, + 1, + ]; + } catch (error) { + return [ + index, + { + Err: { + code: + error instanceof NativeRuntimeRequestError + ? error.nativeCode + : "fixture", + }, + }, + 1, + ]; + } + }) + ); + } if (opts.args[1] === "source-size") { return nativeSourceSizeReceipt(); } @@ -6545,6 +6588,9 @@ test("a missing shared tag names the requested image and every affected active s }; } if (request.args[1] === "ensure-image") { + if (request.args[3] === "another:latest") { + return { image_id: `sha256:${"f".repeat(64)}` }; + } throw new NativeRuntimeRequestError({ nativeCode: "registry_image_not_found", message: "private registry detail", From cc4d2310ea3b1c98feac7052a77edab87b6a9da8 Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:06:31 +0000 Subject: [PATCH 02/33] fix(native): budget image waits and recover only owned staging --- .../runtime-core/src/provider/image_ensure.rs | 64 +++++++++++++++++-- .../src/provider/image_tag_store.rs | 18 +++--- src/backends/native-project-start.ts | 21 +++++- src/backends/native-runtime-client.ts | 26 ++++++-- src/lib/native-detached-up.ts | 17 ++++- 5 files changed, 126 insertions(+), 20 deletions(-) diff --git a/packages/runtime-core/src/provider/image_ensure.rs b/packages/runtime-core/src/provider/image_ensure.rs index a01f646f5..54d73c69a 100644 --- a/packages/runtime-core/src/provider/image_ensure.rs +++ b/packages/runtime-core/src/provider/image_ensure.rs @@ -45,8 +45,7 @@ impl ImageCache { let lease = lifecycle::startup_lease(root, lifecycle::STARTUP_LEASE_WAIT)?; let staging = root.with_file_name("image-staging"); if staging.try_exists().map_err(state::io)? { - state::check_private_directory(&staging)?; - fs::remove_dir_all(&staging).map_err(state::io)?; + clean_staging(&staging, true)?; } cache.lease = Some(lease); } @@ -55,6 +54,42 @@ impl ImageCache { } } +fn clean_staging(path: &Path, root: bool) -> Result<(), CandidateError> { + if !path.try_exists().map_err(state::io)? { + return Ok(()); + } + state::check_private_directory(path)?; + for entry in fs::read_dir(path).map_err(state::io)? { + let entry = entry.map_err(state::io)?; + let name = entry.file_name(); + let name = name.to_string_lossy(); + let metadata = fs::symlink_metadata(entry.path()).map_err(state::io)?; + if root && hex(&name) && metadata.is_dir() && metadata.uid() == current_uid() { + clean_staging(&entry.path(), false)?; + continue; + } + let generated = matches!(&*name, "image.tar" | "receipt.json" | "receipt.pending") + || [".hack-image-", ".hack-layer-"].iter().any(|prefix| { + name.strip_prefix(prefix) + .and_then(|tail| tail.strip_suffix(".tmp")) + .and_then(|tail| tail.split_once('-')) + .is_some_and(|(pid, sequence)| { + pid.parse::().is_ok_and(|pid| pid > 0) + && !sequence.is_empty() + && sequence.bytes().all(|byte| byte.is_ascii_digit()) + }) + }); + if !root && generated && metadata.is_file() && metadata.uid() == current_uid() { + fs::remove_file(entry.path()).map_err(state::io)?; + } else { + return Err(refused(format!( + "Unexpected image staging entry {name:?} was left in place." + ))); + } + } + fs::remove_dir(path).map_err(state::io) +} + struct Reservation<'a> { cache: &'a ImageCache, key: String, @@ -63,7 +98,7 @@ struct Reservation<'a> { impl Drop for Reservation<'_> { fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); + let _ = clean_staging(&self.path, false); self.cache .state .lock() @@ -383,6 +418,11 @@ pub fn ensure_batch( let Some((reference, platform)) = jobs.get(index) else { break; }; + let report = + std::env::var("HACK_INTERNAL_REPORT_IMAGE_WAIT").as_deref() == Ok("batch"); + if report { + eprintln!("hack.image-wait:working {index}"); + } let started = std::time::Instant::now(); let result = timed_acquire( Step::ImageEnsure, @@ -393,6 +433,9 @@ pub fn ensure_batch( true, (&cache, Some(index)), ); + if report { + eprintln!("hack.image-wait:finished {index}"); + } finished.lock().unwrap().push(( index, result, @@ -972,13 +1015,26 @@ mod tests { platform: platform.candidates()[0], }) } + #[test] + fn unrelated_staging_files_are_named_and_preserved() { + let f = Fixture::new(); + let root = f.1.state_root.join("artifacts/images"); + let staged = root.with_file_name("image-staging").join(key(&pin(1))); + state::private_directory(&staged).unwrap(); + let unrelated = staged.join("unrelated"); + fs::write(&unrelated, b"fixture").unwrap(); + let error = ImageCache::default().enter(&root).err().unwrap(); + assert!(error.message.contains("unrelated")); + assert_eq!(fs::read(unrelated).unwrap(), b"fixture"); + } + #[test] fn next_cache_writer_recovers_staging_left_by_interrupt() { let f = Fixture::new(); let root = f.1.state_root.join("artifacts/images"); let staged = root.with_file_name("image-staging").join(key(&pin(1))); state::private_directory(&staged).unwrap(); - fs::write(staged.join("partial"), b"fixture").unwrap(); + fs::write(staged.join(".hack-image-1-0.tmp"), b"fixture").unwrap(); let coordinator = ImageCache::default(); let _cache = coordinator.enter(&root).unwrap(); assert!(!staged.exists()); diff --git a/packages/runtime-core/src/provider/image_tag_store.rs b/packages/runtime-core/src/provider/image_tag_store.rs index 863ea59c7..6af0a0549 100644 --- a/packages/runtime-core/src/provider/image_tag_store.rs +++ b/packages/runtime-core/src/provider/image_tag_store.rs @@ -424,15 +424,17 @@ fn resolve_pending( // resolution another process just published. let lock = match state::Lock::acquire(&root) { Err(error) if error.code == "provider_busy" => { - let report_wait = std::env::var_os("HACK_INTERNAL_REPORT_IMAGE_WAIT") - .is_some_and(|value| value == "1"); - if report_wait { - eprintln!("hack.image-wait:begin {canonical}"); + let report_wait = std::env::var("HACK_INTERNAL_REPORT_IMAGE_WAIT").unwrap_or_default(); + match report_wait.as_str() { + "batch" => eprintln!("hack.image-wait:begin {canonical}"), + "1" => eprintln!("hack.image-wait:begin"), + _ => (), } - let lock = - state::Lock::acquire_existing_waiting(&root, std::time::Duration::from_secs(590)); - if report_wait { - eprintln!("hack.image-wait:end {canonical}"); + let lock = super::lifecycle::startup_lease(&root, std::time::Duration::from_secs(590)); + match report_wait.as_str() { + "batch" => eprintln!("hack.image-wait:end {canonical}"), + "1" => eprintln!("hack.image-wait:end"), + _ => (), } lock.map_err(|error| { if error.code == "provider_busy" { diff --git a/src/backends/native-project-start.ts b/src/backends/native-project-start.ts index 6e9490858..36b2c099a 100644 --- a/src/backends/native-project-start.ts +++ b/src/backends/native-project-start.ts @@ -19,6 +19,7 @@ import { nativeShellForwardingNotice, reportNativeImageDownloadWait, reportNativeImageNotice, + reportNativeImageWork, } from "../lib/native-detached-up.ts"; import { describeNativeProcessRefusals, @@ -871,6 +872,7 @@ async function pinNativeImageBatch( for (let offset = 0; offset < pending.length; offset += 3) { const wave = pending.slice(offset, offset + 3); const waiting = new Set(); + const working = new Set(); const reply = await opts.invoke({ runtime: opts.runtime, cwd: opts.projectRoot, @@ -879,7 +881,19 @@ async function pinNativeImageBatch( JSON.stringify(wave.map((job) => [job.input, job.policy ?? "native"])) ), signal: opts.signal, - onImageWait: (active, reference) => { + onImageWait: (active, reference, work) => { + if (work) { + const image = wave[Number(reference)]?.reference; + if (image) { + if (active) { + working.add(image); + } else { + working.delete(image); + } + reportNativeImageWork([...working]); + } + return; + } if (!(reference && wave.some((job) => job.reference === reference))) { return; } @@ -890,7 +904,10 @@ async function pinNativeImageBatch( } reportNativeImageDownloadWait(waiting.values().next().value ?? null); }, - timeoutMs: NATIVE_IMAGE_ENSURE_TIMEOUT_MS, + timeoutMs: Math.min( + 3_600_000, + wave.length * NATIVE_IMAGE_ENSURE_TIMEOUT_MS + ), }); if (!Array.isArray(reply) || reply.length !== wave.length) { throw unconfirmed("the runtime image batch"); diff --git a/src/backends/native-runtime-client.ts b/src/backends/native-runtime-client.ts index 9e24ddeeb..4ce2120b0 100644 --- a/src/backends/native-runtime-client.ts +++ b/src/backends/native-runtime-client.ts @@ -778,7 +778,11 @@ export async function invokeNativeRuntime(opts: { readonly cwd: string; readonly timeoutMs?: number; readonly signal?: AbortSignal; - readonly onImageWait?: (waiting: boolean, reference?: string) => void; + readonly onImageWait?: ( + waiting: boolean, + reference?: string, + working?: boolean + ) => void; readonly privateInput?: Uint8Array; /** Graph exec and run-service return command exit status alongside JSON. */ readonly serviceExecResponse?: boolean; @@ -834,10 +838,12 @@ export async function invokeNativeRuntime(opts: { // Internal invariant: callers build these argv shapes; no user input selects them. throw new Error(REQUEST_BUDGET_REFUSAL); } + const imageBatch = + opts.args[0] === "runtime" && opts.args[1] === "ensure-images"; if ( !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || - timeoutMs > 600_000 || + timeoutMs > (imageBatch ? 3_600_000 : 600_000) || (opts.privateInput?.byteLength ?? 0) > MAX_PRIVATE_INPUT_BYTES ) { // A selected startup timeout or the managed environment size can exceed these bounds. @@ -859,7 +865,7 @@ export async function invokeNativeRuntime(opts: { Object.assign(env, nativeHotReloadEnvironment(opts.args)); Object.assign(env, nativeAdmissionReuseEnvironment(opts.args)); if (opts.onImageWait) { - env.HACK_INTERNAL_REPORT_IMAGE_WAIT = "1"; + env.HACK_INTERNAL_REPORT_IMAGE_WAIT = imageBatch ? "batch" : "1"; } const child = Bun.spawn( [ @@ -1354,7 +1360,11 @@ async function readNativeFailure( signal?: AbortSignal, limit = MAX_NATIVE_FAILURE_BYTES, startupLogs = false, - onImageWait?: (waiting: boolean, reference?: string) => void + onImageWait?: ( + waiting: boolean, + reference?: string, + working?: boolean + ) => void ): Promise { const reader = stream.getReader(); const cancel = () => { @@ -1384,6 +1394,14 @@ async function readNativeFailure( break; } const [state, reference] = text.slice(0, newline).split(" ", 2); + if ( + state === "hack.image-wait:working" || + state === "hack.image-wait:finished" + ) { + onImageWait(state === "hack.image-wait:working", reference, true); + text = text.slice(newline + 1); + continue; + } if ( state === "hack.image-wait:begin" || state === "hack.image-wait:end" diff --git a/src/lib/native-detached-up.ts b/src/lib/native-detached-up.ts index bd867f575..26816786d 100644 --- a/src/lib/native-detached-up.ts +++ b/src/lib/native-detached-up.ts @@ -85,6 +85,10 @@ let publishFailure: ((failure: StartupFailure) => Promise) | undefined; let publishProgress: | ((phase: Exclude) => void) | undefined; +let workingImages: readonly string[] = []; +export function reportNativeImageWork(images: readonly string[]): void { + workingImages = images; +} let progressHeartbeat: ReturnType | undefined; let heartbeatIntervalMs = NATIVE_DETACHED_HEARTBEAT_MS; @@ -732,6 +736,7 @@ export async function runNativeDetachedOwner(opts: { | { readonly kind: "prestart-refusal"; readonly data: PrestartRefusal } | { readonly kind: "progress"; + readonly images?: readonly string[]; readonly phase: Exclude; } ): Promise => @@ -831,12 +836,19 @@ export async function runNativeDetachedOwner(opts: { stopProgressHeartbeat(); return; } - send({ kind: "progress", phase }); + send({ + kind: "progress", + phase, + ...(phase === "images" && workingImages.length + ? { images: workingImages } + : {}), + }); }; try { return await opts.run(opts.args); } finally { stopping = true; + workingImages = []; publishReady = undefined; publishShellVariables = undefined; publishProfileNotice = undefined; @@ -942,7 +954,8 @@ function watchStartDeadline(opts: { } if ( isRecord(value) && - Object.keys(value).length === 2 && + (Object.keys(value).length === 2 || + (value.phase === "images" && Array.isArray(value.images))) && value.kind === "progress" && isNativeDetachedStartPhase(value.phase) ) { From 1992cbdd4470100d4a43f2a3252e863142086b00 Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:06:56 +0000 Subject: [PATCH 03/33] fix(native): recover interrupted manifest proof publication (HACK-2555) --- .../runtime-core/src/provider/image_ensure.rs | 81 +++++++++++++++++-- 1 file changed, 74 insertions(+), 7 deletions(-) diff --git a/packages/runtime-core/src/provider/image_ensure.rs b/packages/runtime-core/src/provider/image_ensure.rs index 54d73c69a..999f88f43 100644 --- a/packages/runtime-core/src/provider/image_ensure.rs +++ b/packages/runtime-core/src/provider/image_ensure.rs @@ -339,17 +339,30 @@ pub(super) fn publish_proof( platform: PlatformPolicy, proof: ®istry_image::ManifestProof, ) -> Result<(), CandidateError> { - static PROOF_WRITER: Mutex<()> = Mutex::new(()); - let _writer = PROOF_WRITER.lock().unwrap(); let path = manifest_path(candidate, pin, platform); - state::private_directory( - path.parent() - .ok_or_else(|| refused("Image proof parent is missing."))?, - )?; + let parent = path + .parent() + .ok_or_else(|| refused("Image proof parent is missing."))?; + let lock = lifecycle::startup_lease(parent, lifecycle::STARTUP_LEASE_WAIT)?; + let pending = path.with_extension("pending"); + match fs::symlink_metadata(&pending) { + Ok(metadata) + if metadata.is_file() + && metadata.uid() == current_uid() + && metadata.nlink() == 1 + && metadata.mode() & 0o077 == 0 => + { + lock.verify_path(parent)?; + fs::remove_file(pending).map_err(state::io)?; + } + Ok(_) => return Err(refused("Unsafe pending image proof was left in place.")), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => (), + Err(error) => return Err(state::io(error)), + } if path.try_exists().map_err(state::io)? { return Ok(()); } - state::write(&path, proof) + state::write_before_rename(&path, proof, &|| lock.verify_path(parent)) } fn check_registry_config( @@ -1015,6 +1028,60 @@ mod tests { platform: platform.candidates()[0], }) } + #[test] + #[ignore = "subprocess fixture"] + fn stopped_proof_writer() { + let file = PathBuf::from(std::env::var_os("HACK_TEST_PENDING_IMAGE_PROOF").unwrap()); + let _lock = state::Lock::acquire(file.parent().unwrap()).unwrap(); + let proof = registry_image::test_manifest_resolution().proof; + state::write_before_rename(&file, &proof, &|| { + fs::write(file.with_extension("synced"), b"ready").unwrap(); + loop { + std::thread::park(); + } + }) + .unwrap(); + } + + #[test] + fn killed_proof_writer_can_be_replaced_after_pending_sync() { + let f = Fixture::new(); + let path = manifest_path(&f.1, &pin(1), PlatformPolicy::Native); + let mut child = super::super::process::spawn_child( + std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--ignored", + "--exact", + "provider::image_ensure::tests::stopped_proof_writer", + ]) + .env("HACK_TEST_PENDING_IMAGE_PROOF", &path) + .stdout(std::process::Stdio::null()), + ) + .unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while !path.with_extension("synced").exists() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + child.kill().unwrap(); + child.wait().unwrap(); + assert!(path.with_extension("synced").exists()); + assert!(path.with_extension("pending").exists()); + assert!(!path.exists()); + publish_proof( + &f.1, + &pin(1), + PlatformPolicy::Native, + ®istry_image::test_manifest_resolution().proof, + ) + .unwrap(); + assert!( + recorded_proof(&f.1, &pin(1), PlatformPolicy::Native) + .unwrap() + .is_some() + ); + assert!(!path.with_extension("pending").exists()); + } + #[test] fn unrelated_staging_files_are_named_and_preserved() { let f = Fixture::new(); From 4b05b76736e4af8bf35e3f9e37538cdce33f770c Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:15:57 +0000 Subject: [PATCH 04/33] fix(native): admit image disk use and retain batch failures --- .../runtime-core/src/provider/image_ensure.rs | 103 +++++++++++-- .../src/provider/image_tag_store.rs | 3 +- .../src/provider/registry_image.rs | 19 +++ src/backends/native-image-policy.ts | 106 ++++++++++++++ src/backends/native-project-start.ts | 135 ++++++++---------- src/lib/native-detached-up.ts | 28 ++-- tests/fixtures/native-detached-owner.ts | 18 +++ tests/native-detached-up.test.ts | 26 ++++ tests/native-project-start.test.ts | 65 ++++++++- 9 files changed, 409 insertions(+), 94 deletions(-) diff --git a/packages/runtime-core/src/provider/image_ensure.rs b/packages/runtime-core/src/provider/image_ensure.rs index 999f88f43..4e2fda6f7 100644 --- a/packages/runtime-core/src/provider/image_ensure.rs +++ b/packages/runtime-core/src/provider/image_ensure.rs @@ -28,6 +28,7 @@ const IMAGE_WORKERS: usize = 3; struct CacheState { lease: Option, reservations: BTreeMap, + disk_reserved: u64, } #[derive(Default)] @@ -39,6 +40,30 @@ struct ImageCache { } impl ImageCache { + fn reserve_disk( + &self, + needed: u64, + available: impl Fn() -> Result, + ) -> Result, CandidateError> { + let mut cache = self.state.lock().unwrap(); + loop { + if available()?.saturating_sub(cache.disk_reserved) >= needed { + cache.disk_reserved += needed; + return Ok(DiskReservation { + cache: self, + bytes: needed, + }); + } + if cache.disk_reserved == 0 { + return Err(CandidateError::new( + "image_disk_space", + "The image archive and its temporary layer exceed available disk space.", + )); + } + cache = self.changed.wait(cache).unwrap(); + } + } + fn enter(&self, root: &Path) -> Result, CandidateError> { let mut cache = self.state.lock().unwrap(); if cache.lease.is_none() { @@ -54,6 +79,33 @@ impl ImageCache { } } +struct DiskReservation<'a> { + cache: &'a ImageCache, + bytes: u64, +} +impl Drop for DiskReservation<'_> { + fn drop(&mut self) { + self.cache.state.lock().unwrap().disk_reserved -= self.bytes; + self.cache.changed.notify_all(); + } +} + +fn disk_available(path: &Path) -> Result { + const RESERVE: u64 = 512 * 1024 * 1024; + let path = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()) + .map_err(|_| refused("Invalid image staging path."))?; + let mut stat = std::mem::MaybeUninit::::uninit(); + // SAFETY: The path is terminated and stat points to writable storage. + if unsafe { libc::statvfs(path.as_ptr(), stat.as_mut_ptr()) } != 0 { + return Err(state::io(std::io::Error::last_os_error())); + } + // SAFETY: statvfs initialized the buffer on success. + let stat = unsafe { stat.assume_init() }; + let bytes = u64::try_from((stat.f_bavail as u128) * (stat.f_frsize as u128)) + .map_err(|_| refused("Invalid image disk headroom."))?; + Ok(bytes.saturating_sub(RESERVE)) +} + fn clean_staging(path: &Path, root: bool) -> Result<(), CandidateError> { if !path.try_exists().map_err(state::io)? { return Ok(()); @@ -74,17 +126,20 @@ fn clean_staging(path: &Path, root: bool) -> Result<(), CandidateError> { .and_then(|tail| tail.strip_suffix(".tmp")) .and_then(|tail| tail.split_once('-')) .is_some_and(|(pid, sequence)| { - pid.parse::().is_ok_and(|pid| pid > 0) - && !sequence.is_empty() - && sequence.bytes().all(|byte| byte.is_ascii_digit()) + pid.parse::() + .is_ok_and(|value| value > 0 && value.to_string() == pid) + && sequence + .parse::() + .is_ok_and(|value| value.to_string() == sequence) }) }); if !root && generated && metadata.is_file() && metadata.uid() == current_uid() { fs::remove_file(entry.path()).map_err(state::io)?; } else { - return Err(refused(format!( - "Unexpected image staging entry {name:?} was left in place." - ))); + return Err(CandidateError::new( + "image_staging_entry", + format!("Unexpected image staging entry {name:?} was left in place."), + )); } } fs::remove_dir(path).map_err(state::io) @@ -741,8 +796,14 @@ fn confirm_selection( if offline { return Err(no_archive()); } - let mut acquired = - registry_image::acquire_with(reference, path, policy, limit, platform)?; + let mut acquired = registry_image::acquire_with_disk_admission( + reference, + path, + policy, + limit, + platform, + |needed| cache.reserve_disk(needed, || disk_available(path.parent().unwrap())), + )?; *acquired_proof.borrow_mut() = acquired.proof.take(); Ok(acquired) }, @@ -1028,6 +1089,32 @@ mod tests { platform: platform.candidates()[0], }) } + #[test] + fn disk_budget_waits_for_the_current_fetch_and_refuses_an_oversized_archive() { + let cache = ImageCache::default(); + let first = cache.reserve_disk(7, || Ok(10)).unwrap(); + std::thread::scope(|scope| { + let (started, waiting) = std::sync::mpsc::channel(); + let cache = &cache; + let second = scope.spawn(move || { + cache + .reserve_disk(7, || { + let _ = started.send(()); + Ok(10) + }) + .unwrap() + }); + waiting + .recv_timeout(std::time::Duration::from_secs(2)) + .unwrap(); + assert!(!second.is_finished()); + drop(first); + drop(second.join().unwrap()); + }); + let error = cache.reserve_disk(11, || Ok(10)).err().unwrap(); + assert_eq!(error.code, "image_disk_space"); + } + #[test] #[ignore = "subprocess fixture"] fn stopped_proof_writer() { diff --git a/packages/runtime-core/src/provider/image_tag_store.rs b/packages/runtime-core/src/provider/image_tag_store.rs index 6af0a0549..772c25c2a 100644 --- a/packages/runtime-core/src/provider/image_tag_store.rs +++ b/packages/runtime-core/src/provider/image_tag_store.rs @@ -430,7 +430,8 @@ fn resolve_pending( "1" => eprintln!("hack.image-wait:begin"), _ => (), } - let lock = super::lifecycle::startup_lease(&root, std::time::Duration::from_secs(590)); + let lock = + state::Lock::acquire_existing_waiting(&root, std::time::Duration::from_secs(590)); match report_wait.as_str() { "batch" => eprintln!("hack.image-wait:end {canonical}"), "1" => eprintln!("hack.image-wait:end"), diff --git a/packages/runtime-core/src/provider/registry_image.rs b/packages/runtime-core/src/provider/registry_image.rs index 75f781436..5beae4410 100644 --- a/packages/runtime-core/src/provider/registry_image.rs +++ b/packages/runtime-core/src/provider/registry_image.rs @@ -2225,6 +2225,17 @@ pub fn acquire_with( policy: &ImagePolicy, limit: u64, platform: PlatformPolicy, +) -> Result { + acquire_with_disk_admission(reference_text, output, policy, limit, platform, |_| Ok(())) +} + +pub(super) fn acquire_with_disk_admission( + reference_text: &str, + output: &Path, + policy: &ImagePolicy, + limit: u64, + platform: PlatformPolicy, + reserve: impl FnOnce(u64) -> Result, ) -> Result { let pinned = pinned(reference_text, policy)?; let limit = limit.min(policy.archive_limit); @@ -2255,6 +2266,14 @@ pub fn acquire_with( "The image exceeds the configured image budget or the remaining image cache budget.", )); } + // The current layer coexists with the growing archive until it is appended. + let largest_layer = manifest + .layers + .iter() + .map(|layer| layer.size) + .max() + .unwrap_or(0); + let _disk = reserve(planned.saturating_add(largest_layer))?; let config_name = format!("{}.json", config.digest.trim_start_matches("sha256:")); let deadline = fetch.deadline; let manifest_bytes = serde_json::to_vec( diff --git a/src/backends/native-image-policy.ts b/src/backends/native-image-policy.ts index 18bf69437..4cc1b6f18 100644 --- a/src/backends/native-image-policy.ts +++ b/src/backends/native-image-policy.ts @@ -80,6 +80,112 @@ export function nativeImageBlockerDetail( ); } +export type ImageFailure = { + reference: string; + code: string; + reason: string; + recovery: string; + services: readonly string[]; +}; + +const IMAGE_FAILURE_CODE = /^[a-z][a-z0-9_]{0,63}$/; +const IMAGE_FAILURE_TEXT = /^[ -~]{1,400}$/; +const IMAGE_FAILURE_SERVICE = /^[A-Za-z0-9_.-]{1,128}$/; + +export function imageBatchFailures(value: unknown): value is ImageFailure[] { + return ( + Array.isArray(value) && + value.length > 0 && + value.length <= 3 && + value.every( + (entry) => + entry && + typeof entry === "object" && + typeof entry.reference === "string" && + DISPLAY_REFERENCE.test(entry.reference) && + typeof entry.code === "string" && + IMAGE_FAILURE_CODE.test(entry.code) && + typeof entry.reason === "string" && + IMAGE_FAILURE_TEXT.test(entry.reason) && + typeof entry.recovery === "string" && + IMAGE_FAILURE_TEXT.test(entry.recovery) && + Array.isArray(entry.services) && + entry.services.length <= 64 && + entry.services.every( + (service: unknown) => + typeof service === "string" && IMAGE_FAILURE_SERVICE.test(service) + ) + ) + ); +} + +export class NativeImageBatchError extends HackCliError { + readonly failures: readonly ImageFailure[]; + + constructor(failures: readonly ImageFailure[]) { + super({ + code: "E_LIFECYCLE_FAILED", + detail: { images: failures }, + message: [ + "Image preparation failed.", + ...failures.map((image) => { + const services = image.services.length + ? ` for service${image.services.length > 1 ? "s" : ""} ${image.services.join(", ")} field image` + : ""; + return `- ${image.reference}${services} (${image.code}): ${image.reason}. ${image.recovery}`; + }), + ].join("\n"), + }); + this.failures = failures; + } +} + +export function batchImageFailure( + reference: string, + value: unknown, + services: readonly string[] +): ImageFailure { + const error = + value && typeof value === "object" + ? (value as Record) + : {}; + const code = + typeof error.code === "string" && IMAGE_FAILURE_CODE.test(error.code) + ? error.code + : "image_reply_invalid"; + let reason = nativeImageRegistryReason(error.cause_code); + if ( + !reason && + (error.message_fixed === true || code === "image_staging_entry") && + typeof error.message === "string" && + IMAGE_FAILURE_TEXT.test(error.message) + ) { + reason = error.message.endsWith(".") + ? error.message.slice(0, -1) + : error.message; + } + reason ??= + code === "registry_image_not_found" + ? "tag no longer exists in the registry (404)" + : code.replaceAll("_", " "); + let recovery = "Inspect hack doctor, then retry hack up."; + if (code === "image_tag_download_busy" || code === "provider_busy") { + recovery = "Run hack up again after the current image work finishes."; + } else if (code === "image_disk_space") { + recovery = "Free disk space and run hack up again."; + } else if (code.startsWith("registry_") || code.includes("offline_missing")) { + recovery = + "Run hack pull when the registry is reachable, then retry hack up."; + } + return { + reference, + code, + reason, + recovery, + services: services.filter((name) => IMAGE_FAILURE_SERVICE.test(name)), + }; +} + export class NativeImageBlocker extends ClosedCliError { readonly observation: NativeImageBlockerDetail; diff --git a/src/backends/native-project-start.ts b/src/backends/native-project-start.ts index 36b2c099a..8892a721a 100644 --- a/src/backends/native-project-start.ts +++ b/src/backends/native-project-start.ts @@ -60,7 +60,9 @@ import { } from "./native-https-owner.ts"; import { reportNativeIgnoredSettingNotices } from "./native-ignored-setting-notices.ts"; import { + batchImageFailure, NATIVE_IMAGE_ENSURE_TIMEOUT_MS, + NativeImageBatchError, nativeImagePolicyArgs, nativeImageRegistryReason, } from "./native-image-policy.ts"; @@ -867,51 +869,70 @@ async function pinNativeImageBatch( return; } const pending = [...jobs.values()]; - const failures: Error[] = []; - const confirmed = new Set(); for (let offset = 0; offset < pending.length; offset += 3) { const wave = pending.slice(offset, offset + 3); const waiting = new Set(); const working = new Set(); - const reply = await opts.invoke({ - runtime: opts.runtime, - cwd: opts.projectRoot, - args: ["runtime", "ensure-images", "--json", ...nativeImagePolicyArgs()], - privateInput: new TextEncoder().encode( - JSON.stringify(wave.map((job) => [job.input, job.policy ?? "native"])) - ), - signal: opts.signal, - onImageWait: (active, reference, work) => { - if (work) { - const image = wave[Number(reference)]?.reference; - if (image) { - if (active) { - working.add(image); - } else { - working.delete(image); + const reply = await opts + .invoke({ + runtime: opts.runtime, + cwd: opts.projectRoot, + args: [ + "runtime", + "ensure-images", + "--json", + ...nativeImagePolicyArgs(), + ], + privateInput: new TextEncoder().encode( + JSON.stringify(wave.map((job) => [job.input, job.policy ?? "native"])) + ), + signal: opts.signal, + onImageWait: (active, reference, work) => { + if (work) { + const image = wave[Number(reference)]?.reference; + if (image) { + if (active) { + working.add(image); + } else { + working.delete(image); + } + reportNativeImageWork([...working]); } - reportNativeImageWork([...working]); + return; } - return; - } - if (!(reference && wave.some((job) => job.reference === reference))) { - return; - } - if (active) { - waiting.add(reference); - } else { - waiting.delete(reference); + if (!(reference && wave.some((job) => job.reference === reference))) { + return; + } + if (active) { + waiting.add(reference); + } else { + waiting.delete(reference); + } + reportNativeImageDownloadWait(waiting.values().next().value ?? null); + }, + timeoutMs: Math.min( + 3_600_000, + wave.length * NATIVE_IMAGE_ENSURE_TIMEOUT_MS + ), + }) + .catch((error: unknown) => { + // Older bundled runtimes reject the command before doing any work. + if ( + error instanceof NativeRuntimeRequestError && + error.nativeCode === "unsupported_command" + ) { + return null; } - reportNativeImageDownloadWait(waiting.values().next().value ?? null); - }, - timeoutMs: Math.min( - 3_600_000, - wave.length * NATIVE_IMAGE_ENSURE_TIMEOUT_MS - ), - }); + throw error; + }); + if (reply === null) { + return; + } + if (!Array.isArray(reply) || reply.length !== wave.length) { throw unconfirmed("the runtime image batch"); } + const failures: ReturnType[] = []; const seen = new Set(); for (const pair of reply) { if ( @@ -942,43 +963,10 @@ async function pinNativeImageBatch( ensuredPlatformAccepted(image.platform, job.policy) ) ) { - const error = isRecord(result.Err) ? result.Err : undefined; report(`${job.reference} · image preparation failed · ${elapsed} ms`); - if ( - error?.code === "image_tag_offline_missing" || - error?.code === "image_archive_offline_missing" || - error?.code === "image_tag_download_busy" - ) { - failures.push( - await nativeImageBlocker({ - runtime: opts.runtime, - projectRoot: opts.projectRoot, - missing: job.reference, - references: pending.map((image) => image.reference), - confirmed, - downloading: error.code === "image_tag_download_busy", - reason: - typeof error.cause_code === "string" - ? error.cause_code - : undefined, - invoke: opts.invoke, - }) - ); - } else { - const reason = nativeImageRegistryReason(error?.cause_code); - const names = job.names.filter((name) => SERVICE_NAME.test(name)); - const affected = names.length - ? ` for service${names.length > 1 ? "s" : ""} ${names.join(", ")} field image` - : ""; - const detail = - error?.code === "registry_image_not_found" - ? `Native image acquisition failed${affected} (registry_image_not_found); the selected image ${job.reference} was not found.` - : `Image unavailable: ${job.reference}${reason ? ` (${reason})` : ""}`; - failures.push(new ClosedCliError(detail)); - } + failures.push(batchImageFailure(job.reference, result.Err, job.names)); continue; } - confirmed.add(job.reference); report(`${job.reference} · image verified in guest · ${elapsed} ms`); const notice = offlineTagNotice(image); if (notice && !reportNativeImageNotice(notice)) { @@ -988,12 +976,9 @@ async function pinNativeImageBatch( spec.image = image.image_id; } } - } - if (failures.length === 1) { - throw failures[0]; - } - if (failures.length) { - throw new ClosedCliError(failures.map((error) => error.message).join("\n")); + if (failures.length) { + throw new NativeImageBatchError(failures); + } } } diff --git a/src/lib/native-detached-up.ts b/src/lib/native-detached-up.ts index 26816786d..712c659f9 100644 --- a/src/lib/native-detached-up.ts +++ b/src/lib/native-detached-up.ts @@ -6,6 +6,9 @@ import { renderNativeHotReloadNotice, } from "../backends/native-hot-reload-notice.ts"; import { + type ImageFailure, + imageBatchFailures, + NativeImageBatchError, NativeImageBlocker, type NativeImageBlockerDetail, nativeImageBlockerDetail, @@ -63,7 +66,9 @@ type Ready = { }; let publishReady: ((ready: Ready) => void) | undefined; let publishImageBlocker: - | ((detail: NativeImageBlockerDetail) => Promise) + | (( + detail: NativeImageBlockerDetail | readonly ImageFailure[] + ) => Promise) | undefined; let publishImageDownloadWait: ((reference: string | null) => void) | undefined; let publishImageNotice: ((notice: string) => void) | undefined; @@ -355,6 +360,10 @@ export async function nativeDetachedUpFailure(error: unknown): Promise { if (!publishFailure) { return; } + if (error instanceof NativeImageBatchError) { + await publishImageBlocker?.(error.failures); + return; + } if (error instanceof NativeImageBlocker) { await publishImageBlocker?.(error.observation); return; @@ -726,7 +735,7 @@ export async function runNativeDetachedOwner(opts: { } | { readonly kind: "image-blocker"; - readonly detail: NativeImageBlockerDetail; + readonly detail: NativeImageBlockerDetail | readonly ImageFailure[]; } | { readonly kind: "image-download-wait"; @@ -1106,13 +1115,14 @@ export async function startNativeDetachedUp(opts: { if (failed) { return; } - const imageBlocked = - !ready && - isRecord(value) && - value.kind === "image-blocker" && - nativeImageBlockerDetail(value.detail) - ? new NativeImageBlocker(value.detail) - : undefined; + let imageBlocked: NativeImageBatchError | NativeImageBlocker | undefined; + if (!ready && isRecord(value) && value.kind === "image-blocker") { + if (imageBatchFailures(value.detail)) { + imageBlocked = new NativeImageBatchError(value.detail); + } else if (nativeImageBlockerDetail(value.detail)) { + imageBlocked = new NativeImageBlocker(value.detail); + } + } const refused = ready ? undefined : (imageBlocked ?? startupRefusal(value)); if (refused) { failed = true; diff --git a/tests/fixtures/native-detached-owner.ts b/tests/fixtures/native-detached-owner.ts index 0e6a11f85..bb3d37425 100644 --- a/tests/fixtures/native-detached-owner.ts +++ b/tests/fixtures/native-detached-owner.ts @@ -2,6 +2,10 @@ import { ChildProcess, spawn } from "node:child_process"; import { existsSync } from "node:fs"; import { rename, writeFile } from "node:fs/promises"; import { join } from "node:path"; +import { + batchImageFailure, + NativeImageBatchError, +} from "../../src/backends/native-image-policy.ts"; import { NativeRuntimeRequestError, retainNativeRuntimeFailure, @@ -415,6 +419,7 @@ if (role === "channel-holder") { "immediate-failure", "exit-first-failure", "failed-services", + "image-batch-errors", "prestart-refusal", "prestart-after-runtime", "prestart-plain-error", @@ -548,6 +553,19 @@ if (role === "channel-holder") { } return 1; } + if (mode === "image-batch-errors") { + await nativeDetachedUpFailure( + new NativeImageBatchError([ + batchImageFailure("fixture/image:a", { code: "provider_busy" }, [ + "web", + ]), + batchImageFailure("fixture/image:b", { code: "image_disk_space" }, [ + "db", + ]), + ]) + ); + return 1; + } if (mode === "failed-services") { // A service's process exited during startup: only its name may cross // IPC. Unsafe names and anything resembling output are dropped. diff --git a/tests/native-detached-up.test.ts b/tests/native-detached-up.test.ts index 0daacf196..036e3da2c 100644 --- a/tests/native-detached-up.test.ts +++ b/tests/native-detached-up.test.ts @@ -646,6 +646,32 @@ test("HACK-2339: a failed hook's lines reach only a terminal stderr; otherwise o ]); }, 60_000); +test("detached JSON retains every image refusal and recovery action", async () => { + const result = await prestartRun("image-batch-errors"); + expect(result.code).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ + ok: false, + error: { + code: "E_LIFECYCLE_FAILED", + detail: { + images: [ + { + reference: "fixture/image:a", + code: "provider_busy", + recovery: + "Run hack up again after the current image work finishes.", + }, + { + reference: "fixture/image:b", + code: "image_disk_space", + recovery: "Free disk space and run hack up again.", + }, + ], + }, + }, + }); +}, 30_000); + test("HACK-2351: image work longer than the budget, with heartbeats, still completes", async () => { const started = performance.now(); const result = await prestartRun("slow-images"); diff --git a/tests/native-project-start.test.ts b/tests/native-project-start.test.ts index 73cec7aa1..8b434f0e9 100644 --- a/tests/native-project-start.test.ts +++ b/tests/native-project-start.test.ts @@ -5177,7 +5177,7 @@ test("startup admits each reference once and reuses validated pins for shared se if (request.args[1] === "ensure-image") { order.push(`ensure ${request.args[3]}`); // Acquisition plus import gets the runtime's whole bounded request budget. - expect(request.timeoutMs).toBe(NATIVE_IMAGE_ENSURE_TIMEOUT_MS); + expect(request.timeoutMs).toBe(2 * NATIVE_IMAGE_ENSURE_TIMEOUT_MS); expect(request.args.slice(0, 5)).toEqual([ "runtime", "ensure-image", @@ -5201,6 +5201,69 @@ test("startup admits each reference once and reuses validated pins for shared se expect(events.indexOf("before")).toBeLessThan(events.indexOf("runtime up")); }); +test("one image batch uses the combined deadline and stops before the next wave", async () => { + const { opts } = await fixture(false); + withImages(opts, { web: "a:1", worker: "b:1", cache: "c:1", db: "d:1" }); + const original = opts.dependencies.invoke!; + let waves = 0; + opts.dependencies.invoke = async (request) => { + if (request.args[1] !== "ensure-images") { + return await original(request); + } + waves += 1; + expect(request.timeoutMs).toBe(1_800_000); + return [ + [0, { Err: { code: "provider_busy" } }, 1], + [1, { Err: { code: "image_disk_space" } }, 2], + [2, { Ok: { image_id: `sha256:${"c".repeat(64)}` } }, 3], + ]; + }; + const error = await startNativeProject(opts).catch( + (failure: unknown) => failure + ); + expect(waves).toBe(1); + expect(error).toMatchObject({ + code: "E_LIFECYCLE_FAILED", + detail: { + images: [ + { + reference: "a:1", + code: "provider_busy", + recovery: "Run hack up again after the current image work finishes.", + }, + { + reference: "b:1", + code: "image_disk_space", + recovery: "Free disk space and run hack up again.", + }, + ], + }, + }); +}); + +test("an older runtime falls back to ordinary image selection", async () => { + const { opts } = await fixture(false); + withImages(opts, { web: "alpine:1", worker: "redis:1" }); + const original = opts.dependencies.invoke!; + const calls: string[] = []; + opts.dependencies.invoke = async (request) => { + if (request.args[1] === "ensure-images") { + calls.push("batch"); + throw new NativeRuntimeRequestError({ + nativeCode: "unsupported_command", + message: "Older runtime", + }); + } + if (request.args[1] === "ensure-image") { + calls.push(String(request.args[3])); + return { image_id: `sha256:${"c".repeat(64)}` }; + } + return await original(request); + }; + expect(await startNativeProject(opts)).toBe(0); + expect(calls).toEqual(["batch", "alpine:1", "redis:1"]); +}); + test("a changed 11-service plan uses the loaded selections of two recorded references", async () => { const { opts } = await fixture(false); const image = `sha256:${"e".repeat(64)}`; From 79634caa56bc9ecad23902955050cc1246c2611e Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:23:10 +0000 Subject: [PATCH 05/33] fix(native): preserve stray image staging entries --- .../runtime-core/src/provider/image_ensure.rs | 156 ++++++++++++++---- src/backends/native-image-policy.ts | 27 ++- src/backends/native-runtime-client.ts | 6 +- tests/native-image-tags.test.ts | 22 +++ 4 files changed, 175 insertions(+), 36 deletions(-) diff --git a/packages/runtime-core/src/provider/image_ensure.rs b/packages/runtime-core/src/provider/image_ensure.rs index 4e2fda6f7..dc19d51dc 100644 --- a/packages/runtime-core/src/provider/image_ensure.rs +++ b/packages/runtime-core/src/provider/image_ensure.rs @@ -14,7 +14,7 @@ use std::{ collections::BTreeMap, fs, io::Read, - os::unix::fs::{MetadataExt, OpenOptionsExt}, + os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}, path::{Path, PathBuf}, sync::{Arc, Condvar, Mutex, MutexGuard}, }; @@ -70,7 +70,7 @@ impl ImageCache { let lease = lifecycle::startup_lease(root, lifecycle::STARTUP_LEASE_WAIT)?; let staging = root.with_file_name("image-staging"); if staging.try_exists().map_err(state::io)? { - clean_staging(&staging, true)?; + clean_staging(&staging, 0)?; } cache.lease = Some(lease); } @@ -106,7 +106,17 @@ fn disk_available(path: &Path) -> Result { Ok(bytes.saturating_sub(RESERVE)) } -fn clean_staging(path: &Path, root: bool) -> Result<(), CandidateError> { +fn generated_sequence(name: &str) -> bool { + name.split_once('-').is_some_and(|(pid, sequence)| { + pid.parse::() + .is_ok_and(|value| value > 0 && value.to_string() == pid) + && sequence + .parse::() + .is_ok_and(|value| value.to_string() == sequence) + }) +} + +fn clean_staging(path: &Path, level: u8) -> Result<(), CandidateError> { if !path.try_exists().map_err(state::io)? { return Ok(()); } @@ -116,33 +126,47 @@ fn clean_staging(path: &Path, root: bool) -> Result<(), CandidateError> { let name = entry.file_name(); let name = name.to_string_lossy(); let metadata = fs::symlink_metadata(entry.path()).map_err(state::io)?; - if root && hex(&name) && metadata.is_dir() && metadata.uid() == current_uid() { - clean_staging(&entry.path(), false)?; + if metadata.uid() != current_uid() { continue; } - let generated = matches!(&*name, "image.tar" | "receipt.json" | "receipt.pending") + let generated_dir = (level == 0 && hex(&name)) + || (level == 1 + && name + .strip_prefix("attempt-") + .is_some_and(generated_sequence)); + if generated_dir && metadata.is_dir() && metadata.mode() & 0o077 == 0 { + clean_staging(&entry.path(), level + 1)?; + } + let generated_file = matches!(&*name, "image.tar" | "receipt.json" | "receipt.pending") || [".hack-image-", ".hack-layer-"].iter().any(|prefix| { name.strip_prefix(prefix) .and_then(|tail| tail.strip_suffix(".tmp")) - .and_then(|tail| tail.split_once('-')) - .is_some_and(|(pid, sequence)| { - pid.parse::() - .is_ok_and(|value| value > 0 && value.to_string() == pid) - && sequence - .parse::() - .is_ok_and(|value| value.to_string() == sequence) - }) + .is_some_and(generated_sequence) }); - if !root && generated && metadata.is_file() && metadata.uid() == current_uid() { + if level > 0 && generated_file && metadata.is_file() { fs::remove_file(entry.path()).map_err(state::io)?; - } else { - return Err(CandidateError::new( - "image_staging_entry", - format!("Unexpected image staging entry {name:?} was left in place."), - )); } } - fs::remove_dir(path).map_err(state::io) + match fs::remove_dir(path) { + Err(error) if error.kind() == std::io::ErrorKind::DirectoryNotEmpty => Ok(()), + result => result.map_err(state::io), + } +} + +fn create_staging(root: &Path, reference: &str) -> Result { + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(0); + let key_dir = root.with_file_name("image-staging").join(key(reference)); + state::private_directory(&key_dir)?; + loop { + let sequence = NEXT.fetch_add(1, Ordering::Relaxed); + let attempt = key_dir.join(format!("attempt-{}-{sequence}", std::process::id())); + match fs::DirBuilder::new().mode(0o700).create(&attempt) { + Ok(()) => return Ok(attempt), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(state::io(error)), + } + } } struct Reservation<'a> { @@ -153,7 +177,10 @@ struct Reservation<'a> { impl Drop for Reservation<'_> { fn drop(&mut self) { - let _ = clean_staging(&self.path, false); + let _ = clean_staging(&self.path, 2); + if let Some(key_dir) = self.path.parent() { + let _ = fs::remove_dir(key_dir); + } self.cache .state .lock() @@ -410,7 +437,15 @@ pub(super) fn publish_proof( lock.verify_path(parent)?; fs::remove_file(pending).map_err(state::io)?; } - Ok(_) => return Err(refused("Unsafe pending image proof was left in place.")), + Ok(_) => { + let name = pending.file_name().unwrap().to_string_lossy(); + let location = format!("artifacts/image-proofs/{name}"); + return Err(CandidateError::new( + "image_proof_pending", + format!("Unsafe pending image proof at {location} was left in place."), + ) + .with_state_component(&location)); + } Err(error) if error.kind() == std::io::ErrorKind::NotFound => (), Err(error) => return Err(state::io(error)), } @@ -976,8 +1011,7 @@ fn ensure_pinned_coordinated( state = coordinator.changed.wait(state).unwrap(); occupied = inventory()?; }; - let staging = root.with_file_name("image-staging").join(key(&reference)); - state::private_directory(&staging)?; + let staging = create_staging(&root, &reference)?; state.reservations.insert(reference.clone(), limit); let reservation = Reservation { cache: coordinator, @@ -1012,6 +1046,7 @@ fn ensure_pinned_coordinated( return Err(refused("New archive differs from its acquisition receipt.")); } state::write(&dir.join("receipt.json"), &receipt)?; + inspect_entry(candidate, dir, &reference, acquired.platform)?; let state = coordinator.enter(&root)?; let target = root.join(entry_key(&reference, acquired.platform)); if target.try_exists().map_err(state::io)? { @@ -1170,16 +1205,71 @@ mod tests { } #[test] - fn unrelated_staging_files_are_named_and_preserved() { + fn a_batch_reuses_staging_without_moving_or_deleting_stray_entries() { let f = Fixture::new(); let root = f.1.state_root.join("artifacts/images"); - let staged = root.with_file_name("image-staging").join(key(&pin(1))); - state::private_directory(&staged).unwrap(); - let unrelated = staged.join("unrelated"); - fs::write(&unrelated, b"fixture").unwrap(); - let error = ImageCache::default().enter(&root).err().unwrap(); - assert!(error.message.contains("unrelated")); - assert_eq!(fs::read(unrelated).unwrap(), b"fixture"); + let staging = root.with_file_name("image-staging"); + let key_dir = staging.join(key(&pin(1))); + let foreign = key_dir.join("foreign"); + state::private_directory(&foreign).unwrap(); + for path in [ + staging.join(".DS_Store"), + key_dir.join(".DS_Store"), + foreign.join(".hack-image-1-0.tmp"), + ] { + fs::write(path, b"stray").unwrap(); + } + let leftover = key_dir.join(".hack-image-1-0.tmp"); + fs::write(&leftover, b"partial").unwrap(); + let attempt = key_dir.join("attempt-1-0"); + state::private_directory(&attempt).unwrap(); + fs::write(attempt.join(".hack-layer-1-0.tmp"), b"partial").unwrap(); + + let cache = ImageCache::default(); + for id in [1, 2] { + ensure_pinned_coordinated( + (&f.1, &cache), + &pin(id), + &ImagePolicy::default(), + PlatformPolicy::Native, + |_, _| panic!("no platform lookup"), + acquire, + |_, _, _, _| Ok(()), + ) + .unwrap(); + } + assert_eq!(usage(&f.1, &root).unwrap(), (2, 14)); + for path in [ + staging.join(".DS_Store"), + key_dir.join(".DS_Store"), + foreign.join(".hack-image-1-0.tmp"), + ] { + assert_eq!(fs::read(path).unwrap(), b"stray"); + } + assert!(!leftover.exists()); + assert!(!attempt.exists()); + } + + #[test] + fn an_unsafe_pending_proof_names_the_preserved_entry() { + let f = Fixture::new(); + let pending = + manifest_path(&f.1, &pin(1), PlatformPolicy::Native).with_extension("pending"); + state::private_directory(&pending).unwrap(); + let failure = publish_proof( + &f.1, + &pin(1), + PlatformPolicy::Native, + ®istry_image::test_manifest_resolution().proof, + ) + .unwrap_err(); + assert_eq!(failure.code, "image_proof_pending"); + assert!( + failure + .message + .contains(pending.file_name().unwrap().to_str().unwrap()) + ); + assert!(pending.is_dir()); } #[test] diff --git a/src/backends/native-image-policy.ts b/src/backends/native-image-policy.ts index 4cc1b6f18..241312686 100644 --- a/src/backends/native-image-policy.ts +++ b/src/backends/native-image-policy.ts @@ -140,6 +140,27 @@ export class NativeImageBatchError extends HackCliError { } } +const PENDING_PROOF_PATH = /^artifacts\/image-proofs\/[a-f0-9]{64}\.pending$/; + +export function pendingImageProofReason( + value: Record +): string | undefined { + const component = value.state_component; + if ( + !( + value.code === "image_proof_pending" && + component && + typeof component === "object" && + "path" in component && + typeof component.path === "string" && + PENDING_PROOF_PATH.test(component.path) + ) + ) { + return; + } + return `Unsafe pending image proof at ${component.path} was left in place`; +} + export function batchImageFailure( reference: string, value: unknown, @@ -153,10 +174,12 @@ export function batchImageFailure( typeof error.code === "string" && IMAGE_FAILURE_CODE.test(error.code) ? error.code : "image_reply_invalid"; - let reason = nativeImageRegistryReason(error.cause_code); + let reason = + nativeImageRegistryReason(error.cause_code) ?? + pendingImageProofReason(error); if ( !reason && - (error.message_fixed === true || code === "image_staging_entry") && + error.message_fixed === true && typeof error.message === "string" && IMAGE_FAILURE_TEXT.test(error.message) ) { diff --git a/src/backends/native-runtime-client.ts b/src/backends/native-runtime-client.ts index 4ce2120b0..bfe6c1eff 100644 --- a/src/backends/native-runtime-client.ts +++ b/src/backends/native-runtime-client.ts @@ -19,7 +19,10 @@ import { readNativeConfigurationRefusals, } from "./native-configuration-refusals.ts"; import { nativeHotReloadEnvironment } from "./native-hot-reload-notice.ts"; -import { nativeImageRegistryReason } from "./native-image-policy.ts"; +import { + nativeImageRegistryReason, + pendingImageProofReason, +} from "./native-image-policy.ts"; import { type NativePlanChange, nativePlanChangeGuidance, @@ -499,6 +502,7 @@ export function nativeFailureDetail(value: Record): { const message = networkRequestFailureMessage(value) ?? stateComponentFailureMessage(value) ?? + pendingImageProofReason(value) ?? bridgeSocketsFailureMessage(value) ?? execStageFailureMessage(value) ?? routeProbeFailureMessage(value, service) ?? diff --git a/tests/native-image-tags.test.ts b/tests/native-image-tags.test.ts index 9f56cab0d..235474579 100644 --- a/tests/native-image-tags.test.ts +++ b/tests/native-image-tags.test.ts @@ -1,4 +1,8 @@ import { expect, test } from "bun:test"; +import { + batchImageFailure, + pendingImageProofReason, +} from "../src/backends/native-image-policy.ts"; import { nativeImageBlocker } from "../src/backends/native-image-tags.ts"; const runtime = { binary: "/fixture/hack-native", home: "/fixture/home" }; @@ -31,3 +35,21 @@ test("an unavailable tag names the missing image and the locally observed images "Run hack pull when the registry is reachable, then retry hack up.", ]); }); + +test("an unsafe pending proof names only the admitted relative file", () => { + const path = `artifacts/image-proofs/${"a".repeat(64)}.pending`; + const value = { + code: "image_proof_pending", + state_component: { version: 1, path }, + }; + expect(pendingImageProofReason(value)).toContain(path); + expect(batchImageFailure("example/image:stable", value, []).reason).toContain( + path + ); + expect( + pendingImageProofReason({ + ...value, + state_component: { path: "/untrusted/pending" }, + }) + ).toBeUndefined(); +}); From 011e97e8109f51dd147ce782d66be86c2fc90034 Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:00:40 +0000 Subject: [PATCH 06/33] fix(models): require the final counterexample state --- scripts/lib/tla-result.ts | 28 +++++++++++++--------------- scripts/lib/tla-runtime-models.ts | 5 ++++- tests/tla-runtime-models.test.ts | 1 + 3 files changed, 18 insertions(+), 16 deletions(-) diff --git a/scripts/lib/tla-result.ts b/scripts/lib/tla-result.ts index 71c8e34df..11d947ce6 100644 --- a/scripts/lib/tla-result.ts +++ b/scripts/lib/tla-result.ts @@ -83,7 +83,7 @@ export function verifyRestoreHistoryModelResult(opts: { ); } -const TRACE_STATES = /(?=State \d+:)/; +const TRACE_STATES = /(?=^State \d+:)/m; const DISTINCT_STATES = /\b(\d+) distinct states found, 0 states left on queue\b/; @@ -123,22 +123,20 @@ export function verifyFiniteModelResult(opts: { ) { return false; } + const finalState = opts.output.split(TRACE_STATES).at(-1) ?? ""; + const lines = finalState.split(/\r?\n/); + const header = lines[0] ?? ""; return ( opts.exitCode === 12 && opts.output.includes(`Invariant ${opts.invariant} is violated.`) && - opts.output.split(TRACE_STATES).some((state) => { - const lines = state.split(/\r?\n/); - if (!/^State \d+: - lines[0]?.includes(`<${witness.action} `) && - witness.fields.every((field) => lines.includes(`/\\ ${field}`)) - ); - }) + /^State \d+: + header.slice(header.indexOf("<")).startsWith(`<${witness.action} `) && + witness.fields.every((field) => lines.includes(`/\\ ${field}`)) + ) ); } diff --git a/scripts/lib/tla-runtime-models.ts b/scripts/lib/tla-runtime-models.ts index 7b0f94b4d..22d9ac3aa 100644 --- a/scripts/lib/tla-runtime-models.ts +++ b/scripts/lib/tla-runtime-models.ts @@ -3302,7 +3302,10 @@ const contracts: readonly ModelContract[] = [ states: 3233, invariant: "Safe", action: "Import", - fields: ['phase = <<"import", "import", "queued", "queued">>'], + fields: [ + 'phase = <<"import", "import", "queued", "queued">>', + "verified = {1, 2}", + ], }, { name: "native-image-presence", diff --git a/tests/tla-runtime-models.test.ts b/tests/tla-runtime-models.test.ts index a8bd7a8a1..3f94e8617 100644 --- a/tests/tla-runtime-models.test.ts +++ b/tests/tla-runtime-models.test.ts @@ -51,6 +51,7 @@ for (const model of contracts) { "Parse error", output.replace(`Invariant ${model.invariant}`, "Invariant Wrong"), output.replace(`<${model.action} `, "\n${fields.join("\n")}`, `${header}\n${fields[0]}\nState 3: \n${fields[1]}`, ]) { expect( From 70a36dccb32ceb99dd2aff903605f63d67989601 Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:24:43 +0000 Subject: [PATCH 07/33] perf(native): overlap first-start project image builds --- docs/guides/native-candidate.md | 6 + docs/reference/v5-model-coverage.md | 2 + scripts/lib/tla-runtime-models.ts | 17 +++ src/backends/native-project-builds.ts | 122 +++++++++++++---- src/backends/native-project-start.ts | 22 ++- src/commands/project.ts | 12 +- .../tla/native-build-batch/BuildBatch.tla | 32 +++++ .../models/tla/native-build-batch/COVERAGE.md | 15 +++ .../tla/native-build-batch/build-batch.svg | 20 +++ .../tla/native-build-batch/cancel-wins.cfg | 8 ++ .../tla/native-build-batch/negative.cfg | 8 ++ .../tla/native-build-batch/positive.cfg | 8 ++ tests/native-project-builds.test.ts | 125 ++++++++++++++++++ tests/native-refusal-cli.test.ts | 58 ++++++-- 14 files changed, 419 insertions(+), 36 deletions(-) create mode 100644 tests/models/tla/native-build-batch/BuildBatch.tla create mode 100644 tests/models/tla/native-build-batch/COVERAGE.md create mode 100644 tests/models/tla/native-build-batch/build-batch.svg create mode 100644 tests/models/tla/native-build-batch/cancel-wins.cfg create mode 100644 tests/models/tla/native-build-batch/negative.cfg create mode 100644 tests/models/tla/native-build-batch/positive.cfg diff --git a/docs/guides/native-candidate.md b/docs/guides/native-candidate.md index 1c98cd0cc..f42e99737 100644 --- a/docs/guides/native-candidate.md +++ b/docs/guides/native-candidate.md @@ -1447,6 +1447,12 @@ If the prepared tree changes, `runtime probe` and every build refuse with `artifact_digest_mismatch`. `runtime probe` reports `builder_prepared`: `true` when the client is present and unchanged, `false` for a home without it. +A project's first native start can build distinct images together. The +four-CPU development pool runs at most three builds at once. Identical build +requests still share one build. A failure or Ctrl-C requests cancellation of +the other builds, and the CLI waits for all started builds to settle before +returning. The foreground labels output by build and reports its elapsed time. + A home without the image builder refuses a build with `builder_not_prepared`: "The image builder is not installed in this native home", with the setup command that adds it, instead of a missing-file error. `hack up` prints that refusal with diff --git a/docs/reference/v5-model-coverage.md b/docs/reference/v5-model-coverage.md index 70c918ac5..fabc78115 100644 --- a/docs/reference/v5-model-coverage.md +++ b/docs/reference/v5-model-coverage.md @@ -75,6 +75,7 @@ must be attached to the eventual exact integration revision. | Private environment allocation lifetime: staged values and private file members, crash between record and stage, retirement with the container | **Coverage gap:** no maintained model covers environment or credential delivery; file members share the existing allocation, intent record and retirement, so the state machine is unchanged | `packages/runtime-core/src/provider/environment.rs` (preparation bounds, staging layout, verification), `managed_environment.rs` (envelope v2 refusals, forwarding), `graph/launcher.rs` (read-only binds, overlap refusals) and `environment_recovery.rs` retirement tests | Live VM evidence that only the owning UID reads a member, writes fail read-only and the member is absent after cleanup; refresh or rotation of delivered files is not implemented. | | One pool, many project roots: share-set changes, boot mounts, per-project share selection, removal of a referenced share | multi-root-share | `provider::share_update` (journaled stopped-pool add/remove, record before owner), `project_share::{check_request, check_boot, validate_set}`, `OwnedGuest::project_share_for`; `share_update` and `project_share` unit tests | Real provider boot with an updated mount record, virtio-fs device limits and live multi-project graphs on a host VM. Cross-project cleanup is abstracted to one run's own resources. | | Cached image presence before archive reads | [native-image-presence](../../tests/models/tla/native-image-presence/COVERAGE.md) | `image_load::load_waiting` requires live exact image and platform readback for receipt reuse and verifies the archive on any upload path. Explicit archive loads retain their early hash. | One request, one archive, one lease, one boot. Expiry and registry availability may change before tag selection. Guest eviction may precede readback or create. Guest ownership, filesystem behavior, interrupted imports and performance require separate runtime evidence. | +| First-start build batch: authored dispatch, bounded concurrency, stop and drain | [native-build-batch](../../tests/models/tla/native-build-batch/COVERAGE.md) | `runPendingBuilds` captures the first failure and drains every started invocation. Controlled runtime and source CLI SIGINT regressions cover cancellation and caller exit. | Four distinct keys and a cap of three. Per-key leases and receipts are covered by native-build-retention; actual VM settlement remains host evidence. | | Native image builds: unleased build versus engine stop, crash mid-build, storage recreation, foreign or forged images, reclamation versus retained graph references | native-build-retention | `provider::image_build` (shared build fence, per-key lock, incarnation/boot/engine recheck and label check at adoption, dead-attempt recording) and `image_build::reclaim` (owned labels, current receipts, retained graph state scan, engine non-force removal); `image_build` regressions | One key and namespace. Since key version 2 (HACK-2533) every edited build context makes a new key with its own receipt; reclamation keeps, per build declaration, the current and one previous key's image, plus every image retained state (except its diagnostic restore history, HACK-2554) or a container references and every receipt without a declaration, and an `up` that built runs it best-effort after readiness (`image_build::tests::ten_edits_of_one_build_leave_its_current_and_previous_images`); the model's retained-reference safety is unchanged, and which receipt is current is regression-tested, not modeled. Snapshots of a dead owner are removed at the next build in the namespace, only after the owner is proven gone and under that key's lock (`snapshots_of_dead_owners_are_removed_at_the_next_build_of_any_key`). Which inputs a key covers (context walk, ignore rules, hard-link groups, stat cache) and restore's per-up build decision are regression-tested in `image_build::context` and `image_build` and in `tests/native-project-builds.test.ts`, not modeled. A build client orphaned by a killed `hack-native` is not modeled (the client inherits the build fence and per-key lock, so both stay held until it exits: `image_build::tests::a_killed_coordinator_leaves_its_client_fenced`); real BuildKit, engine removal semantics and guest storage are host evidence. | | Runtime service per native home (HACK-2460, design): start race, crash at any step, version skew and drain, lost replies, resends on new connections, one-shot fallback, inspection of started but unfinished work | runtime-service | Process half implemented as a library; nothing starts or calls it yet. `TakeLock`, `LoseRace` and `Bind` map to `service::start` (a lock on the private `run/service/` directory, then `service.lock`, each checked against its path and held for the process's whole life, drain included; an existing socket is probed and kept if anything answers). `IdleExit`, `Retire`, `RefuseDraining` and `ExitDrained` map to `run`, `refuse_queued` and `shut_down`, with `settle` releasing ownership only after a complete drain. The tests in `packages/runtime-core/src/service/tests.rs` walk each action (concurrent starts, lock replacement while serving and while draining, stale and live sockets, idle exit with a held session, retire, connections queued at shutdown, drain timeout). `Crash` gets its real-process SIGKILL test in the next slice. Intent records, admission of mutations, skew, fallback and inspection are not implemented; each later slice adds the regression that walks its actions, behind `HACK_RUNTIME_SERVICE` (default `off`) | Not modelled, covered by regression tests instead: a lock held for a moment after its owner let go, because a forked child shares the open file description until it runs `exec` (the starter's bounded retry window, `service/tests.rs`); the time bound on that window; a drain that runs out of time ending the process at once with exit code 3; a signal (TERM, INT, HUP) draining like retire; and a starter that never reads the notify line (`tests/runtime_service_contract.rs`, `tests/runtime_service_hooks.rs`). The model treats a release as immediate and every drain as finishing. Implemented slice assumes the `run/service/` directory itself is not replaced (replacing `service.lock` is covered) and that the process exits after a drain that ran out of its 10 s bound; it refuses, never serves, connections queued at stop. Assumption each mutation slice must meet: its inspector distinguishes proven absence from missing evidence (for example work a provider accepted but has not yet made visible), and missing evidence yields "unknown", never "not done"; the model makes dispatched work visible at once. Liveness, several leases, cancellation of joined attempts, event cursors, dashboard authentication, the idle-exit queue race and intent-write durability are not modelled. | | MCP cold start, cancellation and duplicate launches | mcp-startup, mcp-startup-cancellation | Shared MCP bundle identity, startup deduplication and cancellation regressions | Fresh supported client sessions, full workflow coverage and measured overhead (WU16/WU20/WU28). | @@ -150,6 +151,7 @@ liveness/reachability controls have their own documented assumptions. | [native-pool-stop](../../tests/models/tla/native-pool-stop/PoolStop.tla) | 210 | 10 | | [start-graph](../../tests/models/tla/start-graph/COVERAGE.md) | 1,656,372 + 81,534 two-boot | 10 | | [probe-readiness](../../tests/models/tla/probe-readiness/ProbeReadiness.tla) | 175,757 | 7 | +| [native-build-batch](../../tests/models/tla/native-build-batch/BuildBatch.tla) | 296 | 2 | | [native-build-retention](../../tests/models/tla/native-build-retention/BuildRetention.tla) | 6,181 | 4 | | [runtime-service](../../tests/models/tla/runtime-service/RuntimeService.tla) | 1,006,849 | 11 | | [shared-helper-instance](../../tests/models/tla/shared-helper-instance/Instance.tla) | 7,649 | 11 | diff --git a/scripts/lib/tla-runtime-models.ts b/scripts/lib/tla-runtime-models.ts index 35262c990..2b1eba956 100644 --- a/scripts/lib/tla-runtime-models.ts +++ b/scripts/lib/tla-runtime-models.ts @@ -2809,6 +2809,23 @@ const contracts: readonly ModelContract[] = [ }, ], }, + { + name: "native-build-batch", + module: "BuildBatch", + states: 296, + invariant: "NoLiveReturn", + action: "Return", + fields: ["result = -2"], + additionalControls: [ + { + name: "cancel-wins", + negative: true, + invariant: "FirstOutcome", + action: "Return", + fields: ["active = {}"], + }, + ], + }, { name: "native-build-retention", module: "BuildRetention", diff --git a/src/backends/native-project-builds.ts b/src/backends/native-project-builds.ts index 2f1e6c48a..a8bd01276 100644 --- a/src/backends/native-project-builds.ts +++ b/src/backends/native-project-builds.ts @@ -585,6 +585,15 @@ export function refuseManagedSecretBuildArguments(opts: { } } +/** Leave a CPU for other guest work on the four-CPU development pool. */ +const MAX_CONCURRENT_PROJECT_BUILDS = 3; + +export type NativeBuildSettlement = { + readonly services: readonly string[]; + readonly durationMs: number; + readonly outcome: "built" | "reused" | "failed" | "cancelled"; +}; + /** * Build (or reuse) every admitted build service in the selected profiles and pin it to * its content ID; returns the pinned services. As with Compose `up`, a build service @@ -602,6 +611,8 @@ export async function buildNativeProjectImages(opts: { readonly specs: Record>; readonly rebuild: boolean; readonly signal: AbortSignal; + readonly guestCpus?: number; + readonly onBuildSettled?: (settlement: NativeBuildSettlement) => void; readonly invoke?: typeof invokeNativeBuild; /** Called once for each build the runtime actually ran (not a reused image). */ readonly onBuilt?: () => void; @@ -786,6 +797,8 @@ async function runPendingBuilds(opts: { readonly specs: Record>; readonly rebuild: boolean; readonly signal: AbortSignal; + readonly guestCpus?: number; + readonly onBuildSettled?: (settlement: NativeBuildSettlement) => void; readonly invoke?: typeof invokeNativeBuild; readonly onBuilt?: () => void; }): Promise { @@ -793,16 +806,81 @@ async function runPendingBuilds(opts: { // The runtime requires the exact canonical root; it also derives the namespace. const projectRoot = await realpath(opts.projectRoot); const directory = await mkdtemp(join(tmpdir(), "hack-native-build-")); + const cpus = opts.guestCpus ?? 1; + const cap = + Number.isSafeInteger(cpus) && cpus > 0 + ? Math.min(MAX_CONCURRENT_PROJECT_BUILDS, cpus) + : 1; + const parallel = cap > 1 && opts.pending.size > 1; + const controller = new AbortController(); + const running = new Set>(); + const interrupt = () => + controller.abort( + new ClosedCliError("Native foreground up was canceled; values omitted.") + ); + opts.signal.addEventListener("abort", interrupt, { once: true }); + if (opts.signal.aborted) { + interrupt(); + } + + const runBuild = async (requestFile: string, services: readonly string[]) => { + const started = performance.now(); + let outcome: NativeBuildSettlement["outcome"] = "failed"; + try { + const built = await invoke({ + runtime: opts.runtime, + cwd: opts.projectRoot, + requestFile, + signal: controller.signal, + ...(parallel + ? { + write: (line: string) => + process.stderr.write(`[${services.join(", ")}] ${line}`), + } + : {}), + }); + if (controller.signal.aborted) { + outcome = "cancelled"; + return; + } + outcome = built.reused ? "reused" : "built"; + if (!built.reused) { + opts.onBuilt?.(); + } + for (const service of services) { + const spec = opts.specs[service]; + if (spec) { + pin(spec, built.imageId); + } + } + } catch (error) { + if (controller.signal.aborted) { + outcome = "cancelled"; + } else { + controller.abort(nameBuildFailure(services, error)); + } + } finally { + if (parallel) { + opts.onBuildSettled?.({ + services, + outcome, + durationMs: performance.now() - started, + }); + } + await rm(requestFile, { force: true }); + } + }; + try { let index = 0; for (const { request, services } of opts.pending.values()) { - if (opts.signal.aborted) { - throw new ClosedCliError( - "Native foreground up was canceled; values omitted." - ); + if (running.size >= cap) { + await Promise.race(running); } - const requestFile = join(directory, `request-${index}.json`); - index += 1; + if (controller.signal.aborted) { + break; + } + const requestFile = join(directory, `request-${index++}.json`); await writeFile( requestFile, JSON.stringify({ @@ -818,29 +896,25 @@ async function runPendingBuilds(opts: { }), { mode: 0o600, flag: "wx" } ); - const built = await invoke({ - runtime: opts.runtime, - cwd: opts.projectRoot, - requestFile, - signal: opts.signal, - }).catch((error: unknown) => { - throw nameBuildFailure(services, error); - }); - // The request carries argument values; remove it as soon as it is consumed. - await rm(requestFile, { force: true }); - if (!built.reused) { - opts.onBuilt?.(); - } - for (const service of services) { - const spec = opts.specs[service]; - if (spec) { - pin(spec, built.imageId); - } + // Stage sequentially so the runtime calls start in authored order. + if (controller.signal.aborted) { + break; } + const task = runBuild(requestFile, services) + .catch((error: unknown) => controller.abort(error)) + .finally(() => { + running.delete(task); + }); + running.add(task); } + } catch (error) { + controller.abort(error); } finally { + await Promise.all(running); + opts.signal.removeEventListener("abort", interrupt); await rm(directory, { recursive: true, force: true }); } + controller.signal.throwIfAborted(); } /** diff --git a/src/backends/native-project-start.ts b/src/backends/native-project-start.ts index 6f716432a..c373dd758 100644 --- a/src/backends/native-project-start.ts +++ b/src/backends/native-project-start.ts @@ -84,6 +84,7 @@ import { buildNativeProjectImages, invokeNativeBuild, type NativeBuildRequest, + type NativeBuildSettlement, type NativeVerifiedBuild, nativeBuildsEnabled, nativeRebuildRequested, @@ -776,6 +777,8 @@ async function resolveNativeBuildImages(opts: { readonly specs: Record>; readonly verified: ReadonlyMap | undefined; readonly signal: AbortSignal; + readonly guestCpus?: number; + readonly onBuildSettled?: (settlement: NativeBuildSettlement) => void; readonly invoke: typeof invokeNativeBuild | undefined; readonly onBuilt: () => void; }): Promise> { @@ -2107,7 +2110,8 @@ export type NativeStartupProgress = /** Indented route, unserved-route and published-port lines. */ readonly endpoints: readonly string[]; } - | ({ readonly phase: "service-exited" } & NativeServiceExit); + | ({ readonly phase: "service-exited" } & NativeServiceExit) + | ({ readonly phase: "build-settled" } & NativeBuildSettlement); function progressReporter( observe: ((event: NativeStartupProgress) => void) | undefined @@ -2333,6 +2337,19 @@ function emitNativeLeftOutNotice(opts: { ); } +/** Guest CPU allocation is fixed by the runtime profile (provider/profile.rs). */ +function nativePoolBuildCpus(pool: unknown): number { + if (isRecord(pool)) { + if (pool.profile === "development") { + return 4; + } + if (pool.profile === "research") { + return 2; + } + } + return 1; +} + /** * Once per start, when the pool runs with hot reload on shared source off, or * forced on over a large share: printed, or handed to a detached launcher. @@ -2885,6 +2902,9 @@ async function startNativeProjectAttempt( builds, specs, verified: opts.verifiedBuildImages, + guestCpus: restore ? 1 : nativePoolBuildCpus(pool), + onBuildSettled: (settled) => + progress({ phase: "build-settled", ...settled }), signal: controller.signal, invoke: deps.build, onBuilt: () => { diff --git a/src/commands/project.ts b/src/commands/project.ts index 996c28871..bcce4fa22 100644 --- a/src/commands/project.ts +++ b/src/commands/project.ts @@ -43,7 +43,7 @@ import { writeStartBlocker, writeUpHookBlocker, } from "../ui/start-refusal-output.ts"; -import { createTextOutput } from "../ui/text-output.ts"; +import { createTextOutput, formatDuration } from "../ui/text-output.ts"; import { writeComposeStarted } from "./compose-lifecycle-closing.ts"; import { createComposeUpProgress, @@ -6623,6 +6623,11 @@ function reportNativeStartupProgress(event: NativeStartupProgress): void { case "runtime": logger.step({ message: "Starting the native runtime…" }); return; + case "build-settled": + logger.info({ + message: `Build ${event.services.join(", ")}: ${event.outcome} in ${formatDuration(event.durationMs)}`, + }); + return; case "images": logger.step({ message: "Acquiring service images…" }); return; @@ -6982,7 +6987,10 @@ async function handleNativeUp({ if (event.phase === "ready") { ready = true; } - if (restart || ready || event.phase !== "stopped") { + if ( + (restart || ready || event.phase !== "stopped") && + (event.phase !== "build-settled" || args.options.json !== true) + ) { reportNativeStartupProgress(event); } }, diff --git a/tests/models/tla/native-build-batch/BuildBatch.tla b/tests/models/tla/native-build-batch/BuildBatch.tla new file mode 100644 index 000000000..4272de6e3 --- /dev/null +++ b/tests/models/tla/native-build-batch/BuildBatch.tla @@ -0,0 +1,32 @@ +---- MODULE BuildBatch ---- +EXTENDS Integers, FiniteSets +CONSTANTS Jobs, Cap, EarlyReturn, CancelWins +VARIABLES next, active, stop, cancelled, result +vars == <> +Init == /\ next = 1 /\ active = {} /\ stop = 0 + /\ cancelled = {} /\ result = -1 +Start == /\ result = -1 /\ stop = 0 + /\ next \in Jobs /\ Cardinality(active) < Cap + /\ active' = active \cup {next} /\ next' = next + 1 + /\ UNCHANGED <> +Fail(j) == /\ result = -1 /\ j \in active /\ stop = 0 + /\ stop' = j /\ active' = active \ {j} + /\ UNCHANGED <> +Interrupt == /\ result = -1 /\ stop = 0 + /\ stop' = -2 + /\ UNCHANGED <> +Settle(j) == /\ result = -1 /\ j \in active + /\ active' = active \ {j} + /\ cancelled' = IF stop = 0 THEN cancelled ELSE cancelled \cup {j} + /\ UNCHANGED <> +Return == /\ result = -1 + /\ (stop # 0 \/ next \notin Jobs) + /\ (active = {} \/ (EarlyReturn /\ stop = -2)) + /\ result' \in IF CancelWins /\ stop \in Jobs /\ cancelled # {} THEN cancelled ELSE {stop} + /\ UNCHANGED <> +Next == Start \/ Interrupt \/ Return \/ \E j \in Jobs: Fail(j) \/ Settle(j) +NoLiveReturn == result # -1 => active = {} +FirstOutcome == result # -1 => result = stop +Bounded == Cardinality(active) <= Cap +Spec == Init /\ [][Next]_vars +==== diff --git a/tests/models/tla/native-build-batch/COVERAGE.md b/tests/models/tla/native-build-batch/COVERAGE.md new file mode 100644 index 000000000..671e074c9 --- /dev/null +++ b/tests/models/tla/native-build-batch/COVERAGE.md @@ -0,0 +1,15 @@ +# Native image build batch + +Four distinct build keys, a cap of three, and one upstream interrupt. +`Start` is the authored-order CLI dispatch after its private request is written. +`Fail` settles the failing invocation and captures the first observed error. +`Interrupt` covers user cancellation. Both prevent further dispatch. +`Settle` removes an invocation only after its promise settles. `Return` requires +an empty active set and reports the original outcome. The model assumes each +invocation's promise settles after its owned runtime child exits. Runtime-side +lease and BuildKit settlement, forced termination, and receipts remain the +existing single-build contract and are outside this batch model. + +TLC 1.7.4 explored 296 states. The early-return control violated +`NoLiveReturn` and the cancellation-error control violated `FirstOutcome`. +See the [state chart](build-batch.svg). diff --git a/tests/models/tla/native-build-batch/build-batch.svg b/tests/models/tla/native-build-batch/build-batch.svg new file mode 100644 index 000000000..0e1f99575 --- /dev/null +++ b/tests/models/tla/native-build-batch/build-batch.svg @@ -0,0 +1,20 @@ + + Build batch: dispatch, cancel and settle + + + + + + + + + + + + Dispatch in orderAt most three live + Abort siblingsKeep first outcome + ReturnNo builds live + Fail or Ctrl-CAll settled + All queued builds succeeded and settled + + diff --git a/tests/models/tla/native-build-batch/cancel-wins.cfg b/tests/models/tla/native-build-batch/cancel-wins.cfg new file mode 100644 index 000000000..f05668b6a --- /dev/null +++ b/tests/models/tla/native-build-batch/cancel-wins.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + Jobs = {1, 2, 3, 4} + Cap = 3 + EarlyReturn = FALSE + CancelWins = TRUE +INVARIANTS NoLiveReturn FirstOutcome Bounded +CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-build-batch/negative.cfg b/tests/models/tla/native-build-batch/negative.cfg new file mode 100644 index 000000000..711d55634 --- /dev/null +++ b/tests/models/tla/native-build-batch/negative.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + Jobs = {1, 2, 3, 4} + Cap = 3 + EarlyReturn = TRUE + CancelWins = FALSE +INVARIANTS NoLiveReturn FirstOutcome Bounded +CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-build-batch/positive.cfg b/tests/models/tla/native-build-batch/positive.cfg new file mode 100644 index 000000000..d9b3a2d59 --- /dev/null +++ b/tests/models/tla/native-build-batch/positive.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + Jobs = {1, 2, 3, 4} + Cap = 3 + EarlyReturn = FALSE + CancelWins = FALSE +INVARIANTS NoLiveReturn FirstOutcome Bounded +CHECK_DEADLOCK FALSE diff --git a/tests/native-project-builds.test.ts b/tests/native-project-builds.test.ts index 5906d05e6..084531a7e 100644 --- a/tests/native-project-builds.test.ts +++ b/tests/native-project-builds.test.ts @@ -774,3 +774,128 @@ test("a native home without the image builder says so and how to add it", async expect(message).not.toContain(VALUE); expect(written.join("")).toBe("resolving base images\n"); }); + +test.each([ + { cpus: 4, cap: 3, outcome: "success" }, + { cpus: 2, cap: 2, outcome: "success" }, + { cpus: 1, cap: 1, outcome: "success" }, + { cpus: 4, cap: 3, outcome: "failure" }, + { cpus: 4, cap: 3, outcome: "interrupt" }, +] as const)("build batch $outcome with $cpus guest CPUs", async ({ + cpus, + cap, + outcome, +}) => { + const project = await root(); + const controller = new AbortController(); + const names = ["web", "worker", "tools", "jobs"]; + const builds = new Map( + names.map((target) => [target, { ...request(), target }]) + ); + builds.set("duplicate", { ...request(), target: "web" }); + const specs = Object.fromEntries( + [...builds.keys()].map((name) => [name, { build: "app" }]) + ); + const started: string[] = []; + const releases = new Map< + string, + ReturnType> + >(); + const cancelled = new Set(); + const completed: string[] = []; + const settlements: string[] = []; + let returned = false; + const result = buildNativeProjectImages({ + runtime: { binary: "/test/runtime", home: project } as never, + projectRoot: project, + branch: null, + profiles: [], + builds, + specs, + rebuild: false, + guestCpus: cpus, + signal: controller.signal, + onBuildSettled: ({ outcome: decision, services }) => { + settlements.push(`${services.join(",")}: ${decision}`); + }, + invoke: async ({ requestFile, signal }) => { + const target = + names[Number(/request-(\d+)\.json$/.exec(requestFile)?.[1])]; + if (target === undefined) { + throw new Error("Unexpected request index"); + } + expect(releases.size).toBeLessThan(cap); + started.push(target); + const release = Promise.withResolvers(); + releases.set(target, release); + signal?.addEventListener("abort", () => cancelled.add(target), { + once: true, + }); + const fail = await release.promise; + releases.delete(target); + completed.push(target); + if (fail || cancelled.has(target)) { + throw new NativeRuntimeRequestError({ + message: `fixture ${target}`, + nativeCode: "native_build_failed", + }); + } + return { imageId: IMAGE, buildKey: KEY, reused: false }; + }, + }) + .catch((error: unknown) => error) + .finally(() => { + returned = true; + }); + + const waitFor = async (condition: () => boolean) => { + const end = performance.now() + 2000; + while (!(condition() || returned) && performance.now() < end) { + await Bun.sleep(2); + } + expect(condition()).toBe(true); + }; + try { + await waitFor(() => started.length === cap); + expect(started).toEqual(names.slice(0, cap)); + if (outcome === "success") { + for (let index = 0; index < names.length; index++) { + const name = names[index] ?? ""; + await waitFor(() => releases.has(name)); + releases.get(name)?.resolve(false); + } + expect(await result).toEqual(new Set([...builds.keys()])); + expect(started).toEqual(names); + expect(specs.duplicate).toEqual({ image: IMAGE }); + expect(settlements).toHaveLength(cap > 1 ? names.length : 0); + } else { + if (outcome === "failure") { + releases.get("worker")?.resolve(true); + await waitFor(() => cancelled.has("web")); + } else { + controller.abort(); + await waitFor(() => cancelled.size === cap); + } + expect(returned).toBe(false); + for (const release of releases.values()) { + release.resolve(false); + } + const error = await result; + expect(error).toBeInstanceOf(Error); + expect(String(error)).toContain( + outcome === "failure" + ? "service worker: fixture worker" + : "was canceled" + ); + expect(started).toEqual(names.slice(0, cap)); + expect(completed.toSorted()).toEqual(names.slice(0, cap).toSorted()); + expect(releases.size).toBe(0); + } + } finally { + controller.abort(); + for (const release of releases.values()) { + release.resolve(false); + } + await result; + } +}); diff --git a/tests/native-refusal-cli.test.ts b/tests/native-refusal-cli.test.ts index a95865971..1874e71f6 100644 --- a/tests/native-refusal-cli.test.ts +++ b/tests/native-refusal-cli.test.ts @@ -95,6 +95,14 @@ async function fixture(compose = COMPOSE) { binary, `#!/bin/sh ${nativeSetupShellReply()} +if [ "$3-$4" = runtime-build-image ] && [ -f '${stub}/runtime-build-image.hold' ]; then + request="${"$"}{6##*/}" + trap '' INT + trap 'printf settled > "$request.settled"; exit 1' TERM + printf '%s' ready > "$request.ready" + for i in $(seq 1 400); do sleep 0.05; done + exit 99 +fi if [ -f '${stub}/'"$3-$4"'.hold' ]; then printf '%s' ready > './interrupt-ready' exec sleep 20 @@ -883,10 +891,23 @@ test( const REGISTRY_COMPOSE = JSON.stringify({ services: { web: { image: "localhost:5000/example/app:1" } }, }); -test.each(["fetch", "graph", "hook"] as const)( +const BUILD_COMPOSE = JSON.stringify({ + services: { + web: { build: { context: "..", target: "web" } }, + worker: { build: { context: "..", target: "worker" } }, + tools: { build: { context: "..", target: "tools" } }, + }, +}); +test.each(["fetch", "graph", "hook", "build"] as const)( "Ctrl-C during native startup %s reports one interruption and exits 130", async (stage) => { - const f = await fixture(stage === "fetch" ? REGISTRY_COMPOSE : COMPOSE); + const f = await fixture( + stage === "fetch" + ? REGISTRY_COMPOSE + : stage === "build" + ? BUILD_COMPOSE + : COMPOSE + ); await scriptUpThroughReview(f); if (stage === "fetch") { await f.reply("runtime admit-image", { @@ -897,6 +918,9 @@ test.each(["fetch", "graph", "hook"] as const)( } else if (stage === "graph") { await f.hold("graph serve"); await f.fail("graph inspect", { code: "graph_unreserved" }); + } else if (stage === "build") { + await f.reply("runtime up", { profile: "development" }); + await f.hold("runtime build-image"); } else { await Bun.write( join(f.projectDir, "hack.config.json"), @@ -917,7 +941,7 @@ test.each(["fetch", "graph", "hook"] as const)( [process.execPath, entrypoint, "--path", f.project, "up"], { cwd: f.project, - env: f.env(SHARED), + env: f.env({ ...SHARED, HACK_NATIVE_BUILDS: "1" }), detached: true, stdout: "pipe", stderr: "pipe", @@ -927,14 +951,30 @@ test.each(["fetch", "graph", "hook"] as const)( const stdout = new Response(child.stdout).text(); const stderr = new Response(child.stderr).text(); try { - await waitForFileContent({ - path: join(f.project, "interrupt-ready"), - complete: (value) => (value === "ready" ? value : undefined), - what: stage, - budgetMs: 10_000, - }); + const barriers = + stage === "build" + ? ["request-0.json", "request-1.json", "request-2.json"] + : []; + await Promise.all( + (barriers.length > 0 + ? barriers.map((request) => `${request}.ready`) + : ["interrupt-ready"] + ).map((barrier) => + waitForFileContent({ + path: join(f.project, barrier), + complete: (value) => (value === "ready" ? value : undefined), + what: stage, + budgetMs: 10_000, + }) + ) + ); process.kill(-child.pid, "SIGINT"); expect(await child.exited).toBe(130); + for (const request of barriers) { + expect( + await Bun.file(join(f.project, `${request}.settled`)).text() + ).toBe("settled"); + } const output = (await stdout) + (await stderr); expect( output.split("\n").filter((line) => /interrupted/i.test(line)) From 51f0af6fb016ba49a154265ae09af4bec85b868f Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:25:43 +0000 Subject: [PATCH 08/33] fix(native): preserve first build error through cleanup --- src/backends/native-project-builds.ts | 30 ++++++++++++++++----------- tests/native-project-builds.test.ts | 2 +- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/backends/native-project-builds.ts b/src/backends/native-project-builds.ts index a8bd01276..ad159c4ab 100644 --- a/src/backends/native-project-builds.ts +++ b/src/backends/native-project-builds.ts @@ -812,6 +812,7 @@ async function runPendingBuilds(opts: { ? Math.min(MAX_CONCURRENT_PROJECT_BUILDS, cpus) : 1; const parallel = cap > 1 && opts.pending.size > 1; + const onBuildSettled = parallel ? opts.onBuildSettled : undefined; const controller = new AbortController(); const running = new Set>(); const interrupt = () => @@ -857,16 +858,14 @@ async function runPendingBuilds(opts: { if (controller.signal.aborted) { outcome = "cancelled"; } else { - controller.abort(nameBuildFailure(services, error)); + controller.abort(nameBuildFailure(services, error, parallel)); } } finally { - if (parallel) { - opts.onBuildSettled?.({ - services, - outcome, - durationMs: performance.now() - started, - }); - } + onBuildSettled?.({ + services, + outcome, + durationMs: performance.now() - started, + }); await rm(requestFile, { force: true }); } }; @@ -912,7 +911,9 @@ async function runPendingBuilds(opts: { } finally { await Promise.all(running); opts.signal.removeEventListener("abort", interrupt); - await rm(directory, { recursive: true, force: true }); + await rm(directory, { recursive: true, force: true }).catch( + (error: unknown) => controller.abort(error) + ); } controller.signal.throwIfAborted(); } @@ -947,12 +948,17 @@ const BUILD_SOURCE_POLICY: Readonly> = { */ function nameBuildFailure( services: readonly string[], - error: unknown + error: unknown, + parallel: boolean ): unknown { + const which = serviceList(services); if (!(error instanceof NativeRuntimeRequestError)) { - return error; + return parallel + ? new ClosedCliError( + `Native foreground up could not build ${which}. ${error instanceof ClosedCliError ? error.message : "Build result unavailable; values omitted."}` + ) + : error; } - const which = serviceList(services); const code = error.nativeCode; const change = code !== undefined && Object.hasOwn(BUILD_SOURCE_POLICY, code) diff --git a/tests/native-project-builds.test.ts b/tests/native-project-builds.test.ts index 084531a7e..372085d70 100644 --- a/tests/native-project-builds.test.ts +++ b/tests/native-project-builds.test.ts @@ -793,7 +793,7 @@ test.each([ names.map((target) => [target, { ...request(), target }]) ); builds.set("duplicate", { ...request(), target: "web" }); - const specs = Object.fromEntries( + const specs: Record> = Object.fromEntries( [...builds.keys()].map((name) => [name, { build: "app" }]) ); const started: string[] = []; From 5828716ecc4071172587ff31d494d985948b3591 Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:31:44 +0000 Subject: [PATCH 09/33] test(native): require registry sibling cancellation --- tests/native-project-start.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/native-project-start.test.ts b/tests/native-project-start.test.ts index a24d2e6b9..ec1a9acad 100644 --- a/tests/native-project-start.test.ts +++ b/tests/native-project-start.test.ts @@ -5584,7 +5584,12 @@ test("a parallel build registry refusal keeps its blocker after the sibling sett }; const result = startNativeProject(opts); try { - await Promise.race([siblingAborted.promise, result, Bun.sleep(2000)]); + const aborted = await Promise.race([ + siblingAborted.promise.then(() => true), + result.then(() => false), + Bun.sleep(2000).then(() => false), + ]); + expect(aborted).toBe(true); expect(starts).toBe(2); expect(siblingSettled).toBe(false); } finally { From 9ed94b5829a8f3cdd77acbbd03d0b4dc7e446d3f Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:33:07 +0000 Subject: [PATCH 10/33] fix(native): deduplicate equivalent Dockerfile paths --- src/backends/native-project-builds.ts | 26 +++++++++++++++++++++++--- tests/native-project-builds.test.ts | 6 +++++- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/src/backends/native-project-builds.ts b/src/backends/native-project-builds.ts index 94dde50c9..ee9d70f81 100644 --- a/src/backends/native-project-builds.ts +++ b/src/backends/native-project-builds.ts @@ -1,6 +1,14 @@ import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; +import { + dirname, + isAbsolute, + join, + posix, + relative, + resolve, + sep, +} from "node:path"; import { childEnvironment } from "../lib/child-environment.ts"; import { ClosedCliError, HackCliError } from "../lib/cli-result.ts"; import { isRecord } from "../lib/guards.ts"; @@ -35,6 +43,7 @@ import { const IMAGE_ID = /^sha256:[a-f0-9]{64}$/; const BUILD_KEY = /^[a-f0-9]{64}$/; const ARGUMENT = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/; +const TRAILING_SLASH = /\/$/; const TARGET = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/; /** * The Compose `build` fields native builds implement. The Compose-backend feature @@ -740,9 +749,20 @@ type PendingBuild = { request: NativeBuildRequest; services: string[] }; /** The declaration a build request stands for: identical ones build once. */ export function nativeBuildIdentity(request: NativeBuildRequest): string { + const { context, dockerfile } = request; + // Match the runtime's lexical source resolution for valid relative paths. + // Keep the authored path in the request so the runtime still validates it. + const keyPath = + dockerfile.length > 0 && + !posix.isAbsolute(dockerfile) && + !dockerfile.includes("$") && + !dockerfile.includes("~") && + !dockerfile.includes("\0") + ? [posix.join(context, dockerfile).replace(TRAILING_SLASH, "")] + : [dockerfile, "invalid"]; return JSON.stringify([ - request.context, - request.dockerfile, + context, + keyPath, request.target, Object.entries(request.args).sort(([a], [b]) => (a < b ? -1 : 1)), ]); diff --git a/tests/native-project-builds.test.ts b/tests/native-project-builds.test.ts index 52bb2b4af..627c51952 100644 --- a/tests/native-project-builds.test.ts +++ b/tests/native-project-builds.test.ts @@ -812,7 +812,11 @@ test.each([ const builds = new Map( names.map((target) => [target, { ...request(), target }]) ); - builds.set("duplicate", { ...request(), target: "web" }); + builds.set("duplicate", { + ...request(), + dockerfile: "./Dockerfile", + target: "web", + }); const specs: Record> = Object.fromEntries( [...builds.keys()].map((name) => [name, { build: "app" }]) ); From 15b888d1f72204c91d9303ce395d0098b4754495 Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:48:08 +0000 Subject: [PATCH 11/33] docs: add rendered native build batch chart --- .../tla/native-build-batch/build-batch.mmd | 2 +- .../tla/native-build-batch/build-batch.png | Bin 0 -> 59834 bytes .../tla/native-build-batch/build-batch.svg | 86 ++++++++++++++---- 3 files changed, 67 insertions(+), 21 deletions(-) create mode 100644 tests/models/tla/native-build-batch/build-batch.png diff --git a/tests/models/tla/native-build-batch/build-batch.mmd b/tests/models/tla/native-build-batch/build-batch.mmd index e098c0c16..9868018c0 100644 --- a/tests/models/tla/native-build-batch/build-batch.mmd +++ b/tests/models/tla/native-build-batch/build-batch.mmd @@ -6,5 +6,5 @@ stateDiagram-v2 Dispatch --> Dispatch: Slot available Dispatch --> Drain: Failure or Ctrl-C Dispatch --> Done: All succeeded and settled - Drain --> Done: All started builds settled + Drain --> Done: All builds settled Done --> [*] diff --git a/tests/models/tla/native-build-batch/build-batch.png b/tests/models/tla/native-build-batch/build-batch.png new file mode 100644 index 0000000000000000000000000000000000000000..daed07b4e7c8e2f4c0c65cdfbdff0ab797454490 GIT binary patch literal 59834 zcmeEu^;cA3+wLd=3Ia-pfQWQSOCum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I`+fOR-!Bv!GdQXWDO?dI3vVUpJ5k5egNQ zaam4Oyniw;)2ZZqU+n~^*r~U|($aF^w+LtUMbqOiv#JcB^IX2pXI@%+b81QBlfhMQ z3~E;Z!^1sZO~$>G`gad*UDk2r_^V8)U`D$J@I^sv8(spZnaSV?+xK3t(y z89j=Z@7MNVp;{TaWlqD(u~tUv928uEXzX@C&z~gLXwZgrI z`wy*)d*8~ygWX#W;hzT(Nn1-R1TyqAq|=1aMiH1s8ynN9vQm*N$<|B!PKEB0YvkPE z`j?H38}-9S3iAg|UoFI zn-wI;6lgEtJxmt;QZ0b~QMAC|M62uT^PyBj*t}e<*fm>Rf(n2#aHgh&aKayyWnY}w z1v?GoBoOXgz~UC4C)ncq)L=1*p|wpHoKxF| - Build batch: dispatch, cancel and settle - - - - - - - - - - - - Dispatch in orderAt most three live - Abort siblingsKeep first outcome - ReturnNo builds live - Fail or Ctrl-CAll settled - All queued builds succeeded and settled - - +Slot availableFailure or Ctrl-CAll succeeded and settledAll builds settledDispatch in authored orderAbort siblings, keep firstoutcomeReturn with no live builds \ No newline at end of file From 3c452ae2f40b42f3ede7f0b821f0d4c1c7dd1db0 Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:01:38 +0000 Subject: [PATCH 12/33] fix(native): build from verified local base images --- docs/guides/native-candidate.md | 13 +- docs/reference/v5-model-coverage.md | 2 + packages/runtime-core/src/main.rs | 12 + .../runtime-core/src/provider/build_policy.rs | 27 ++ .../runtime-core/src/provider/image_build.rs | 284 +++++++++++++++--- .../src/provider/image_build/aliases.rs | 239 +++++++++++++++ .../src/provider/image_build/reclaim.rs | 7 + .../src/provider/image_build/tests.rs | 117 ++++++++ .../src/provider/registry_image.rs | 53 +++- .../src/provider/registry_image_test.rs | 33 ++ scripts/lib/tla-runtime-models.ts | 24 ++ src/backends/native-image-tags.ts | 39 ++- src/backends/native-project-builds.ts | 129 +++++++- tests/models/tla/README.md | 13 + .../tla/native-build-alias/BuildAlias.tla | 38 +++ .../tla/native-build-alias/negative.cfg | 4 + .../tla/native-build-alias/positive.cfg | 4 + .../tla/native-build-alias/unsafe-remote.cfg | 4 + .../tla/native-build-alias/unsafe-sweep.cfg | 4 + 19 files changed, 972 insertions(+), 74 deletions(-) create mode 100644 packages/runtime-core/src/provider/image_build/aliases.rs create mode 100644 tests/models/tla/native-build-alias/BuildAlias.tla create mode 100644 tests/models/tla/native-build-alias/negative.cfg create mode 100644 tests/models/tla/native-build-alias/positive.cfg create mode 100644 tests/models/tla/native-build-alias/unsafe-remote.cfg create mode 100644 tests/models/tla/native-build-alias/unsafe-sweep.cfg diff --git a/docs/guides/native-candidate.md b/docs/guides/native-candidate.md index 1c98cd0cc..fa2d7cb27 100644 --- a/docs/guides/native-candidate.md +++ b/docs/guides/native-candidate.md @@ -1495,11 +1495,14 @@ JSON file (a singly linked, mode-`0600` file owned by you): the resolved base references that the receipt and the result report. Never pass a secret as a build argument. BuildKit build secrets are the right mechanism for secrets; native builds do not support them yet. -- Every build runs under a BuildKit source policy: only the pinned base images - resolve as images, and network sources (`ADD` of an `http`, `https` or git URL, and - image blob sources) are denied. The engine would otherwise fetch those from outside - the isolated build network. The policy also covers sources that a base image's - stored `ONBUILD` triggers add; such bases refuse before the build anyway. +- A fresh recorded base resolution whose verified image is in the guest makes + no registry request. An expired resolution checks the registry and can use the + proven loaded base if the registry is unavailable. `hack pull` refreshes build + bases as well as service images. The build key includes each base digest. +- BuildKit receives only attempt-owned local references to the verified bases. + The source policy denies other image sources and remote `ADD`, git and image + blob sources. A private cache tag keeps the base while attempt aliases are + removed, including on recovery after an interrupted build. - Argument values reach the client only through a private definition file (mode `0600`, removed after the build), never its command line or its environment; the client's environment is a fixed list of its own settings. Names must be plain diff --git a/docs/reference/v5-model-coverage.md b/docs/reference/v5-model-coverage.md index 70c918ac5..c1a242a57 100644 --- a/docs/reference/v5-model-coverage.md +++ b/docs/reference/v5-model-coverage.md @@ -76,6 +76,7 @@ must be attached to the eventual exact integration revision. | One pool, many project roots: share-set changes, boot mounts, per-project share selection, removal of a referenced share | multi-root-share | `provider::share_update` (journaled stopped-pool add/remove, record before owner), `project_share::{check_request, check_boot, validate_set}`, `OwnedGuest::project_share_for`; `share_update` and `project_share` unit tests | Real provider boot with an updated mount record, virtio-fs device limits and live multi-project graphs on a host VM. Cross-project cleanup is abstracted to one run's own resources. | | Cached image presence before archive reads | [native-image-presence](../../tests/models/tla/native-image-presence/COVERAGE.md) | `image_load::load_waiting` requires live exact image and platform readback for receipt reuse and verifies the archive on any upload path. Explicit archive loads retain their early hash. | One request, one archive, one lease, one boot. Expiry and registry availability may change before tag selection. Guest eviction may precede readback or create. Guest ownership, filesystem behavior, interrupted imports and performance require separate runtime evidence. | | Native image builds: unleased build versus engine stop, crash mid-build, storage recreation, foreign or forged images, reclamation versus retained graph references | native-build-retention | `provider::image_build` (shared build fence, per-key lock, incarnation/boot/engine recheck and label check at adoption, dead-attempt recording) and `image_build::reclaim` (owned labels, current receipts, retained graph state scan, engine non-force removal); `image_build` regressions | One key and namespace. Since key version 2 (HACK-2533) every edited build context makes a new key with its own receipt; reclamation keeps, per build declaration, the current and one previous key's image, plus every image retained state (except its diagnostic restore history, HACK-2554) or a container references and every receipt without a declaration, and an `up` that built runs it best-effort after readiness (`image_build::tests::ten_edits_of_one_build_leave_its_current_and_previous_images`); the model's retained-reference safety is unchanged, and which receipt is current is regression-tested, not modeled. Snapshots of a dead owner are removed at the next build in the namespace, only after the owner is proven gone and under that key's lock (`snapshots_of_dead_owners_are_removed_at_the_next_build_of_any_key`). Which inputs a key covers (context walk, ignore rules, hard-link groups, stat cache) and restore's per-up build decision are regression-tested in `image_build::context` and `image_build` and in `tests/native-project-builds.test.ts`, not modeled. A build client orphaned by a killed `hack-native` is not modeled (the client inherits the build fence and per-key lock, so both stay held until it exits: `image_build::tests::a_killed_coordinator_leaves_its_client_fenced`); real BuildKit, engine removal semantics and guest storage are host evidence. | +| Native build-base alias lifetime | native-build-alias | `image_build::aliases` journals before publishing, keeps a cache reference, and sweeps only while holding the attempt key lock; tests exercise the live lock and stranded journal. | One base and one attempt. The verified pin and per-attempt name are enforced in Rust. The model abstracts registry transport and Docker's image deletion behavior. | | Runtime service per native home (HACK-2460, design): start race, crash at any step, version skew and drain, lost replies, resends on new connections, one-shot fallback, inspection of started but unfinished work | runtime-service | Process half implemented as a library; nothing starts or calls it yet. `TakeLock`, `LoseRace` and `Bind` map to `service::start` (a lock on the private `run/service/` directory, then `service.lock`, each checked against its path and held for the process's whole life, drain included; an existing socket is probed and kept if anything answers). `IdleExit`, `Retire`, `RefuseDraining` and `ExitDrained` map to `run`, `refuse_queued` and `shut_down`, with `settle` releasing ownership only after a complete drain. The tests in `packages/runtime-core/src/service/tests.rs` walk each action (concurrent starts, lock replacement while serving and while draining, stale and live sockets, idle exit with a held session, retire, connections queued at shutdown, drain timeout). `Crash` gets its real-process SIGKILL test in the next slice. Intent records, admission of mutations, skew, fallback and inspection are not implemented; each later slice adds the regression that walks its actions, behind `HACK_RUNTIME_SERVICE` (default `off`) | Not modelled, covered by regression tests instead: a lock held for a moment after its owner let go, because a forked child shares the open file description until it runs `exec` (the starter's bounded retry window, `service/tests.rs`); the time bound on that window; a drain that runs out of time ending the process at once with exit code 3; a signal (TERM, INT, HUP) draining like retire; and a starter that never reads the notify line (`tests/runtime_service_contract.rs`, `tests/runtime_service_hooks.rs`). The model treats a release as immediate and every drain as finishing. Implemented slice assumes the `run/service/` directory itself is not replaced (replacing `service.lock` is covered) and that the process exits after a drain that ran out of its 10 s bound; it refuses, never serves, connections queued at stop. Assumption each mutation slice must meet: its inspector distinguishes proven absence from missing evidence (for example work a provider accepted but has not yet made visible), and missing evidence yields "unknown", never "not done"; the model makes dispatched work visible at once. Liveness, several leases, cancellation of joined attempts, event cursors, dashboard authentication, the idle-exit queue race and intent-write durability are not modelled. | | MCP cold start, cancellation and duplicate launches | mcp-startup, mcp-startup-cancellation | Shared MCP bundle identity, startup deduplication and cancellation regressions | Fresh supported client sessions, full workflow coverage and measured overhead (WU16/WU20/WU28). | | Software install/upgrade/rollback, active launcher versus selection, compatibility | **Coverage gap:** no maintained model here is an installer/selection refinement | `scripts/installer/channel.ts`, `src/lib/release-install.ts`, `tests/v4-upgrade.test.ts`, `tests/upgrade-installer.test.ts`, Python-free installer/download tests, candidate-install contract | Historical-byte compiled-CLI cases cover key-present/lost v4 homes, real Git/worktrees, consent, migration, resolution, retirement and sentinel-free output. Four injected publication faults cover stable caught-error rollback; transfer fixtures cover retry, deadlines and uncertain cancellation. No power-loss atomicity, hostile external writer, published artifact or real native runtime proof. Add a bounded selection/lock/crash/compatibility model before primary-driver promotion. | @@ -150,6 +151,7 @@ liveness/reachability controls have their own documented assumptions. | [native-pool-stop](../../tests/models/tla/native-pool-stop/PoolStop.tla) | 210 | 10 | | [start-graph](../../tests/models/tla/start-graph/COVERAGE.md) | 1,656,372 + 81,534 two-boot | 10 | | [probe-readiness](../../tests/models/tla/probe-readiness/ProbeReadiness.tla) | 175,757 | 7 | +| [native-build-alias](../../tests/models/tla/native-build-alias/BuildAlias.tla) | 9 | 4 | | [native-build-retention](../../tests/models/tla/native-build-retention/BuildRetention.tla) | 6,181 | 4 | | [runtime-service](../../tests/models/tla/runtime-service/RuntimeService.tla) | 1,006,849 | 11 | | [shared-helper-instance](../../tests/models/tla/shared-helper-instance/Instance.tla) | 7,649 | 11 | diff --git a/packages/runtime-core/src/main.rs b/packages/runtime-core/src/main.rs index cc8162d5f..f541647b4 100644 --- a/packages/runtime-core/src/main.rs +++ b/packages/runtime-core/src/main.rs @@ -1301,6 +1301,18 @@ fn run() -> Result<(), CandidateError> { references, )?)?; } + [ + "runtime", + "build-image", + "--request", + request, + "--bases", + "--json", + ] => { + print_json(&hack_runtime_core::provider::image_build::build_bases( + Path::new(request), + )?)?; + } ["runtime", "build-image", "--request", request, "--json"] => { // Build output streams to stderr; only the result is printed on stdout. print_json(&hack_runtime_core::provider::image_build::build_image( diff --git a/packages/runtime-core/src/provider/build_policy.rs b/packages/runtime-core/src/provider/build_policy.rs index e2a37aa7f..37300aca6 100644 --- a/packages/runtime-core/src/provider/build_policy.rs +++ b/packages/runtime-core/src/provider/build_policy.rs @@ -52,8 +52,35 @@ fn rule(action: &str, identifier: String, match_type: &str) -> Value { /// reference pinned by digest; it is normalized the way BuildKit's `llb.Image` /// normalizes it, so the allow rule equals the source identifier exactly. pub fn document<'a>(pinned: impl IntoIterator) -> Result { + document_for(pinned, false) +} + +pub(super) fn build_document<'a>( + sources: impl IntoIterator, +) -> Result { + let sources: Vec<_> = sources.into_iter().collect(); + let aliases = sources + .iter() + .any(|source| super::image_build::aliases::allowed(source)); + document_for(sources, aliases) +} + +fn document_for<'a>( + pinned: impl IntoIterator, + aliases: bool, +) -> Result { let mut allowed = BTreeSet::new(); for reference in pinned { + if aliases { + if !super::image_build::aliases::allowed(reference) { + return Err(CandidateError::new( + "native_build_base_image", + "BuildKit requires an owned local base alias.", + )); + } + allowed.insert(format!("docker-image://{reference}")); + continue; + } match normalize(reference) { Ok(ImageReference::Named(named)) if named.digest.is_some() && named.docker_hub_repository().is_some() => diff --git a/packages/runtime-core/src/provider/image_build.rs b/packages/runtime-core/src/provider/image_build.rs index 0084eafa3..0aea54b68 100644 --- a/packages/runtime-core/src/provider/image_build.rs +++ b/packages/runtime-core/src/provider/image_build.rs @@ -27,9 +27,9 @@ //! image, so no context case remains in which the image holds bytes other than the //! keyed ones; a reused image's key misses only what the stat cache can miss (see //! [`context`]). Base images are pinned by digest. -//! - Every image the Dockerfile can pull (see [`super::build_scan`]) resolves to a digest -//! before BuildKit runs and is handed to it as a named build context, so BuildKit pulls -//! only those exact manifests. Base images with stored `ONBUILD` triggers refuse. +//! - Resolve each base to a verified digest and a loaded config ID before output reuse. +//! The build key includes those pins. BuildKit sees only attempt-owned local contexts. +//! Base images with stored `ONBUILD` triggers refuse. //! - The provider lease is held only for short admission and adoption steps, never while //! BuildKit runs. A shared build fence (`run/image-builds/active.lock`), taken under the //! lease and held for the whole operation, makes `runtime down` refuse instead of @@ -82,6 +82,7 @@ use std::{ time::{Duration, Instant, SystemTime}, }; +pub(super) mod aliases; mod client_relay; mod context; mod output; @@ -152,7 +153,7 @@ fn image_id(value: &str) -> bool { pub enum Policy { /// Reuse a verified image for this build key; build only when it is missing. Missing, - /// Always build (BuildKit's cache keeps unchanged steps cheap) and re-resolve bases. + /// Always run BuildKit. Base selections still use their ordinary freshness policy. Rebuild, } @@ -180,6 +181,10 @@ pub struct BuildRequest { pub policy: Policy, #[serde(default)] pub timeout_seconds: Option, + #[serde(default)] + pub image_tag_ttl_seconds: Option, + #[serde(default)] + pub command_base_pins: BTreeMap, } fn default_dockerfile() -> String { "Dockerfile".into() @@ -195,6 +200,10 @@ pub struct BuildOutcome { pub reused: bool, /// Named build context to the pinned reference it resolved to, for this image. pub base_pins: BTreeMap, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub base_fallbacks: Vec, + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub base_selections: BTreeMap, /// Build cache bytes the post-build prune reclaimed; `None` when no prune ran or /// it failed (the build result stands either way). #[serde(skip_serializing_if = "Option::is_none")] @@ -266,6 +275,12 @@ pub(super) trait BuildPool { deadline: Instant, canceled: &dyn Fn() -> bool, ) -> Result; + fn tag_base(&self, _: &Self::Lease, _: &str, _: &str) -> Result<(), CandidateError> { + unreachable!("only live builds use aliases") + } + fn untag_base(&self, _: &Self::Lease, _: &str) -> Result<(), CandidateError> { + unreachable!("only live builds use aliases") + } /// The verified builder executable. fn builder(&self) -> Result; /// Where the client's filtered output goes. @@ -523,12 +538,17 @@ impl IgnoreFiles { } } -/// Validate the request, resolve paths inside the project without following symlinks, -/// read and scan the Dockerfile, hash the build context and derive the build key. -/// Local reads only, apart from the context stat cache under `builds` (the -/// `run/image-builds` state directory), which is best effort. -pub(super) fn prepare(request: BuildRequest, builds: &Path) -> Result { - validate_request(&request)?; +struct Scanned { + root: PathBuf, + context: PathBuf, + dockerfile: PathBuf, + project: context::ProjectRoot, + bytes: Vec, + scan: build_scan::DockerfileScan, +} + +fn scan_request(request: &BuildRequest) -> Result { + validate_request(request)?; let root = fs::canonicalize(&request.project_root).map_err(|_| { refusal( "native_build_source", @@ -564,6 +584,37 @@ pub(super) fn prepare(request: BuildRequest, builds: &Path) -> Result Result, CandidateError> { + let request: BuildRequest = state::read_bounded(request, MAX_REQUEST_BYTES)?; + Ok(scan_request(&request)? + .scan + .images + .into_iter() + .map(|base| base.reference.canonical()) + .collect()) +} + +/// Validate and fingerprint the complete build input without network access. +pub(super) fn prepare(request: BuildRequest, builds: &Path) -> Result { + let Scanned { + root, + context, + dockerfile, + project, + bytes, + scan, + } = scan_request(&request)?; let namespace = namespace(&root, request.branch.as_deref()); let relative = |path: &Path, base: &Path| -> String { path.strip_prefix(base) @@ -774,13 +825,31 @@ fn owned_image( /// `canceled` reports a pending cancellation request; it is checked before each /// unleased step, during base resolution and while the client runs. The time budget /// starts here: base resolution and the client share it. +#[cfg(test)] pub(super) fn run( candidate: &Candidate, pool: &P, inputs: &Inputs, canceled: &dyn Fn() -> bool, ) -> Result { - let deadline = Instant::now() + inputs.timeout; + run_with_bases( + candidate, + pool, + inputs, + canceled, + None, + Instant::now() + inputs.timeout, + ) +} + +fn run_with_bases( + candidate: &Candidate, + pool: &P, + inputs: &Inputs, + canceled: &dyn Fn() -> bool, + selected: Option<&BTreeMap>, + deadline: Instant, +) -> Result { let canceled_early = || { refusal( "native_build_canceled", @@ -825,6 +894,11 @@ pub(super) fn run( Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => return Err(state::io(error)), } + let alias_path = directory.join(format!("{}.client/base-aliases.json", inputs.key)); + if selected.is_some() { + aliases::sweep_stranded(&root, pool, &lease, &identity, &alias_path); + aliases::sweep(pool, &lease, &identity, &alias_path)?; + } let expected = labels(inputs, &identity); let previous = read_receipt(&receipt_path)?; if let Some(previous) = &previous { @@ -867,33 +941,41 @@ pub(super) fn run( remove_stranded_snapshots(&directory); // Step 2, unleased: resolve every base image to a pinned manifest. - let mut pins = BTreeMap::new(); - for base in &inputs.images { - if canceled() { - return Err(canceled_early()); - } - if Instant::now() >= deadline { - return Err(expired_early()); - } - let resolved = pool.resolve(base, deadline, canceled).map_err(|error| { - if error.code.starts_with("registry_") && error.cause_code.is_some() { - error.with_build_base_reference(base.reference.canonical()) - } else { - error + let pins = if let Some(selected) = selected { + selected + .iter() + .map(|(name, base)| (name.clone(), base.pinned_reference.clone())) + .collect() + } else { + let mut pins = BTreeMap::new(); + for base in &inputs.images { + if canceled() { + return Err(canceled_early()); } - })?; - if !image_id(&resolved.source_digest) - || !resolved - .pinned_reference - .ends_with(&format!("@{}", resolved.source_digest)) - { - return Err(refusal( - "native_build_base_image", - "A build base image did not resolve to a pinned manifest.", - )); + if Instant::now() >= deadline { + return Err(expired_early()); + } + let resolved = pool.resolve(base, deadline, canceled).map_err(|error| { + if error.code.starts_with("registry_") && error.cause_code.is_some() { + error.with_build_base_reference(base.reference.canonical()) + } else { + error + } + })?; + if !image_id(&resolved.source_digest) + || !resolved + .pinned_reference + .ends_with(&format!("@{}", resolved.source_digest)) + { + return Err(refusal( + "native_build_base_image", + "A build base image did not resolve to a pinned manifest.", + )); + } + pins.insert(base.context_name.clone(), resolved.pinned_reference); } - pins.insert(base.context_name.clone(), resolved.pinned_reference); - } + pins + }; let builder = pool.builder()?; if canceled() { return Err(canceled_early()); @@ -958,6 +1040,13 @@ pub(super) fn run( sequence: previous.as_ref().and_then(|receipt| receipt.sequence), }; state::write(&receipt_path, &receipt)?; + let (aliases, worker_pins) = if let Some(bases) = selected { + let (aliases, contexts) = + aliases::Aliases::prepare(pool, &lease, &identity, alias_path, bases)?; + (Some(aliases), contexts) + } else { + (None, pins.clone()) + }; drop(lease); // Step 4, unleased: run the client in its own process group. @@ -980,7 +1069,7 @@ pub(super) fn run( inputs, &snapshot.context(), relay.socket(), - &pins, + &worker_pins, &expected, )?; inherit_locks(&mut client, &[&fence, &key_lock]); @@ -993,6 +1082,7 @@ pub(super) fn run( ); // The client has exited or was stopped; wait for the guest to end its connections. relay.finish(client_relay::FINISH_GRACE); + drop(aliases); let ended = match ended { Ok(ended) => ended, Err(error) => { @@ -1091,6 +1181,8 @@ pub(super) fn run( tag: inputs.tag(), reused: false, base_pins: pins, + base_fallbacks: Vec::new(), + base_selections: BTreeMap::new(), cache_reclaimed_bytes, }) } @@ -1117,6 +1209,8 @@ fn reused(inputs: &Inputs, id: &str, pins: &BTreeMap) -> BuildOu tag: inputs.tag(), reused: true, base_pins: pins.clone(), + base_fallbacks: Vec::new(), + base_selections: BTreeMap::new(), cache_reclaimed_bytes: None, } } @@ -1357,9 +1451,10 @@ fn command( // The policy allows exactly the pinned references the definition names as // contexts, and denies every other image and network source. let policy = bake.join(SOURCE_POLICY); - let policy_bytes = - serde_json::to_vec(&build_policy::document(pins.values().map(String::as_str))?) - .map_err(|_| invalid("Cannot encode the build source policy."))?; + let policy_bytes = serde_json::to_vec(&build_policy::build_document( + pins.values().map(String::as_str), + )?) + .map_err(|_| invalid("Cannot encode the build source policy."))?; write_private(&policy, &policy_bytes)?; let mut command = super::process::clean_command(builder); command @@ -1639,6 +1734,28 @@ impl<'a> BuildPool for LivePool<'a> { canceled, ) } + fn tag_base( + &self, + lease: &Self::Lease, + id: &str, + reference: &str, + ) -> Result<(), CandidateError> { + let (repo, tag) = reference.rsplit_once(':').expect("generated alias"); + lease.request( + reqwest::Method::POST, + &format!("/v1.53/images/{id}/tag?repo={repo}&tag={tag}"), + None, + )?; + Ok(()) + } + fn untag_base(&self, lease: &Self::Lease, reference: &str) -> Result<(), CandidateError> { + lease.request( + reqwest::Method::DELETE, + &format!("/v1.53/images/{reference}?force=false&noprune=true"), + None, + )?; + Ok(()) + } fn builder(&self) -> Result { artifact::verify_builder(self.candidate)?; Ok(artifact::builder_executable(self.candidate)) @@ -1733,12 +1850,91 @@ fn interruptible( } } +fn key_with_bases( + key: &str, + selected: &BTreeMap, +) -> Result { + if selected.is_empty() { + return Ok(key.into()); + } + let pins: BTreeMap<_, _> = selected + .iter() + .map(|(name, base)| (name, &base.pinned_reference)) + .collect(); + serde_json::to_vec(&(key, pins)) + .map(|encoded| sha256_hex(&encoded)) + .map_err(|_| invalid("Cannot encode the build key.")) +} + /// `runtime build-image --request `: build or reuse one native image. pub fn build_image(candidate: &Candidate, request: &Path) -> Result { let request: BuildRequest = state::read_bounded(request, MAX_REQUEST_BYTES)?; - let inputs = prepare(request, &builds_root(candidate))?; + let mut policy = super::image_policy::ImagePolicy::default(); + if let Some(ttl) = request.image_tag_ttl_seconds { + if ttl > 2_592_000 { + return Err(invalid("Image tag lifetime exceeds thirty days.")); + } + policy.tag_ttl_seconds = ttl; + } + let prior_pins = request.command_base_pins.clone(); + let mut inputs = prepare(request, &builds_root(candidate))?; let _signals = CancelSignals::install()?; - run(candidate, &LivePool { candidate }, &inputs, &|| { - CANCEL_REQUESTED.load(Ordering::Acquire) - }) + let canceled = || CANCEL_REQUESTED.load(Ordering::Acquire); + let deadline = Instant::now() + inputs.timeout; + let pool = LivePool { candidate }; + let (lease, _) = pool.lease()?; + drop(lease); + let mut selected = BTreeMap::new(); + let mut fallbacks = Vec::new(); + let mut selections = BTreeMap::new(); + for base in &inputs.images { + if canceled() || Instant::now() >= deadline { + return Err(late_stop(canceled())); + } + let reference = base.reference.canonical(); + policy.command_image_pin = prior_pins + .get(&reference) + .map(|pin| registry_image::pinned_syntax(pin).map(|(canonical, _)| canonical)) + .transpose()?; + let ensured = super::image_ensure::ensure(candidate, &reference, &policy) + .map_err(|error| error.with_build_base_reference(reference.clone()))?; + let proof = super::image_ensure::recorded_proof( + candidate, + &ensured.pinned_reference, + super::image_platform::PlatformPolicy::Native, + )? + .ok_or_else(|| { + refusal( + "native_build_base_image", + "The verified base proof is missing.", + ) + })?; + let resolved = + proof.verified_build_base(&ensured.pinned_reference, policy.archive_limit)?; + if resolved.image_id != ensured.image_id { + return Err(refusal( + "native_build_base_image", + "The build base proof differs from the loaded image.", + )); + } + if let Some(tag) = ensured.tag_resolution + && tag.source == super::image_tag_store::TagSource::Offline + { + fallbacks.push(tag); + } + selections.insert(reference, resolved.pinned_reference.clone()); + selected.insert(base.context_name.clone(), resolved); + } + inputs.key = key_with_bases(&inputs.key, &selected)?; + let mut outcome = run_with_bases( + candidate, + &pool, + &inputs, + &canceled, + Some(&selected), + deadline, + )?; + outcome.base_fallbacks = fallbacks; + outcome.base_selections = selections; + Ok(outcome) } diff --git a/packages/runtime-core/src/provider/image_build/aliases.rs b/packages/runtime-core/src/provider/image_build/aliases.rs new file mode 100644 index 000000000..b48066a8a --- /dev/null +++ b/packages/runtime-core/src/provider/image_build/aliases.rs @@ -0,0 +1,239 @@ +//! Attempt-owned aliases for the classic worker's prefer-local lookup. +use super::*; + +pub(super) const DOMAIN: &str = "127.0.0.1:1"; +const ATTEMPT: &str = "hack-build-attempt"; +const CACHE: &str = "hack-build-cache"; + +fn parse(reference: &str) -> Option<(&str, &str)> { + let value = reference.strip_prefix("127.0.0.1:1/hack-build-attempt/")?; + let (namespace, key) = value.split_once('/')?; + let (key, nonce) = key.split_once(':')?; + (hex64(namespace) + && hex64(key) + && nonce.len() == 32 + && nonce + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))) + .then_some((namespace, key)) +} + +pub(in crate::provider) fn allowed(reference: &str) -> bool { + parse(reference).is_some() +} + +fn scope(path: &Path) -> Option<(&str, &str)> { + let scratch = path.parent()?; + let key = scratch.file_name()?.to_str()?.strip_suffix(".client")?; + let namespace = scratch.parent()?.file_name()?.to_str()?; + (hex64(namespace) && hex64(key)).then_some((namespace, key)) +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Journal { + incarnation: String, + engine_id: String, + aliases: BTreeMap, +} + +fn tag( + pool: &P, + lease: &P::Lease, + id: &str, + reference: &str, +) -> Result<(), CandidateError> { + if let Some(image) = pool.inspect(lease, reference)? { + if image["Id"] == id { + return Ok(()); + } + return Err(refusal( + "native_build_base_image", + "A private base alias differs from the verified image.", + )); + } + pool.tag_base(lease, id, reference)?; + if pool + .inspect(lease, reference)? + .is_some_and(|image| image["Id"] == id) + { + Ok(()) + } else { + Err(refusal( + "native_build_base_image", + "The worker base alias could not be verified.", + )) + } +} + +pub(super) struct Aliases<'a, P: BuildPool> { + pool: &'a P, + path: PathBuf, +} + +impl<'a, P: BuildPool> Aliases<'a, P> { + pub(super) fn prepare( + pool: &'a P, + lease: &P::Lease, + identity: &PoolIdentity, + path: PathBuf, + bases: &BTreeMap, + ) -> Result<(Self, BTreeMap), CandidateError> { + let (namespace, key) = scope(&path) + .ok_or_else(|| refusal("native_build_receipt", "The build alias path is invalid."))?; + let mut journal = Journal { + incarnation: identity.incarnation.clone(), + engine_id: identity.engine_id.clone(), + aliases: BTreeMap::new(), + }; + let mut contexts = BTreeMap::new(); + for (context, base) in bases { + let mut nonce = [0u8; 16]; + File::open("/dev/urandom") + .and_then(|mut file| file.read_exact(&mut nonce)) + .map_err(state::io)?; + let alias = format!( + "{DOMAIN}/{ATTEMPT}/{namespace}/{key}:{:x}", + crate::Hex(nonce) + ); + if pool.inspect(lease, &alias)?.is_some() { + return Err(refusal( + "native_build_base_image", + "An attempt base alias already exists.", + )); + } + let keeper = format!( + "{DOMAIN}/{CACHE}:{}", + base.image_id.trim_start_matches("sha256:") + ); + tag(pool, lease, &base.image_id, &keeper)?; + journal.aliases.insert(alias.clone(), base.image_id.clone()); + contexts.insert(context.clone(), alias); + } + if !journal.aliases.is_empty() { + state::write(&path, &journal)?; + // The journal survives an interrupted tag request and precedes every alias. + for (alias, id) in &journal.aliases { + if let Err(error) = tag(pool, lease, id, alias) { + let _ = sweep(pool, lease, identity, &path); + return Err(error); + } + } + } + Ok((Self { pool, path }, contexts)) + } +} + +impl Drop for Aliases<'_, P> { + fn drop(&mut self) { + if self.path.exists() + && let Ok((lease, identity)) = self.pool.lease() + { + let _ = sweep(self.pool, &lease, &identity, &self.path); + } + } +} + +pub(super) fn sweep( + pool: &P, + lease: &P::Lease, + identity: &PoolIdentity, + path: &Path, +) -> Result<(), CandidateError> { + crate::reject_aliased_state(path.parent().expect("journal parent"))?; + let pending = path.with_extension("pending"); + match fs::symlink_metadata(&pending) { + Ok(metadata) + if metadata.is_file() + && metadata.nlink() == 1 + && metadata.uid() == unsafe { libc::geteuid() } + && metadata.mode() & 0o077 == 0 => + { + fs::remove_file(pending).map_err(state::io)?; + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(state::io(error)), + Ok(_) => { + return Err(refusal( + "native_build_receipt", + "The pending build alias journal is unsafe.", + )); + } + } + if !path.try_exists().map_err(state::io)? { + return Ok(()); + } + let journal: Journal = state::read_bounded(path, MAX_RECEIPT_BYTES)?; + if journal.incarnation == identity.incarnation && journal.engine_id == identity.engine_id { + for (alias, id) in journal.aliases { + if parse(&alias) != scope(path) || !image_id(&id) { + return Err(refusal( + "native_build_receipt", + "The recorded build alias is invalid.", + )); + } + if let Some(image) = pool.inspect(lease, &alias)? { + let keeper = format!("{DOMAIN}/{CACHE}:{}", id.trim_start_matches("sha256:")); + if image["Id"] != id + || pool + .inspect(lease, &keeper)? + .is_none_or(|image| image["Id"] != id) + { + return Err(refusal( + "native_build_receipt", + "The recorded build alias or its cache tag differs.", + )); + } + pool.untag_base(lease, &alias)?; + } + } + } + fs::remove_file(path).map_err(state::io) +} + +/// Sweep only attempt journals whose key lock is free, including other projects. +pub(super) fn sweep_stranded( + root: &Path, + pool: &P, + lease: &P::Lease, + identity: &PoolIdentity, + current: &Path, +) { + let Ok(namespaces) = fs::read_dir(root) else { + return; + }; + for ns in namespaces.filter_map(Result::ok) { + if !ns.file_name().to_str().is_some_and(hex64) + || !ns.file_type().is_ok_and(|kind| kind.is_dir()) + { + continue; + } + let directory = ns.path(); + let Ok(entries) = fs::read_dir(&directory) else { + continue; + }; + for entry in entries.filter_map(Result::ok) { + let name = entry.file_name(); + let Some(key) = name + .to_str() + .and_then(|name| name.strip_suffix(".client")) + .filter(|key| hex64(key)) + else { + continue; + }; + let path = entry.path().join("base-aliases.json"); + if path == current + || !entry.file_type().is_ok_and(|kind| kind.is_dir()) + || (!path.is_file() && !path.with_extension("pending").is_file()) + { + continue; + } + let lock = directory.join(format!("{key}.lock")); + if let Ok(Some(_held)) = + Flock::open(&lock).and_then(|lock| Flock::try_lock(lock, libc::LOCK_EX)) + { + let _ = sweep(pool, lease, identity, &path); + } + } + } +} diff --git a/packages/runtime-core/src/provider/image_build/reclaim.rs b/packages/runtime-core/src/provider/image_build/reclaim.rs index 70f876314..8de47adf5 100644 --- a/packages/runtime-core/src/provider/image_build/reclaim.rs +++ b/packages/runtime-core/src/provider/image_build/reclaim.rs @@ -337,6 +337,13 @@ pub(super) fn run( ) -> Result { let (lease, identity) = pool.lease()?; require_no_active_build(candidate)?; + super::aliases::sweep_stranded( + &builds_root(candidate), + pool, + &lease, + &identity, + Path::new(""), + ); // Under the lease no build can start, adopt or write a receipt. let current = current_images(candidate)?; let referenced = referenced_images(candidate)?; diff --git a/packages/runtime-core/src/provider/image_build/tests.rs b/packages/runtime-core/src/provider/image_build/tests.rs index e7ed5efa6..2ea81a620 100644 --- a/packages/runtime-core/src/provider/image_build/tests.rs +++ b/packages/runtime-core/src/provider/image_build/tests.rs @@ -62,6 +62,8 @@ impl Fixture { args: BTreeMap::from([("GREETING".to_owned(), SECRET.to_owned())]), policy, timeout_seconds: Some(30), + image_tag_ttl_seconds: None, + command_base_pins: BTreeMap::new(), } } fn inputs(&self, policy: Policy) -> Inputs { @@ -236,6 +238,19 @@ impl BuildPool for FakePool { image_id: IMAGE.into(), }) } + fn tag_base(&self, _: &(), id: &str, tag: &str) -> Result<(), CandidateError> { + let mut images = self.images.borrow_mut(); + let image = images + .get(id) + .cloned() + .ok_or_else(|| refusal("engine_not_found", "Missing base."))?; + images.insert(tag.into(), image); + Ok(()) + } + fn untag_base(&self, _: &(), tag: &str) -> Result<(), CandidateError> { + self.images.borrow_mut().remove(tag); + Ok(()) + } fn builder(&self) -> Result { if let Some(home) = &self.builder_home { artifact::verify_builder(&Candidate::discover(home)?)?; @@ -1976,3 +1991,105 @@ fn snapshots_of_dead_owners_are_removed_at_the_next_build_of_any_key() { assert!(!fixture.scratch(&inputs).join("snapshot").exists()); assert!(!fixture.scratch(&inputs).join("snapshot.owner").exists()); } + +#[test] +fn a_dead_build_alias_is_swept_only_after_the_worker_releases_its_key() { + let fixture = Fixture::new(); + let pool = FakePool::new("pool-1"); + pool.images + .borrow_mut() + .insert(IMAGE.into(), serde_json::json!({"Id":IMAGE})); + let (_, identity) = pool.lease().unwrap(); + let namespace = fixture.root.join("a".repeat(64)); + let key = "b".repeat(64); + let scratch = namespace.join(format!("{key}.client")); + state::private_directory(&scratch).unwrap(); + let path = scratch.join("base-aliases.json"); + let lock = Flock::try_lock( + Flock::open(&namespace.join(format!("{key}.lock"))).unwrap(), + libc::LOCK_EX, + ) + .unwrap() + .unwrap(); + let bases = BTreeMap::from([( + "fixture".into(), + BuildBase { + pinned_reference: format!("docker.io/library/alpine@{PIN}"), + source_digest: PIN.into(), + image_id: IMAGE.into(), + }, + )]); + let (attempt, references) = + aliases::Aliases::prepare(&pool, &(), &identity, path.clone(), &bases).unwrap(); + let alias = &references["fixture"]; + assert!(aliases::allowed(alias)); + assert!(pool.inspect(&(), alias).unwrap().is_some()); + std::mem::forget(attempt); + aliases::sweep_stranded(&fixture.root, &pool, &(), &identity, Path::new("")); + assert!(pool.inspect(&(), alias).unwrap().is_some()); + drop(lock); + aliases::sweep_stranded(&fixture.root, &pool, &(), &identity, Path::new("")); + assert!(pool.inspect(&(), alias).unwrap().is_none()); + assert!(pool.inspect(&(), IMAGE).unwrap().is_some()); + assert!(!path.exists()); +} + +#[test] +fn a_verified_base_selects_the_build_key_and_only_a_local_worker_source() { + let fixture = Fixture::new(); + let mut inputs = fixture.inputs(Policy::Missing); + let pool = FakePool::new("pool-1"); + let base = BuildBase { + pinned_reference: format!("docker.io/library/alpine@{PIN}"), + source_digest: PIN.into(), + image_id: PIN.into(), + }; + let mut bases = BTreeMap::from([("alpine:3.20".into(), base.clone())]); + let key = key_with_bases(&inputs.key, &bases).unwrap(); + bases.get_mut("alpine:3.20").unwrap().pinned_reference = + format!("docker.io/library/alpine@{IMAGE}"); + assert_ne!(key_with_bases(&inputs.key, &bases).unwrap(), key); + bases.insert("alpine:3.20".into(), base); + inputs.key = key; + fixture.client(&inputs, "ok"); + pool.built(&inputs, "pool-1", serde_json::json!({})); + pool.images + .borrow_mut() + .insert(PIN.into(), serde_json::json!({"Id":PIN})); + let outcome = run_with_bases( + &fixture.candidate, + &pool, + &inputs, + &never, + Some(&bases), + Instant::now() + inputs.timeout, + ) + .unwrap(); + assert_eq!( + outcome.base_pins["alpine:3.20"], + format!("docker.io/library/alpine@{PIN}") + ); + assert!(pool.resolve_deadlines.borrow().is_empty()); + let scratch = fixture.scratch(&inputs); + let bake: Value = + serde_json::from_slice(&fs::read(scratch.join("seen-bake.json")).unwrap()).unwrap(); + let reference = bake["target"]["build"]["contexts"]["alpine:3.20"] + .as_str() + .unwrap(); + let policy: Value = + serde_json::from_slice(&fs::read(scratch.join("seen-policy.json")).unwrap()).unwrap(); + assert_eq!(policy_decision(&policy, reference), "ALLOW"); + assert_eq!( + policy_decision( + &policy, + &format!("docker-image://docker.io/library/alpine@{PIN}") + ), + "DENY" + ); + assert!( + pool.inspect(&(), reference.trim_start_matches("docker-image://")) + .unwrap() + .is_none() + ); + assert!(pool.inspect(&(), PIN).unwrap().is_some()); +} diff --git a/packages/runtime-core/src/provider/registry_image.rs b/packages/runtime-core/src/provider/registry_image.rs index 75f781436..7a2a302d3 100644 --- a/packages/runtime-core/src/provider/registry_image.rs +++ b/packages/runtime-core/src/provider/registry_image.rs @@ -1767,6 +1767,36 @@ impl ManifestProof { pin: &str, policy: PlatformPolicy, ) -> Result<(ImagePlatform, String), CandidateError> { + let (manifest, selected) = self.verified_manifest(pin, policy)?; + Ok((selected, manifest.config.expect("checked manifest").digest)) + } + + pub(super) fn verified_build_base( + &self, + pin: &str, + archive_limit: u64, + ) -> Result { + let (_, source_digest) = pinned_syntax(pin)?; + let (manifest, _) = self.verified_manifest(pin, PlatformPolicy::Native)?; + bounded_build_base(&manifest, pin, archive_limit)?; + if declares_onbuild(self.config.as_bytes())? { + return Err(CandidateError::new( + "native_build_base_image", + "A build base image declares ONBUILD triggers; native builds refuse stored triggers.", + )); + } + Ok(BuildBase { + pinned_reference: pin.into(), + source_digest, + image_id: manifest.config.expect("checked manifest").digest, + }) + } + + fn verified_manifest( + &self, + pin: &str, + policy: PlatformPolicy, + ) -> Result<(Manifest, ImagePlatform), CandidateError> { let (_, expected) = pinned_syntax(pin)?; let initial = parse_manifest(self.initial.as_bytes(), &expected)?; let (manifest, indexed) = if initial.manifests.is_empty() { @@ -1792,11 +1822,12 @@ impl ManifestProof { check_selected_manifest(&manifest)?; let config = manifest .config + .as_ref() .ok_or_else(|| error("Image config descriptor is missing."))?; - Fetch::checked(&config, MAX_METADATA as u64)?; - verify_object(&config, self.config.as_bytes())?; + Fetch::checked(config, MAX_METADATA as u64)?; + verify_object(config, self.config.as_bytes())?; let selected = config_platform(self.config.as_bytes(), policy, indexed)?; - Ok((selected, config.digest)) + Ok((manifest, selected)) } } @@ -2041,7 +2072,7 @@ pub fn resolve_build_base( return Err(error("Registry manifest digest or size mismatch.") .with_cause_code("registry_digest_mismatch".into())); } - let (manifest, _, indexed, _) = + let (manifest, _, _, child) = select(&mut fetch, &initial, &source_digest, PlatformPolicy::Native)?; let pinned_reference = format!("{}/{}@{source_digest}", registry.domain, named.path); // BuildKit pulls the base itself, outside acquisition's archive budget, so the sizes @@ -2051,18 +2082,8 @@ pub fn resolve_build_base( .config .ok_or_else(|| error("Image config descriptor is missing."))?; let config_bytes = fetch.object("blobs", &config)?; - config_platform(&config_bytes, PlatformPolicy::Native, indexed)?; - if declares_onbuild(&config_bytes)? { - return Err(CandidateError::new( - "native_build_base_image", - "A build base image declares ONBUILD triggers; native builds refuse stored triggers.", - )); - } - Ok(BuildBase { - pinned_reference, - source_digest, - image_id: config.digest, - }) + ManifestProof::new(initial, child, config_bytes)? + .verified_build_base(&pinned_reference, policy.archive_limit) } /// Refuse a build base whose manifest declares more than `limit` compressed bytes of diff --git a/packages/runtime-core/src/provider/registry_image_test.rs b/packages/runtime-core/src/provider/registry_image_test.rs index 1ca68acdd..b7471c5ec 100644 --- a/packages/runtime-core/src/provider/registry_image_test.rs +++ b/packages/runtime-core/src/provider/registry_image_test.rs @@ -3,6 +3,39 @@ //! registry opt-in; no test reaches a public registry, the user's Docker configuration, //! a credential store or a runtime. use super::*; + +#[test] +fn build_admission_rechecks_stored_proof_without_the_registry() { + let mut resolved = test_manifest_resolution(); + let (selection, requests) = count_requests(|| { + resolved.proof.verified_build_base( + &resolved.pinned_reference, + ImagePolicy::default().archive_limit, + ) + }); + let selection = selection.unwrap(); + assert_eq!(requests, 0); + assert_eq!(selection.source_digest, resolved.source_digest); + assert_eq!(selection.image_id, resolved.image_id); + assert_eq!( + resolved + .proof + .verified_build_base(&resolved.pinned_reference, 1) + .unwrap_err() + .code, + "native_build_base_image" + ); + resolved.proof.config.push(' '); + assert!( + resolved + .proof + .verified_build_base( + &resolved.pinned_reference, + ImagePolicy::default().archive_limit + ) + .is_err() + ); +} use crate::provider::image_load::tests::{Layer, compress}; use crate::provider::image_policy::LocalRegistry; use crate::provider::registry_credentials::tests::DockerFixture; diff --git a/scripts/lib/tla-runtime-models.ts b/scripts/lib/tla-runtime-models.ts index 35262c990..a36b5be5f 100644 --- a/scripts/lib/tla-runtime-models.ts +++ b/scripts/lib/tla-runtime-models.ts @@ -2809,6 +2809,30 @@ const contracts: readonly ModelContract[] = [ }, ], }, + { + name: "native-build-alias", + module: "BuildAlias", + states: 9, + invariant: "BaseSurvives", + action: "Cleanup", + fields: ["base = FALSE", "alias = FALSE"], + additionalControls: [ + { + name: "unsafe-remote", + negative: true, + invariant: "NoRegistryFallback", + action: "ResolveMissing", + fields: ["wire = TRUE", 'phase = "solving"'], + }, + { + name: "unsafe-sweep", + negative: true, + invariant: "NoLiveSweep", + action: "Cleanup", + fields: ["sweptLive = TRUE", "alias = FALSE"], + }, + ], + }, { name: "native-build-retention", module: "BuildRetention", diff --git a/src/backends/native-image-tags.ts b/src/backends/native-image-tags.ts index 8fcd09ba6..c297ff848 100644 --- a/src/backends/native-image-tags.ts +++ b/src/backends/native-image-tags.ts @@ -9,7 +9,11 @@ import { nativeImageRegistryReason, } from "./native-image-policy.ts"; import { prepareNativeProjectAdaptation } from "./native-project-adaptation.ts"; -import { nativeServiceActive } from "./native-project-builds.ts"; +import { + admitNativeProjectBuilds, + nativeBuildBases, + nativeServiceActive, +} from "./native-project-builds.ts"; import { admitNativeProjectImages } from "./native-project-image-admission.ts"; import { prepareNativeProjectInput, @@ -107,12 +111,33 @@ export async function pullNativeProjectImages(opts: { invoke, }); - for (const [name, spec] of specs) { - if (typeof spec.image !== "string") { - continue; - } - const reference = canonical.get(spec.image) ?? spec.image; - const policy = nativeEmulationPolicy(adapted.amd64Emulation, name); + const builds = admitNativeProjectBuilds({ + services: Object.fromEntries(specs), + projectRoot: opts.project.projectRoot, + composeFile: opts.project.composeFile, + enabled: true, + }); + const bases = await nativeBuildBases({ + projectRoot: opts.project.projectRoot, + runtime: opts.runtime, + builds, + invoke, + }); + const images = specs.flatMap(([name, spec]) => + typeof spec.image === "string" + ? [ + { + image: spec.image, + policy: nativeEmulationPolicy(adapted.amd64Emulation, name), + }, + ] + : [] + ); + for (const base of bases) { + images.push({ image: base, policy: undefined }); + } + for (const { image, policy } of images) { + const reference = canonical.get(image) ?? image; const selection = `${reference}\n${policy ?? "native"}`; if (seen.has(selection)) { continue; diff --git a/src/backends/native-project-builds.ts b/src/backends/native-project-builds.ts index 2c366bb49..ef9fd2cc2 100644 --- a/src/backends/native-project-builds.ts +++ b/src/backends/native-project-builds.ts @@ -4,13 +4,17 @@ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { childEnvironment } from "../lib/child-environment.ts"; import { ClosedCliError, HackCliError } from "../lib/cli-result.ts"; import { isRecord } from "../lib/guards.ts"; +import { reportNativeImageTagOffline } from "../lib/native-detached-up.ts"; import { NATIVE_BUILDER_MISSING, NATIVE_BUILDER_NOT_PREPARED, type NativeBuilderCommandOptions, nativeBuilderRemedy, } from "../lib/native-image-builder.ts"; -import { nativeImageRegistryReason } from "./native-image-policy.ts"; +import { + nativeImageRegistryReason, + nativeImageTagTtlSeconds, +} from "./native-image-policy.ts"; import { type invokeNativeRuntime, NativeRuntimeRequestError, @@ -328,6 +332,8 @@ export interface NativeBuiltImage { readonly imageId: string; readonly buildKey: string; readonly reused: boolean; + readonly baseFallbacks?: readonly string[]; + readonly baseSelections?: Readonly>; } function parseBuilt(value: unknown): NativeBuiltImage { @@ -345,10 +351,46 @@ function parseBuilt(value: unknown): NativeBuiltImage { "Native runtime returned an invalid image build result; values omitted." ); } + const fallbacks = Array.isArray(value.base_fallbacks) + ? value.base_fallbacks.flatMap((entry: unknown) => { + if ( + !( + isRecord(entry) && + typeof entry.reference === "string" && + BUILD_BASE_REFERENCE.test(entry.reference) && + typeof entry.resolved_at_unix_seconds === "number" + ) + ) { + return []; + } + const time = new Date(entry.resolved_at_unix_seconds * 1000); + const reason = + nativeImageRegistryReason(entry.fallback_reason) ?? + "registry refresh failed"; + return Number.isFinite(time.getTime()) + ? [ + `${reason}, using the loaded build base ${entry.reference} resolved ${time.toISOString()}`, + ] + : []; + }) + : []; + const selections = isRecord(value.base_selections) + ? (Object.fromEntries( + Object.entries(value.base_selections).filter( + ([reference, pin]) => + BUILD_BASE_REFERENCE.test(reference) && + typeof pin === "string" && + BUILD_BASE_REFERENCE.test(pin) && + BUILD_BASE_PIN.test(pin) + ) + ) as Record) + : undefined; return { imageId: value.image_id, buildKey: value.build_key, reused: value.reused, + ...(fallbacks.length ? { baseFallbacks: fallbacks } : {}), + ...(selections ? { baseSelections: selections } : {}), }; } @@ -395,6 +437,7 @@ async function forwardBuildOutput( return held; } +const BUILD_BASE_PIN = /@sha256:[a-f0-9]{64}$/; const BUILD_BASE_REFERENCE = /^[A-Za-z0-9._:/@-]{1,512}$/; export class NativeBuildRegistryError extends NativeRuntimeRequestError { @@ -425,7 +468,7 @@ function buildFailure(line: string | undefined): NativeRuntimeRequestError { ? detail.code : undefined; if ( - code?.startsWith("registry_") && + (code?.startsWith("registry_") || code === "image_tag_offline_missing") && typeof detail.cause_code === "string" && nativeImageRegistryReason(detail.cause_code) && typeof detail.build_base_reference === "string" && @@ -814,6 +857,8 @@ async function runPendingBuilds(opts: { const directory = await mkdtemp(join(tmpdir(), "hack-native-build-")); try { let index = 0; + const notices = new Set(); + const selections = new Map(); for (const { request, services } of opts.pending.values()) { if (opts.signal.aborted) { throw new ClosedCliError( @@ -834,6 +879,10 @@ async function runPendingBuilds(opts: { args: request.args, policy: opts.rebuild ? "rebuild" : "missing", timeout_seconds: BUILD_TIMEOUT_SECONDS, + image_tag_ttl_seconds: nativeImageTagTtlSeconds(), + ...(selections.size + ? { command_base_pins: Object.fromEntries(selections) } + : {}), }), { mode: 0o600, flag: "wx" } ); @@ -845,6 +894,19 @@ async function runPendingBuilds(opts: { }).catch((error: unknown) => { throw nameBuildFailure(services, error); }); + for (const [reference, pin] of Object.entries( + built.baseSelections ?? {} + )) { + selections.set(reference, pin); + } + for (const notice of built.baseFallbacks ?? []) { + if (!notices.has(notice)) { + notices.add(notice); + if (!reportNativeImageTagOffline(notice)) { + process.stderr.write(`${notice}\n`); + } + } + } // The request carries argument values; remove it as soon as it is consumed. await rm(requestFile, { force: true }); if (!built.reused) { @@ -890,6 +952,69 @@ const BUILD_SOURCE_POLICY: Readonly> = { * classify failures. Cancellation and closed client errors carry no * service-specific cause and pass through unchanged. */ +export async function nativeBuildBases(opts: { + readonly projectRoot: string; + readonly runtime: NativeRuntimeSelection; + readonly builds: ReadonlyMap; + readonly invoke: typeof import("./native-runtime-client.ts").invokeNativeRuntime; +}): Promise { + if (opts.builds.size === 0) { + return []; + } + const projectRoot = await realpath(opts.projectRoot); + const directory = await mkdtemp(join(tmpdir(), "hack-native-build-scan-")); + const file = join(directory, "request.json"); + const bases = new Set(); + try { + for (const build of opts.builds.values()) { + await writeFile( + file, + JSON.stringify({ + version: 1, + project_root: projectRoot, + context: build.context, + dockerfile: build.dockerfile, + target: build.target, + args: build.args, + policy: "missing", + }), + { mode: 0o600 } + ); + const result = await opts.invoke({ + runtime: opts.runtime, + cwd: opts.projectRoot, + args: [ + "runtime", + "build-image", + "--request", + file, + "--bases", + "--json", + ], + }); + if ( + !( + Array.isArray(result) && + result.every( + (item: unknown) => + typeof item === "string" && BUILD_BASE_REFERENCE.test(item) + ) + ) + ) { + throw new ClosedCliError( + "Native runtime returned an invalid build base list." + ); + } + for (const reference of result) { + bases.add(reference); + } + } + return [...bases]; + } finally { + await rm(directory, { recursive: true, force: true }); + } +} + function nameBuildFailure( services: readonly string[], error: unknown diff --git a/tests/models/tla/README.md b/tests/models/tla/README.md index 8c3463bf4..15fa8e432 100644 --- a/tests/models/tla/README.md +++ b/tests/models/tla/README.md @@ -1871,3 +1871,16 @@ Not covered: - readiness (healthchecks, their bounds and the end-to-end route probe are in `tests/global-stack-state.test.ts` and `tests/global-readiness.test.ts`); - the login path, which only reads the setting and starts routing; - a home whose whole logging directory is removed before its first manual start, which then counts as new. + +## Native build base aliases + +`native-build-alias/BuildAlias.tla` models one loaded base and one attempt. +`Record` represents the cache tag and the durable alias journal written before +`Tag`. The build-key lock is inherited by the builder. `Crash` can leave an alias +and a live child; `Cleanup` is admitted only after the lock is free, or by the +live owner after the solver is done. The source allowlist contains only that +attempt's local alias. The negative controls remove the cache reference, allow +remote resolution, or sweep while the child still holds the lock. The model +does not simulate Docker's transport, key uniqueness, the registry, or disk +durability. The Rust alias sweep regression and the classic-worker wire count +cover separate implementation boundaries. diff --git a/tests/models/tla/native-build-alias/BuildAlias.tla b/tests/models/tla/native-build-alias/BuildAlias.tla new file mode 100644 index 000000000..cd03c9c44 --- /dev/null +++ b/tests/models/tla/native-build-alias/BuildAlias.tla @@ -0,0 +1,38 @@ +---- MODULE BuildAlias ---- +EXTENDS Naturals +CONSTANT UnsafeUntag, UnsafeRemote, UnsafeSweep +VARIABLES phase, alias, base, keeper, child, wire, sweptLive +vars == <> + +Init == /\ phase = "idle" /\ alias = FALSE /\ base = TRUE + /\ keeper = FALSE /\ child = FALSE /\ wire = FALSE /\ sweptLive = FALSE +Record == /\ phase = "idle" /\ phase' = "recorded" + /\ keeper' = ~UnsafeUntag + /\ UNCHANGED <> +Tag == /\ phase = "recorded" /\ base /\ phase' = "tagged" /\ alias' = TRUE + /\ UNCHANGED <> +Solve == /\ phase = "tagged" /\ alias /\ phase' = "solving" /\ child' = TRUE + /\ UNCHANGED <> +ResolveMissing == /\ phase = "solving" /\ UnsafeRemote + /\ wire' = TRUE /\ UNCHANGED <> +Finish == /\ phase = "solving" /\ phase' = "finished" /\ child' = FALSE + /\ UNCHANGED <> +Crash == /\ phase \in {"recorded", "tagged", "solving", "finished"} + /\ phase' = "stranded" + /\ UNCHANGED <> +ChildExits == /\ phase = "stranded" /\ child /\ child' = FALSE + /\ UNCHANGED <> +Cleanup == /\ phase \in {"finished", "stranded"} + /\ ~child \/ UnsafeSweep + /\ sweptLive' = (sweptLive \/ child) + /\ base' = (base /\ (keeper \/ ~alias)) + /\ alias' = FALSE /\ phase' = "idle" /\ child' = FALSE + /\ UNCHANGED <> + +Next == Record \/ Tag \/ Solve \/ ResolveMissing \/ Finish \/ Crash \/ ChildExits \/ Cleanup +Spec == Init /\ [][Next]_vars +BaseSurvives == base +NoRegistryFallback == ~wire +NoLiveSweep == ~sweptLive +IdleIsClean == phase = "idle" => ~alias +==== diff --git a/tests/models/tla/native-build-alias/negative.cfg b/tests/models/tla/native-build-alias/negative.cfg new file mode 100644 index 000000000..4c6a30e96 --- /dev/null +++ b/tests/models/tla/native-build-alias/negative.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS UnsafeUntag = TRUE UnsafeRemote = FALSE UnsafeSweep = FALSE +INVARIANTS BaseSurvives NoRegistryFallback NoLiveSweep IdleIsClean +CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-build-alias/positive.cfg b/tests/models/tla/native-build-alias/positive.cfg new file mode 100644 index 000000000..7959e99ba --- /dev/null +++ b/tests/models/tla/native-build-alias/positive.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS UnsafeUntag = FALSE UnsafeRemote = FALSE UnsafeSweep = FALSE +INVARIANTS BaseSurvives NoRegistryFallback NoLiveSweep IdleIsClean +CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-build-alias/unsafe-remote.cfg b/tests/models/tla/native-build-alias/unsafe-remote.cfg new file mode 100644 index 000000000..db489d3d2 --- /dev/null +++ b/tests/models/tla/native-build-alias/unsafe-remote.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS UnsafeUntag = FALSE UnsafeRemote = TRUE UnsafeSweep = FALSE +INVARIANTS BaseSurvives NoRegistryFallback NoLiveSweep IdleIsClean +CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-build-alias/unsafe-sweep.cfg b/tests/models/tla/native-build-alias/unsafe-sweep.cfg new file mode 100644 index 000000000..bdce6ad67 --- /dev/null +++ b/tests/models/tla/native-build-alias/unsafe-sweep.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS UnsafeUntag = FALSE UnsafeRemote = FALSE UnsafeSweep = TRUE +INVARIANTS BaseSurvives NoRegistryFallback NoLiveSweep IdleIsClean +CHECK_DEADLOCK FALSE From daec5a3d2a5e3976bbba70c324bf0f5efd49f23b Mon Sep 17 00:00:00 2001 From: Dimitri Kennedy <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:48:32 -0500 Subject: [PATCH 13/33] fix(native): pass base-image notices through a callback `native-project-builds.ts` imported the detached-up module only to report a base-image fallback, which closed an import cycle with the backend feature list: importing the builds module first failed with "Cannot access 'NATIVE_BUILD_FIELDS' before initialization". The start path now passes the reporter in, and uses the name #1082 gave it. Co-Authored-By: Claude Opus 5.5 --- src/backends/native-project-builds.ts | 8 ++++++-- src/backends/native-project-start.ts | 6 ++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/backends/native-project-builds.ts b/src/backends/native-project-builds.ts index ef9fd2cc2..a6c9bed14 100644 --- a/src/backends/native-project-builds.ts +++ b/src/backends/native-project-builds.ts @@ -4,7 +4,6 @@ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { childEnvironment } from "../lib/child-environment.ts"; import { ClosedCliError, HackCliError } from "../lib/cli-result.ts"; import { isRecord } from "../lib/guards.ts"; -import { reportNativeImageTagOffline } from "../lib/native-detached-up.ts"; import { NATIVE_BUILDER_MISSING, NATIVE_BUILDER_NOT_PREPARED, @@ -667,6 +666,8 @@ export async function buildNativeProjectImages(opts: { readonly invoke?: typeof invokeNativeBuild; /** Called once for each build the runtime actually ran (not a reused image). */ readonly onBuilt?: () => void; + /** One line per distinct base-image fallback; stderr when the caller gives none. */ + readonly onNotice?: (line: string) => void; }): Promise> { const pending = pendingBuilds(opts); if (pending.size > 0) { @@ -850,6 +851,7 @@ async function runPendingBuilds(opts: { readonly signal: AbortSignal; readonly invoke?: typeof invokeNativeBuild; readonly onBuilt?: () => void; + readonly onNotice?: (line: string) => void; }): Promise { const invoke = opts.invoke ?? invokeNativeBuild; // The runtime requires the exact canonical root; it also derives the namespace. @@ -902,7 +904,9 @@ async function runPendingBuilds(opts: { for (const notice of built.baseFallbacks ?? []) { if (!notices.has(notice)) { notices.add(notice); - if (!reportNativeImageTagOffline(notice)) { + if (opts.onNotice) { + opts.onNotice(notice); + } else { process.stderr.write(`${notice}\n`); } } diff --git a/src/backends/native-project-start.ts b/src/backends/native-project-start.ts index 9666c0f86..05aeb0b38 100644 --- a/src/backends/native-project-start.ts +++ b/src/backends/native-project-start.ts @@ -782,6 +782,7 @@ async function resolveNativeBuildImages(opts: { readonly signal: AbortSignal; readonly invoke: typeof invokeNativeBuild | undefined; readonly onBuilt: () => void; + readonly onNotice: (line: string) => void; }): Promise> { const remaining = pinVerifiedNativeBuilds(opts); const built = await buildNativeProjectImages({ @@ -3062,6 +3063,11 @@ async function startNativeProjectAttempt( onBuilt: () => { rebuilt = true; }, + onNotice: (line) => { + if (!reportNativeImageNotice(line)) { + process.stderr.write(`${line}\n`); + } + }, }).catch(async (error: unknown) => { if (!(error instanceof NativeBuildRegistryError)) { throw error; From fe1e5be51882b9a1e6a917c0abc0e8efd7119a6c Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:55:52 +0000 Subject: [PATCH 14/33] fix: share native image policy with build bases --- .../runtime-core/src/provider/image_build.rs | 18 ++++++++++-------- .../src/provider/image_build/tests.rs | 2 +- src/backends/native-project-builds.ts | 5 +++-- 3 files changed, 14 insertions(+), 11 deletions(-) diff --git a/packages/runtime-core/src/provider/image_build.rs b/packages/runtime-core/src/provider/image_build.rs index 0aea54b68..e77bb2330 100644 --- a/packages/runtime-core/src/provider/image_build.rs +++ b/packages/runtime-core/src/provider/image_build.rs @@ -182,7 +182,7 @@ pub struct BuildRequest { #[serde(default)] pub timeout_seconds: Option, #[serde(default)] - pub image_tag_ttl_seconds: Option, + pub image_policy_args: Vec, #[serde(default)] pub command_base_pins: BTreeMap, } @@ -1869,13 +1869,15 @@ fn key_with_bases( /// `runtime build-image --request `: build or reuse one native image. pub fn build_image(candidate: &Candidate, request: &Path) -> Result { let request: BuildRequest = state::read_bounded(request, MAX_REQUEST_BYTES)?; - let mut policy = super::image_policy::ImagePolicy::default(); - if let Some(ttl) = request.image_tag_ttl_seconds { - if ttl > 2_592_000 { - return Err(invalid("Image tag lifetime exceeds thirty days.")); - } - policy.tag_ttl_seconds = ttl; - } + let flags: Vec<_> = request + .image_policy_args + .iter() + .map(String::as_str) + .collect(); + let mut policy = super::image_policy::ImagePolicy::from_flags(&flags)?; + // Dockerfile admission allows Docker Hub only, even when service images + // are allowed to use local registries. + policy.local_registries.clear(); let prior_pins = request.command_base_pins.clone(); let mut inputs = prepare(request, &builds_root(candidate))?; let _signals = CancelSignals::install()?; diff --git a/packages/runtime-core/src/provider/image_build/tests.rs b/packages/runtime-core/src/provider/image_build/tests.rs index 2ea81a620..fcb9a9796 100644 --- a/packages/runtime-core/src/provider/image_build/tests.rs +++ b/packages/runtime-core/src/provider/image_build/tests.rs @@ -62,7 +62,7 @@ impl Fixture { args: BTreeMap::from([("GREETING".to_owned(), SECRET.to_owned())]), policy, timeout_seconds: Some(30), - image_tag_ttl_seconds: None, + image_policy_args: Vec::new(), command_base_pins: BTreeMap::new(), } } diff --git a/src/backends/native-project-builds.ts b/src/backends/native-project-builds.ts index a6c9bed14..0cd3f27d4 100644 --- a/src/backends/native-project-builds.ts +++ b/src/backends/native-project-builds.ts @@ -11,8 +11,8 @@ import { nativeBuilderRemedy, } from "../lib/native-image-builder.ts"; import { + nativeImagePolicyArgs, nativeImageRegistryReason, - nativeImageTagTtlSeconds, } from "./native-image-policy.ts"; import { type invokeNativeRuntime, @@ -854,6 +854,7 @@ async function runPendingBuilds(opts: { readonly onNotice?: (line: string) => void; }): Promise { const invoke = opts.invoke ?? invokeNativeBuild; + const imagePolicyArgs = nativeImagePolicyArgs(); // The runtime requires the exact canonical root; it also derives the namespace. const projectRoot = await realpath(opts.projectRoot); const directory = await mkdtemp(join(tmpdir(), "hack-native-build-")); @@ -881,7 +882,7 @@ async function runPendingBuilds(opts: { args: request.args, policy: opts.rebuild ? "rebuild" : "missing", timeout_seconds: BUILD_TIMEOUT_SECONDS, - image_tag_ttl_seconds: nativeImageTagTtlSeconds(), + image_policy_args: imagePolicyArgs, ...(selections.size ? { command_base_pins: Object.fromEntries(selections) } : {}), From 0833576bbc43c6391a92fafb8d7b26163eedbf2e Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:56:58 +0000 Subject: [PATCH 15/33] fix: apply up tag mode to native build bases --- docs/guides/native-candidate.md | 11 ++++++----- docs/versions/v5/native/existing-compose-project.md | 8 +++++--- packages/runtime-core/src/provider/image_build.rs | 3 +++ .../runtime-core/src/provider/image_build/tests.rs | 1 + packages/runtime-core/src/provider/image_policy.rs | 3 ++- src/backends/native-project-builds.ts | 3 +++ src/backends/native-project-start.ts | 2 ++ tests/native-project-builds.test.ts | 2 ++ 8 files changed, 24 insertions(+), 9 deletions(-) diff --git a/docs/guides/native-candidate.md b/docs/guides/native-candidate.md index fa2d7cb27..0f9c1b9ee 100644 --- a/docs/guides/native-candidate.md +++ b/docs/guides/native-candidate.md @@ -503,11 +503,12 @@ With it: an unchanged context is not read again. The cache misses only a change that keeps the size, inode, modification time and change time identical, which needs a deliberate clock or timestamp manipulation; set `HACK_NATIVE_REBUILD=1` after one. -- Only those inputs count. A changed network response (a download in a `RUN` step), - the contents of a cache mount (`RUN --mount=type=cache`), anything outside the build - context and a base-image tag that moved do not trigger a rebuild: a reused image keeps - the base-image digests it was built from. Set `HACK_NATIVE_REBUILD=1` on `up` or - `hack restart` to build every image again; base-image tags then resolve again too. +- A changed network response in a `RUN` step or changed cache mount contents do + not trigger a rebuild. Native checks base-image tags according to the image tag + policy and rebuilds when the selected base digest changes. `hack up --offline` + uses locally recorded selections even after they expire. `hack up --refresh-images` + checks the registry for current tags. `HACK_NATIVE_REBUILD=1` forces BuildKit to + run on `up` or `hack restart` and keeps the usual base tag freshness policy. - When an image is actually built, BuildKit reads a private copy of the included context, made and checked against the build key right before it runs, so edits during a build never reach the image. The copy keeps hard links as links and gives every diff --git a/docs/versions/v5/native/existing-compose-project.md b/docs/versions/v5/native/existing-compose-project.md index 91bec0ef1..82653db9b 100644 --- a/docs/versions/v5/native/existing-compose-project.md +++ b/docs/versions/v5/native/existing-compose-project.md @@ -82,9 +82,11 @@ the build read. Change any of them and the next `up` builds again, also after `hack down`; the run's containers are then recreated from the new image and named volumes are kept. `hack restart` checks the same inputs before it stops anything: a build that fails leaves the current project running, and a rebuilt image is what the -restarted project runs. A download in a `RUN` step, a cache mount and a moved base -image tag do not count; `HACK_NATIVE_REBUILD=1` on `up` or `hack restart` builds every -image again and looks the tags up now. After an `up` that built, native removes the +restarted project runs. A changed download in a `RUN` step or changed cache mount +contents do not trigger a rebuild. A changed base digest does. Use +`hack up --refresh-images` to check base tags now or `hack up --offline` to use +locally recorded selections even after they expire. `HACK_NATIVE_REBUILD=1` forces +a build with the usual base tag freshness policy. After an `up` that built, native removes the older images of each build, keeping the current one, the one before it and any image a run still uses. diff --git a/packages/runtime-core/src/provider/image_build.rs b/packages/runtime-core/src/provider/image_build.rs index e77bb2330..4f498dc39 100644 --- a/packages/runtime-core/src/provider/image_build.rs +++ b/packages/runtime-core/src/provider/image_build.rs @@ -184,6 +184,8 @@ pub struct BuildRequest { #[serde(default)] pub image_policy_args: Vec, #[serde(default)] + pub image_tag_mode: super::image_policy::ImageTagMode, + #[serde(default)] pub command_base_pins: BTreeMap, } fn default_dockerfile() -> String { @@ -1878,6 +1880,7 @@ pub fn build_image(candidate: &Candidate, request: &Path) -> Result; readonly specs: Record>; + readonly imageTagMode?: "refresh" | "offline"; readonly rebuild: boolean; readonly signal: AbortSignal; readonly invoke?: typeof invokeNativeBuild; @@ -847,6 +848,7 @@ async function runPendingBuilds(opts: { readonly branch: string | null | undefined; readonly pending: ReadonlyMap; readonly specs: Record>; + readonly imageTagMode?: "refresh" | "offline"; readonly rebuild: boolean; readonly signal: AbortSignal; readonly invoke?: typeof invokeNativeBuild; @@ -883,6 +885,7 @@ async function runPendingBuilds(opts: { policy: opts.rebuild ? "rebuild" : "missing", timeout_seconds: BUILD_TIMEOUT_SECONDS, image_policy_args: imagePolicyArgs, + image_tag_mode: opts.imageTagMode, ...(selections.size ? { command_base_pins: Object.fromEntries(selections) } : {}), diff --git a/src/backends/native-project-start.ts b/src/backends/native-project-start.ts index 05aeb0b38..14b60bfb1 100644 --- a/src/backends/native-project-start.ts +++ b/src/backends/native-project-start.ts @@ -779,6 +779,7 @@ async function resolveNativeBuildImages(opts: { readonly builds: ReadonlyMap; readonly specs: Record>; readonly verified: ReadonlyMap | undefined; + readonly imageTagMode?: "refresh" | "offline"; readonly signal: AbortSignal; readonly invoke: typeof invokeNativeBuild | undefined; readonly onBuilt: () => void; @@ -3058,6 +3059,7 @@ async function startNativeProjectAttempt( builds, specs, verified: opts.verifiedBuildImages, + imageTagMode: opts.imageTagMode, signal: controller.signal, invoke: deps.build, onBuilt: () => { diff --git a/tests/native-project-builds.test.ts b/tests/native-project-builds.test.ts index 398ca388b..097013bc0 100644 --- a/tests/native-project-builds.test.ts +++ b/tests/native-project-builds.test.ts @@ -242,6 +242,7 @@ test("identical builds run once, pin every service and keep the request private" ["other", { ...request(), target: "dev" }], ]), specs, + imageTagMode: "offline", rebuild: false, signal: new AbortController().signal, invoke: async ({ requestFile }) => { @@ -260,6 +261,7 @@ test("identical builds run once, pin every service and keep the request private" branch: "feature", context: "app", policy: "missing", + image_tag_mode: "offline", args: { A: VALUE }, }); expect(seen[1]?.body.target).toBe("dev"); From af5e612e6e1ceada10e2a687221dd287de03755b Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:58:04 +0000 Subject: [PATCH 16/33] fix: interrupt native build base downloads promptly --- .../runtime-core/src/provider/image_build.rs | 12 ++++--- src/backends/native-project-builds.ts | 33 +++++++++++++++++-- src/backends/native-project-start.ts | 2 ++ 3 files changed, 40 insertions(+), 7 deletions(-) diff --git a/packages/runtime-core/src/provider/image_build.rs b/packages/runtime-core/src/provider/image_build.rs index 4f498dc39..31cb952de 100644 --- a/packages/runtime-core/src/provider/image_build.rs +++ b/packages/runtime-core/src/provider/image_build.rs @@ -1883,8 +1883,6 @@ pub fn build_image(candidate: &Candidate, request: &Path) -> Result Result= deadline { - return Err(late_stop(canceled())); + if Instant::now() >= deadline { + return Err(late_stop(false)); } let reference = base.reference.canonical(); policy.command_image_pin = prior_pins @@ -1930,6 +1928,12 @@ pub fn build_image(candidate: &Candidate, request: &Path) -> Result, - write: (text: string) => void + write: (text: string) => void, + onImageWait?: (reference: string | null) => void ): Promise { const decoder = new TextDecoder(); let pending = ""; let held: string | undefined; const emit = (line: string) => { + if (onImageWait && line.startsWith("hack.image-wait:")) { + const [state, reference] = line.split(" ", 2); + if ( + state === "hack.image-wait:begin" && + reference && + BUILD_BASE_REFERENCE.test(reference) + ) { + onImageWait(reference); + return; + } + if (state === "hack.image-wait:end") { + onImageWait(null); + return; + } + } if (held !== undefined) { write(`${held}\n`); held = undefined; @@ -499,6 +515,7 @@ export async function invokeNativeBuild(opts: { readonly cwd: string; readonly requestFile: string; readonly signal?: AbortSignal; + readonly onImageWait?: (reference: string | null) => void; readonly write?: (text: string) => void; }): Promise { if (opts.signal?.aborted) { @@ -519,7 +536,12 @@ export async function invokeNativeBuild(opts: { ], { cwd: opts.cwd, - env: childEnvironment(systemEnvironment()), + env: childEnvironment({ + ...systemEnvironment(), + ...(opts.onImageWait + ? { HACK_INTERNAL_REPORT_IMAGE_WAIT: "batch" } + : {}), + }), stdin: "ignore", stdout: "pipe", stderr: "pipe", @@ -539,7 +561,8 @@ export async function invokeNativeBuild(opts: { new Response(child.stdout).arrayBuffer(), forwardBuildOutput( child.stderr, - opts.write ?? ((text) => process.stderr.write(text)) + opts.write ?? ((text) => process.stderr.write(text)), + opts.onImageWait ), child.exited, ]); @@ -558,6 +581,7 @@ export async function invokeNativeBuild(opts: { } return parseBuilt(JSON.parse(new TextDecoder().decode(stdout))); } finally { + opts.onImageWait?.(null); opts.signal?.removeEventListener("abort", cancel); clearTimeout(outer); clearTimeout(killTimer); @@ -668,6 +692,7 @@ export async function buildNativeProjectImages(opts: { /** Called once for each build the runtime actually ran (not a reused image). */ readonly onBuilt?: () => void; /** One line per distinct base-image fallback; stderr when the caller gives none. */ + readonly onImageWait?: (reference: string | null) => void; readonly onNotice?: (line: string) => void; }): Promise> { const pending = pendingBuilds(opts); @@ -853,6 +878,7 @@ async function runPendingBuilds(opts: { readonly signal: AbortSignal; readonly invoke?: typeof invokeNativeBuild; readonly onBuilt?: () => void; + readonly onImageWait?: (reference: string | null) => void; readonly onNotice?: (line: string) => void; }): Promise { const invoke = opts.invoke ?? invokeNativeBuild; @@ -896,6 +922,7 @@ async function runPendingBuilds(opts: { runtime: opts.runtime, cwd: opts.projectRoot, requestFile, + onImageWait: opts.onImageWait, signal: opts.signal, }).catch((error: unknown) => { throw nameBuildFailure(services, error); diff --git a/src/backends/native-project-start.ts b/src/backends/native-project-start.ts index 14b60bfb1..e3b7a62ff 100644 --- a/src/backends/native-project-start.ts +++ b/src/backends/native-project-start.ts @@ -783,6 +783,7 @@ async function resolveNativeBuildImages(opts: { readonly signal: AbortSignal; readonly invoke: typeof invokeNativeBuild | undefined; readonly onBuilt: () => void; + readonly onImageWait: (reference: string | null) => void; readonly onNotice: (line: string) => void; }): Promise> { const remaining = pinVerifiedNativeBuilds(opts); @@ -3065,6 +3066,7 @@ async function startNativeProjectAttempt( onBuilt: () => { rebuilt = true; }, + onImageWait: reportNativeImageDownloadWait, onNotice: (line) => { if (!reportNativeImageNotice(line)) { process.stderr.write(`${line}\n`); From 79ddf26539f8bacae8a1806a0c3f22ac8556abfc Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:58:59 +0000 Subject: [PATCH 17/33] fix: recover stranded native build base aliases --- .../runtime-core/src/provider/image_build.rs | 8 +-- .../src/provider/image_build/aliases.rs | 59 +++++++++++++------ 2 files changed, 44 insertions(+), 23 deletions(-) diff --git a/packages/runtime-core/src/provider/image_build.rs b/packages/runtime-core/src/provider/image_build.rs index 31cb952de..e0c6860e9 100644 --- a/packages/runtime-core/src/provider/image_build.rs +++ b/packages/runtime-core/src/provider/image_build.rs @@ -897,10 +897,6 @@ fn run_with_bases( Err(error) => return Err(state::io(error)), } let alias_path = directory.join(format!("{}.client/base-aliases.json", inputs.key)); - if selected.is_some() { - aliases::sweep_stranded(&root, pool, &lease, &identity, &alias_path); - aliases::sweep(pool, &lease, &identity, &alias_path)?; - } let expected = labels(inputs, &identity); let previous = read_receipt(&receipt_path)?; if let Some(previous) = &previous { @@ -937,6 +933,10 @@ fn run_with_bases( state::write(&receipt_path, &dead)?; } } + if selected.is_some() { + aliases::sweep_stranded(&root, pool, &lease, &identity, &alias_path); + aliases::sweep(pool, &lease, &identity, &alias_path)?; + } let previous_bytes = previous.as_ref().and_then(|receipt| receipt.image_bytes); drop(lease); // Snapshots other attempts in this namespace stranded when they were killed. diff --git a/packages/runtime-core/src/provider/image_build/aliases.rs b/packages/runtime-core/src/provider/image_build/aliases.rs index b48066a8a..d2e4b8e90 100644 --- a/packages/runtime-core/src/provider/image_build/aliases.rs +++ b/packages/runtime-core/src/provider/image_build/aliases.rs @@ -47,10 +47,15 @@ fn tag( if image["Id"] == id { return Ok(()); } - return Err(refusal( - "native_build_base_image", - "A private base alias differs from the verified image.", - )); + let keeper = format!("{DOMAIN}/{CACHE}:{}", id.trim_start_matches("sha256:")); + if reference != keeper { + return Err(refusal( + "native_build_base_image", + "A private base alias differs from the verified image.", + )); + } + // The keeper name is derived from this exact image ID. Repoint the + // private tag without deleting the image it currently names. } pool.tag_base(lease, id, reference)?; if pool @@ -163,27 +168,29 @@ pub(super) fn sweep( if !path.try_exists().map_err(state::io)? { return Ok(()); } - let journal: Journal = state::read_bounded(path, MAX_RECEIPT_BYTES)?; + let journal: Journal = match state::read_bounded(path, MAX_RECEIPT_BYTES) { + Ok(journal) => journal, + Err(error) if error.code == "invalid_receipt" => return quarantine(path), + Err(error) => return Err(error), + }; if journal.incarnation == identity.incarnation && journal.engine_id == identity.engine_id { + if journal + .aliases + .iter() + .any(|(alias, id)| parse(alias) != scope(path) || !image_id(id)) + { + return quarantine(path); + } for (alias, id) in journal.aliases { - if parse(&alias) != scope(path) || !image_id(&id) { - return Err(refusal( - "native_build_receipt", - "The recorded build alias is invalid.", - )); - } if let Some(image) = pool.inspect(lease, &alias)? { - let keeper = format!("{DOMAIN}/{CACHE}:{}", id.trim_start_matches("sha256:")); - if image["Id"] != id - || pool - .inspect(lease, &keeper)? - .is_none_or(|image| image["Id"] != id) - { + if image["Id"] != id { return Err(refusal( - "native_build_receipt", - "The recorded build alias or its cache tag differs.", + "native_build_base_image", + "The recorded build alias differs from its image ID.", )); } + let keeper = format!("{DOMAIN}/{CACHE}:{}", id.trim_start_matches("sha256:")); + tag(pool, lease, &id, &keeper)?; pool.untag_base(lease, &alias)?; } } @@ -191,6 +198,20 @@ pub(super) fn sweep( fs::remove_file(path).map_err(state::io) } +fn quarantine(path: &Path) -> Result<(), CandidateError> { + let mut nonce = [0u8; 16]; + File::open("/dev/urandom") + .and_then(|mut file| file.read_exact(&mut nonce)) + .map_err(state::io)?; + let saved = path.with_extension(format!("invalid-{:x}.json", crate::Hex(nonce))); + fs::rename(path, &saved).map_err(state::io)?; + eprintln!( + "Set aside a malformed build alias journal at {}", + saved.display() + ); + Ok(()) +} + /// Sweep only attempt journals whose key lock is free, including other projects. pub(super) fn sweep_stranded( root: &Path, From 33baa0710129afe33ad8b5aee2f35b56f73b006f Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:59:52 +0000 Subject: [PATCH 18/33] fix: reuse verified legacy builds during registry failures --- .../runtime-core/src/provider/image_build.rs | 113 +++++++++++++++--- src/backends/native-project-builds.ts | 5 + 2 files changed, 100 insertions(+), 18 deletions(-) diff --git a/packages/runtime-core/src/provider/image_build.rs b/packages/runtime-core/src/provider/image_build.rs index e0c6860e9..14c99d26d 100644 --- a/packages/runtime-core/src/provider/image_build.rs +++ b/packages/runtime-core/src/provider/image_build.rs @@ -206,6 +206,7 @@ pub struct BuildOutcome { pub base_fallbacks: Vec, #[serde(skip_serializing_if = "BTreeMap::is_empty")] pub base_selections: BTreeMap, + pub reused_legacy_key: bool, /// Build cache bytes the post-build prune reclaimed; `None` when no prune ran or /// it failed (the build result stands either way). #[serde(skip_serializing_if = "Option::is_none")] @@ -823,6 +824,78 @@ fn owned_image( } } +fn reuse_verified( + candidate: &Candidate, + pool: &P, + (lease, identity): (&P::Lease, &PoolIdentity), + inputs: &Inputs, + path: &Path, + previous: &Receipt, +) -> Result, CandidateError> { + if inputs.policy == Policy::Missing + && previous.version == 1 + && previous.namespace == inputs.namespace + && previous.build_key == inputs.key + && previous.phase == Phase::ContentIdVerified + && previous.checkout == candidate.checkout + && previous.provider_incarnation == identity.incarnation + && previous.engine_id == identity.engine_id + && let Some(id) = previous.image_id.as_deref().filter(|id| image_id(id)) + && let Some(inspected) = pool.inspect(lease, id)? + && owned_image(&inspected, id, &labels(inputs, identity)).is_ok() + { + let mut current = previous.clone(); + current.provider_boot_id = identity.boot_id.clone(); + current.declaration = Some(inputs.declaration.clone()); + current.sequence = path.parent().map(next_sequence); + state::write(path, ¤t)?; + return Ok(Some(reused(inputs, id, &previous.base_pins))); + } + Ok(None) +} + +fn reuse_legacy( + candidate: &Candidate, + pool: &P, + inputs: &Inputs, +) -> Result, CandidateError> { + if inputs.policy != Policy::Missing { + return Ok(None); + } + let directory = builds_root(candidate).join(&inputs.namespace); + let path = directory.join(format!("{}.json", inputs.key)); + if !path.try_exists().map_err(state::io)? { + return Ok(None); + } + let (lease, identity) = pool.lease()?; + let lock = Flock::open(&directory.join(format!("{}.lock", inputs.key)))?; + let Some(_lock) = Flock::try_lock(lock, libc::LOCK_EX)? else { + return Ok(None); + }; + let Some(previous) = read_receipt(&path)? else { + return Ok(None); + }; + if path + .with_extension("pending") + .try_exists() + .map_err(state::io)? + { + return Ok(None); + } + let mut outcome = reuse_verified( + candidate, + pool, + (&lease, &identity), + inputs, + &path, + &previous, + )?; + if let Some(reused) = &mut outcome { + reused.reused_legacy_key = true; + } + Ok(outcome) +} + /// Run one build operation end to end. See the module documentation for the protocol. /// `canceled` reports a pending cancellation request; it is checked before each /// unleased step, during base resolution and while the client runs. The time budget @@ -909,22 +982,15 @@ fn run_with_bases( "A build receipt does not match its path; no image was adopted or replaced.", )); } - if inputs.policy == Policy::Missing - && previous.phase == Phase::ContentIdVerified - && previous.checkout == candidate.checkout - && previous.provider_incarnation == identity.incarnation - && previous.engine_id == identity.engine_id - && let Some(id) = previous.image_id.as_deref().filter(|id| image_id(id)) - && let Some(inspected) = pool.inspect(&lease, id)? - && owned_image(&inspected, id, &expected).is_ok() - { - // The reused key becomes its declaration's image in use again. - let mut current = previous.clone(); - current.provider_boot_id = identity.boot_id.clone(); - current.declaration = Some(inputs.declaration.clone()); - current.sequence = Some(next_sequence(&directory)); - state::write(&receipt_path, ¤t)?; - return Ok(reused(inputs, id, &previous.base_pins)); + if let Some(outcome) = reuse_verified( + candidate, + pool, + (&lease, &identity), + inputs, + &receipt_path, + previous, + )? { + return Ok(outcome); } if previous.phase == Phase::Building { // The key lock proves no live holder: that attempt died mid-build. @@ -1185,6 +1251,7 @@ fn run_with_bases( base_pins: pins, base_fallbacks: Vec::new(), base_selections: BTreeMap::new(), + reused_legacy_key: false, cache_reclaimed_bytes, }) } @@ -1213,6 +1280,7 @@ fn reused(inputs: &Inputs, id: &str, pins: &BTreeMap) -> BuildOu base_pins: pins.clone(), base_fallbacks: Vec::new(), base_selections: BTreeMap::new(), + reused_legacy_key: false, cache_reclaimed_bytes: None, } } @@ -1899,8 +1967,17 @@ pub fn build_image(candidate: &Candidate, request: &Path) -> Result ensured, + Err(error) => { + if error.code.starts_with("registry_") + && let Some(outcome) = reuse_legacy(candidate, &pool, &inputs)? + { + return Ok(outcome); + } + return Err(error.with_build_base_reference(reference)); + } + }; let proof = super::image_ensure::recorded_proof( candidate, &ensured.pinned_reference, diff --git a/src/backends/native-project-builds.ts b/src/backends/native-project-builds.ts index 3b001bdf1..0e8f290e3 100644 --- a/src/backends/native-project-builds.ts +++ b/src/backends/native-project-builds.ts @@ -373,6 +373,11 @@ function parseBuilt(value: unknown): NativeBuiltImage { : []; }) : []; + if (value.reused_legacy_key === true && value.reused) { + fallbacks.push( + "Registry unavailable, using the verified build image for the unchanged context and Dockerfile." + ); + } const selections = isRecord(value.base_selections) ? (Object.fromEntries( Object.entries(value.base_selections).filter( From 7d91dbed58439e01f80398d735865a098894a90c Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:02:21 +0000 Subject: [PATCH 19/33] fix: reclaim superseded native build base keepers --- .../runtime-core/src/provider/image_build.rs | 19 +++++- .../src/provider/image_build/aliases.rs | 5 ++ .../src/provider/image_build/reclaim.rs | 60 +++++++++++++++---- .../src/provider/image_build/tests.rs | 54 +++++++++++++++++ 4 files changed, 127 insertions(+), 11 deletions(-) diff --git a/packages/runtime-core/src/provider/image_build.rs b/packages/runtime-core/src/provider/image_build.rs index 14c99d26d..f641c631c 100644 --- a/packages/runtime-core/src/provider/image_build.rs +++ b/packages/runtime-core/src/provider/image_build.rs @@ -70,7 +70,7 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use sha2::{Digest, Sha256}; use std::{ - collections::BTreeMap, + collections::{BTreeMap, BTreeSet}, fs::{self, File, OpenOptions}, io::{Read, Write}, os::fd::AsRawFd, @@ -242,6 +242,8 @@ pub(super) struct Receipt { #[serde(default, skip_serializing_if = "Option::is_none")] image_bytes: Option, base_pins: BTreeMap, + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + base_image_ids: BTreeSet, /// The build declaration this key is a revision of (see [`Inputs::declaration`]). /// Receipts from before this field have none and are never reclaimed. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1103,6 +1105,10 @@ fn run_with_bases( // retry is admitted against it rather than the floor. image_bytes: previous_bytes, base_pins: pins.clone(), + base_image_ids: selected + .into_iter() + .flat_map(|bases| bases.values().map(|base| base.image_id.clone())) + .collect(), declaration: Some(inputs.declaration.clone()), // Kept from the last verified image of this key until this attempt verifies. sequence: previous.as_ref().and_then(|receipt| receipt.sequence), @@ -1954,6 +1960,17 @@ pub fn build_image(candidate: &Candidate, request: &Path) -> Result Option { + let digest = id.strip_prefix("sha256:").filter(|digest| hex64(digest))?; + Some(format!("{DOMAIN}/{CACHE}:{digest}")) +} + fn parse(reference: &str) -> Option<(&str, &str)> { let value = reference.strip_prefix("127.0.0.1:1/hack-build-attempt/")?; let (namespace, key) = value.split_once('/')?; diff --git a/packages/runtime-core/src/provider/image_build/reclaim.rs b/packages/runtime-core/src/provider/image_build/reclaim.rs index 8de47adf5..2fcef8832 100644 --- a/packages/runtime-core/src/provider/image_build/reclaim.rs +++ b/packages/runtime-core/src/provider/image_build/reclaim.rs @@ -76,6 +76,8 @@ pub struct ReclaimReport { pub(super) trait ReclaimPool: BuildPool { /// Images labeled `io.hack-local.kind=build-image`, as the engine lists them. fn build_images(&self, lease: &Self::Lease) -> Result, CandidateError>; + /// Engine image records with private build-base keeper tags. + fn base_images(&self, lease: &Self::Lease) -> Result, CandidateError>; /// Remove one image by content ID without force. `Ok(false)` when the engine refuses. fn remove(&self, lease: &Self::Lease, image: &str) -> Result; } @@ -193,9 +195,15 @@ fn scan_directory( /// The images build receipts protect, with why: per namespace and declaration, the /// most recent and the previous verified key (see the module documentation). -fn current_images(candidate: &Candidate) -> Result, CandidateError> { +#[derive(Default)] +struct CurrentImages { + builds: BTreeMap, + bases: BTreeSet, +} + +fn current_images(candidate: &Candidate) -> Result { let root = builds_root(candidate); - let mut protected = BTreeMap::new(); + let mut protected = CurrentImages::default(); let namespaces = match fs::read_dir(&root) { Ok(namespaces) => namespaces, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(protected), @@ -212,7 +220,8 @@ fn current_images(candidate: &Candidate) -> Result, C return Err(unprovable()); } // Declaration to its verified keys' (sequence, image). - let mut declarations: BTreeMap> = BTreeMap::new(); + let mut declarations: BTreeMap)>> = + BTreeMap::new(); for entry in fs::read_dir(&namespace).map_err(|_| unprovable())? { let path = entry.map_err(|_| unprovable())?.path(); if path.extension().and_then(|e| e.to_str()) != Some("json") { @@ -229,9 +238,10 @@ fn current_images(candidate: &Candidate) -> Result, C (Some(declaration), Some(sequence)) => declarations .entry(declaration) .or_default() - .push((sequence, id)), + .push((sequence, id, receipt.base_image_ids)), _ => { - protected.insert(id, Retained::Current); + protected.builds.insert(id, Retained::Current); + protected.bases.extend(receipt.base_image_ids); } } } @@ -239,10 +249,10 @@ fn current_images(candidate: &Candidate) -> Result, C keys.sort_by_key(|key| std::cmp::Reverse(key.0)); let mut sequences = keys .iter() - .map(|(sequence, _)| *sequence) + .map(|(sequence, _, _)| *sequence) .collect::>(); sequences.dedup(); - for (sequence, id) in keys { + for (sequence, id, bases) in keys { let reason = if Some(&sequence) == sequences.first() { Retained::Current } else if Some(&sequence) == sequences.get(1) { @@ -251,7 +261,8 @@ fn current_images(candidate: &Candidate) -> Result, C continue; }; // An image two keys share keeps its strongest reason. - let slot = protected.entry(id).or_insert(reason); + protected.bases.extend(bases); + let slot = protected.builds.entry(id).or_insert(reason); *slot = (*slot).min(reason); } } @@ -351,7 +362,7 @@ pub(super) fn run( let (candidates, mut retained) = plan( &images, &owner_label(&identity.incarnation), - ¤t, + ¤t.builds, &referenced, )?; let mut removed = Vec::new(); @@ -363,6 +374,24 @@ pub(super) fn run( } } } + for image in pool.base_images(&lease)? { + let Some(id) = image["Id"].as_str() else { + continue; + }; + let Some(keeper) = super::aliases::keeper(id) else { + continue; + }; + if !current.bases.contains(id) + && image["RepoTags"] + .as_array() + .is_some_and(|tags| tags.iter().any(|tag| tag == &keeper)) + && pool + .inspect(&lease, &keeper)? + .is_some_and(|image| image["Id"] == id) + { + let _ = pool.untag_base(&lease, &keeper); + } + } let cache_reclaimed_bytes = pool.prune_cache(&lease, CACHE_BUDGET).ok(); Ok(ReclaimReport { removed, @@ -384,6 +413,17 @@ impl ReclaimPool for LivePool<'_> { .cloned() .ok_or_else(|| refusal("engine_protocol", "The engine image list is not an array.")) } + fn base_images(&self, lease: &Self::Lease) -> Result, CandidateError> { + // Docker's reference filter matches only the private keeper repository. + lease.request( + reqwest::Method::GET, + "/v1.53/images/json?all=true&filters=%7B%22reference%22%3A%5B%22127.0.0.1%3A1%2Fhack-build-cache%3A%2A%22%5D%7D", + None, + )? + .as_array() + .cloned() + .ok_or_else(|| refusal("engine_protocol", "The engine image list is not an array.")) + } fn remove(&self, lease: &Self::Lease, image: &str) -> Result { match lease.request(reqwest::Method::DELETE, &removal_path(image), None) { Ok(_) => Ok(true), @@ -502,7 +542,7 @@ mod tests { plan( &[serde_json::json!({"Id": "bad"})], &owner, - ¤t, + ¤t.builds, &referenced ) .is_err() diff --git a/packages/runtime-core/src/provider/image_build/tests.rs b/packages/runtime-core/src/provider/image_build/tests.rs index 421639957..8f595d2ab 100644 --- a/packages/runtime-core/src/provider/image_build/tests.rs +++ b/packages/runtime-core/src/provider/image_build/tests.rs @@ -519,6 +519,7 @@ fn receipts_with_the_most_and_longest_accepted_pins_stay_readable() { image_id: Some(IMAGE.into()), image_bytes: Some(5 * GIB), base_pins: BTreeMap::new(), + base_image_ids: BTreeSet::new(), declaration: None, sequence: None, }; @@ -1023,6 +1024,7 @@ fn a_dead_attempt_is_recorded_indeterminate_and_built_again() { image_id: None, image_bytes: None, base_pins: BTreeMap::new(), + base_image_ids: BTreeSet::new(), declaration: None, sequence: None, }; @@ -1438,6 +1440,18 @@ impl reclaim::ReclaimPool for FakePool { ) .collect()) } + fn base_images(&self, _: &()) -> Result, CandidateError> { + Ok(self + .images + .borrow() + .iter() + .filter_map(|(tag, image)| { + let id = image["Id"].as_str()?; + (aliases::keeper(id).as_deref() == Some(tag)) + .then(|| serde_json::json!({"Id": id, "RepoTags": [tag]})) + }) + .collect()) + } fn remove(&self, _: &(), image: &str) -> Result { let allowed = self.removable.borrow().get(image).copied().unwrap_or(true); if allowed { @@ -1543,6 +1557,7 @@ fn the_key_is_version_two_and_version_one_receipts_are_never_reused() { image_id: Some(IMAGE.into()), image_bytes: None, base_pins: BTreeMap::new(), + base_image_ids: BTreeSet::new(), declaration: None, sequence: None, }; @@ -2094,3 +2109,42 @@ fn a_verified_base_selects_the_build_key_and_only_a_local_worker_source() { ); assert!(pool.inspect(&(), PIN).unwrap().is_some()); } + +#[test] +fn reclaim_keeps_only_two_of_ten_base_keepers_for_one_build() { + let fixture = Fixture::new(); + let inputs = fixture.inputs(Policy::Missing); + let pool = FakePool::new("pool-1"); + pool.built(&inputs, "pool-1", serde_json::json!({})); + fixture.client(&inputs, "ok"); + run(&fixture.candidate, &pool, &inputs, &never).unwrap(); + let receipt = fixture.receipt(&inputs); + let directory = builds_root(&fixture.candidate).join(&inputs.namespace); + + for revision in 1..=10 { + let mut receipt = receipt.clone(); + receipt.sequence = Some(revision + 1); + receipt.build_key = format!("{revision:064x}"); + let base = format!("sha256:{revision:064x}"); + receipt.base_image_ids.insert(base.clone()); + pool.images.borrow_mut().insert( + aliases::keeper(&base).unwrap(), + serde_json::json!({"Id": base}), + ); + state::write( + &directory.join(format!("{}.json", receipt.build_key)), + &receipt, + ) + .unwrap(); + } + reclaim::run(&fixture.candidate, &pool).unwrap(); + use reclaim::ReclaimPool; + let kept = pool.base_images(&()).unwrap(); + assert_eq!(kept.len(), 2); + for revision in [9, 10] { + assert!( + kept.iter() + .any(|image| image["Id"] == format!("sha256:{revision:064x}")) + ); + } +} From d804ea3acc2f601a368295eb0caac479a05cebfd Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:03:16 +0000 Subject: [PATCH 20/33] fix: use the remaining build budget for base acquisition --- .../runtime-core/src/provider/image_build.rs | 27 ++++++++++++++----- .../src/provider/image_build/reclaim.rs | 16 +++++++++-- .../runtime-core/src/provider/image_ensure.rs | 15 +++++++---- .../runtime-core/src/provider/image_load.rs | 6 +++-- .../runtime-core/src/provider/image_policy.rs | 21 ++++++++++++++- .../src/provider/image_tag_store.rs | 5 ++-- .../src/provider/registry_image.rs | 15 ++++++----- .../src/provider/registry_image_test.rs | 2 +- 8 files changed, 81 insertions(+), 26 deletions(-) diff --git a/packages/runtime-core/src/provider/image_build.rs b/packages/runtime-core/src/provider/image_build.rs index f641c631c..8a3c9ea61 100644 --- a/packages/runtime-core/src/provider/image_build.rs +++ b/packages/runtime-core/src/provider/image_build.rs @@ -1704,15 +1704,26 @@ fn stop_group(child: &mut Child) -> Result<(), CandidateError> { /// The live pool: the candidate's running provider and its pinned builder. struct LivePool<'a> { candidate: &'a Candidate, + build_deadline: Option, } #[cfg(target_os = "macos")] -fn connect(candidate: &Candidate) -> Result, CandidateError> { - super::engine::Engine::connect_until(candidate, Instant::now() + LEASE_WAIT, || false) +fn connect( + candidate: &Candidate, + deadline: Option, +) -> Result, CandidateError> { + super::engine::Engine::connect_until( + candidate, + deadline.unwrap_or_else(|| Instant::now() + LEASE_WAIT), + || CANCEL_REQUESTED.load(Ordering::Acquire), + ) } #[cfg(not(target_os = "macos"))] -fn connect(candidate: &Candidate) -> Result, CandidateError> { - let _ = LEASE_WAIT; +fn connect( + candidate: &Candidate, + deadline: Option, +) -> Result, CandidateError> { + let _ = (LEASE_WAIT, deadline); super::engine::Engine::connect(candidate) } @@ -1768,7 +1779,7 @@ fn verify_build_network(engine: &super::engine::Engine<'_>) -> Result<(), Candid impl<'a> BuildPool for LivePool<'a> { type Lease = super::engine::Engine<'a>; fn lease(&self) -> Result<(Self::Lease, PoolIdentity), CandidateError> { - let engine = connect(self.candidate)?; + let engine = connect(self.candidate, self.build_deadline)?; verify_build_network(&engine)?; let info = engine.request(reqwest::Method::GET, "/v1.53/info", None)?; let engine_id = info["ID"] @@ -1958,7 +1969,11 @@ pub fn build_image(candidate: &Candidate, request: &Path) -> Result String { /// `runtime reclaim-build-images`: see the module documentation. pub fn reclaim_build_images(candidate: &Candidate) -> Result { - run(candidate, &LivePool { candidate }) + run( + candidate, + &LivePool { + candidate, + build_deadline: None, + }, + ) } /// Why a best-effort reclamation removed nothing. @@ -493,7 +499,13 @@ pub(super) fn best_effort(candidate: &Candidate, pool: &P) -> Be /// `runtime reclaim-build-images --best-effort`: see [`best_effort`]. pub fn reclaim_build_images_best_effort(candidate: &Candidate) -> BestEffortReport { - best_effort(candidate, &LivePool { candidate }) + best_effort( + candidate, + &LivePool { + candidate, + build_deadline: None, + }, + ) } #[cfg(test)] diff --git a/packages/runtime-core/src/provider/image_ensure.rs b/packages/runtime-core/src/provider/image_ensure.rs index dc19d51dc..07ab7675d 100644 --- a/packages/runtime-core/src/provider/image_ensure.rs +++ b/packages/runtime-core/src/provider/image_ensure.rs @@ -64,10 +64,15 @@ impl ImageCache { } } - fn enter(&self, root: &Path) -> Result, CandidateError> { + fn enter( + &self, + root: &Path, + policy: &ImagePolicy, + ) -> Result, CandidateError> { let mut cache = self.state.lock().unwrap(); if cache.lease.is_none() { - let lease = lifecycle::startup_lease(root, lifecycle::STARTUP_LEASE_WAIT)?; + let lease = + lifecycle::startup_lease(root, policy.image_wait(lifecycle::STARTUP_LEASE_WAIT)?)?; let staging = root.with_file_name("image-staging"); if staging.try_exists().map_err(state::io)? { clean_staging(&staging, 0)?; @@ -956,7 +961,7 @@ fn ensure_pinned_coordinated( .or_default() .clone(); let _pin = pin.lock().unwrap(); - let mut state = coordinator.enter(&root)?; + let mut state = coordinator.enter(&root, policy)?; let inventory = || measure(Step::ImageCacheInventory, None, |_| usage(candidate, &root)); let mut occupied = inventory()?; // A cached entry is reused only for the platform the pinned image itself selects under @@ -1047,7 +1052,7 @@ fn ensure_pinned_coordinated( } state::write(&dir.join("receipt.json"), &receipt)?; inspect_entry(candidate, dir, &reference, acquired.platform)?; - let state = coordinator.enter(&root)?; + let state = coordinator.enter(&root, policy)?; let target = root.join(entry_key(&reference, acquired.platform)); if target.try_exists().map_err(state::io)? { return Err(refused( @@ -1280,7 +1285,7 @@ mod tests { state::private_directory(&staged).unwrap(); fs::write(staged.join(".hack-image-1-0.tmp"), b"fixture").unwrap(); let coordinator = ImageCache::default(); - let _cache = coordinator.enter(&root).unwrap(); + let _cache = coordinator.enter(&root, &ImagePolicy::default()).unwrap(); assert!(!staged.exists()); assert_eq!(usage(&f.1, &root).unwrap(), (0, 0)); } diff --git a/packages/runtime-core/src/provider/image_load.rs b/packages/runtime-core/src/provider/image_load.rs index 5029b8d58..7174ae0fd 100644 --- a/packages/runtime-core/src/provider/image_load.rs +++ b/packages/runtime-core/src/provider/image_load.rs @@ -755,7 +755,7 @@ pub(super) fn load_cached( resolved_config, |file| { let engine = measure(Step::ImageImportConnect, None, |_| { - connect_for_import(candidate, IMPORT_LEASE_WAIT) + connect_for_import(candidate, policy.image_wait(IMPORT_LEASE_WAIT)?) })?; import(candidate, archive, Some(archive.pin), policy, file, &engine) }, @@ -999,10 +999,12 @@ fn import( let upload = file .try_clone() .map_err(|_| error("Cannot read the image archive."))?; + let timeout = load_timeout(length); + let timeout = policy.image_wait(timeout)?.min(timeout); state::write(&path, &receipt)?; let result = engine.load_archive( reqwest::blocking::Body::sized(HeldTail::new(upload, &validated, expected_sha), length), - load_timeout(length), + timeout, ); // A lost response is reconciled only by independent content-ID readback. if !present()? { diff --git a/packages/runtime-core/src/provider/image_policy.rs b/packages/runtime-core/src/provider/image_policy.rs index 8147a90a4..1b4ce2a69 100644 --- a/packages/runtime-core/src/provider/image_policy.rs +++ b/packages/runtime-core/src/provider/image_policy.rs @@ -6,7 +6,10 @@ //! Budgets are configurable within fixed hard ceilings, so a policy can relax the //! defaults for large development images but never remove the bound. use crate::CandidateError; -use std::path::PathBuf; +use std::{ + path::PathBuf, + time::{Duration, Instant}, +}; const MIB: u64 = 1024 * 1024; /// Default compressed archive budget for one image: fits ordinary language and database @@ -64,6 +67,7 @@ pub struct ImagePolicy { /// Override the ordinary tag lookup for an explicit refresh or an offline command. pub tag_mode: ImageTagMode, pub(crate) short_tag_refresh: bool, + pub(crate) build_deadline: Option, pub(crate) command_image_pin: Option, /// Registries that are refused as local unless named here. pub local_registries: Vec, @@ -86,6 +90,7 @@ impl Default for ImagePolicy { tag_ttl_seconds: DEFAULT_TAG_TTL_SECONDS, tag_mode: ImageTagMode::Normal, short_tag_refresh: false, + build_deadline: None, command_image_pin: None, local_registries: Vec::new(), docker_config: None, @@ -108,6 +113,20 @@ fn mebibytes(value: &str, min: u64, max: u64) -> Result { } impl ImagePolicy { + pub(super) fn image_wait(&self, default: Duration) -> Result { + match self.build_deadline { + Some(deadline) => deadline + .checked_duration_since(Instant::now()) + .ok_or_else(|| { + CandidateError::new( + "native_build_timeout", + "The image build exceeded its time budget.", + ) + }), + None => Ok(default), + } + } + /// The local registry opt-in for `domain`, if any. pub fn local_registry(&self, domain: &str) -> Option<&LocalRegistry> { self.local_registries.iter().find(|r| r.domain == domain) diff --git a/packages/runtime-core/src/provider/image_tag_store.rs b/packages/runtime-core/src/provider/image_tag_store.rs index 772c25c2a..d6725c44a 100644 --- a/packages/runtime-core/src/provider/image_tag_store.rs +++ b/packages/runtime-core/src/provider/image_tag_store.rs @@ -430,8 +430,9 @@ fn resolve_pending( "1" => eprintln!("hack.image-wait:begin"), _ => (), } - let lock = - state::Lock::acquire_existing_waiting(&root, std::time::Duration::from_secs(590)); + let lock = policy + .image_wait(std::time::Duration::from_secs(590)) + .and_then(|wait| state::Lock::acquire_existing_waiting(&root, wait)); match report_wait.as_str() { "batch" => eprintln!("hack.image-wait:end {canonical}"), "1" => eprintln!("hack.image-wait:end"), diff --git a/packages/runtime-core/src/provider/registry_image.rs b/packages/runtime-core/src/provider/registry_image.rs index 05fcff0b0..d8bb5be4d 100644 --- a/packages/runtime-core/src/provider/registry_image.rs +++ b/packages/runtime-core/src/provider/registry_image.rs @@ -891,6 +891,12 @@ impl<'a> Fetch<'a> { .connect_timeout(Duration::from_secs(10)) .build() .map_err(|_| error("Cannot initialize registry TLS client."))?; + let wait = policy.image_wait(ACQUISITION_DEADLINE)?; + let wait = if policy.short_tag_refresh { + wait.min(Duration::from_secs(3)) + } else { + wait + }; Ok(Self { client, registry: registry.clone(), @@ -898,12 +904,7 @@ impl<'a> Fetch<'a> { policy, authorization: None, stage: Stage::Anonymous, - deadline: Instant::now() - + if policy.short_tag_refresh { - Duration::from_secs(3) - } else { - ACQUISITION_DEADLINE - }, + deadline: Instant::now() + wait, request_timeout: REQUEST_TIMEOUT, }) } @@ -1516,7 +1517,7 @@ fn layer_failure( "the registry answered an error status".to_owned() } (NetworkFailureReason::Deadline, _) => { - "the 360-second image deadline was reached".to_owned() + "the image acquisition deadline was reached".to_owned() } }; let failure = error(format!( diff --git a/packages/runtime-core/src/provider/registry_image_test.rs b/packages/runtime-core/src/provider/registry_image_test.rs index b7471c5ec..bcbb9adab 100644 --- a/packages/runtime-core/src/provider/registry_image_test.rs +++ b/packages/runtime-core/src/provider/registry_image_test.rs @@ -2529,7 +2529,7 @@ fn the_deadline_reached_mid_retry_ends_the_layer_without_extending_it() { serde_json::json!({"version": 2, "host": "127.0.0.1", "attempts": 2, "reason": "deadline"}) ); assert!( - failure.message.contains("360-second image deadline"), + failure.message.contains("image acquisition deadline"), "{}", failure.message ); From 2729139f2789e924bc775d32115f35cdcca3f5a4 Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:13:12 +0000 Subject: [PATCH 21/33] test: exercise native build base acquisition and recovery --- docs/reference/v5-model-coverage.md | 2 +- .../runtime-core/src/provider/image_build.rs | 300 +++++++---------- .../src/provider/image_build/reclaim.rs | 2 +- .../src/provider/image_build/tests.rs | 301 ++++++++++++------ .../src/provider/registry_image.rs | 49 --- .../src/provider/registry_image_test.rs | 16 - scripts/lib/tla-runtime-models.ts | 9 +- src/backends/native-image-tags.ts | 49 ++- src/backends/native-project-builds.ts | 19 +- .../native-project-restart-preflight.ts | 10 + tests/models/tla/README.md | 39 ++- .../tla/native-build-alias/BuildAlias.tla | 49 ++- .../tla/native-build-alias/build-alias.mmd | 31 ++ .../tla/native-build-alias/build-alias.svg | 66 ++++ .../tla/native-build-alias/negative.cfg | 4 +- .../tla/native-build-alias/old-order.cfg | 4 + .../tla/native-build-alias/positive.cfg | 4 +- .../tla/native-build-alias/unsafe-remote.cfg | 4 +- .../tla/native-build-alias/unsafe-sweep.cfg | 4 +- tests/native-image-tags.test.ts | 70 +++- tests/native-project-builds.test.ts | 96 ++++++ 21 files changed, 719 insertions(+), 409 deletions(-) create mode 100644 tests/models/tla/native-build-alias/build-alias.mmd create mode 100644 tests/models/tla/native-build-alias/build-alias.svg create mode 100644 tests/models/tla/native-build-alias/old-order.cfg diff --git a/docs/reference/v5-model-coverage.md b/docs/reference/v5-model-coverage.md index c83824cf2..c95ef263a 100644 --- a/docs/reference/v5-model-coverage.md +++ b/docs/reference/v5-model-coverage.md @@ -152,7 +152,7 @@ liveness/reachability controls have their own documented assumptions. | [native-pool-stop](../../tests/models/tla/native-pool-stop/PoolStop.tla) | 210 | 10 | | [start-graph](../../tests/models/tla/start-graph/COVERAGE.md) | 1,656,372 + 81,534 two-boot | 10 | | [probe-readiness](../../tests/models/tla/probe-readiness/ProbeReadiness.tla) | 175,757 | 7 | -| [native-build-alias](../../tests/models/tla/native-build-alias/BuildAlias.tla) | 9 | 4 | +| [native-build-alias](../../tests/models/tla/native-build-alias/BuildAlias.tla) | 23 | 5 | | [native-build-retention](../../tests/models/tla/native-build-retention/BuildRetention.tla) | 6,181 | 4 | | [runtime-service](../../tests/models/tla/runtime-service/RuntimeService.tla) | 1,006,849 | 11 | | [shared-helper-instance](../../tests/models/tla/shared-helper-instance/Instance.tla) | 7,649 | 11 | diff --git a/packages/runtime-core/src/provider/image_build.rs b/packages/runtime-core/src/provider/image_build.rs index 8a3c9ea61..18fa38fed 100644 --- a/packages/runtime-core/src/provider/image_build.rs +++ b/packages/runtime-core/src/provider/image_build.rs @@ -272,20 +272,8 @@ pub(super) trait BuildPool { fn lease(&self) -> Result<(Self::Lease, PoolIdentity), CandidateError>; /// Inspect one image by content ID or tag; `None` when the engine reports it absent. fn inspect(&self, lease: &Self::Lease, image: &str) -> Result, CandidateError>; - /// Resolve one base image to its pinned manifest. Network only; no lease is held. - /// Returns, with an error, by `deadline` or soon after `canceled` reports true. - fn resolve( - &self, - base: &BaseImage, - deadline: Instant, - canceled: &dyn Fn() -> bool, - ) -> Result; - fn tag_base(&self, _: &Self::Lease, _: &str, _: &str) -> Result<(), CandidateError> { - unreachable!("only live builds use aliases") - } - fn untag_base(&self, _: &Self::Lease, _: &str) -> Result<(), CandidateError> { - unreachable!("only live builds use aliases") - } + fn tag_base(&self, lease: &Self::Lease, id: &str, tag: &str) -> Result<(), CandidateError>; + fn untag_base(&self, lease: &Self::Lease, tag: &str) -> Result<(), CandidateError>; /// The verified builder executable. fn builder(&self) -> Result; /// Where the client's filtered output goes. @@ -898,33 +886,12 @@ fn reuse_legacy( Ok(outcome) } -/// Run one build operation end to end. See the module documentation for the protocol. -/// `canceled` reports a pending cancellation request; it is checked before each -/// unleased step, during base resolution and while the client runs. The time budget -/// starts here: base resolution and the client share it. -#[cfg(test)] -pub(super) fn run( - candidate: &Candidate, - pool: &P, - inputs: &Inputs, - canceled: &dyn Fn() -> bool, -) -> Result { - run_with_bases( - candidate, - pool, - inputs, - canceled, - None, - Instant::now() + inputs.timeout, - ) -} - fn run_with_bases( candidate: &Candidate, pool: &P, inputs: &Inputs, canceled: &dyn Fn() -> bool, - selected: Option<&BTreeMap>, + selected: &BTreeMap, deadline: Instant, ) -> Result { let canceled_early = || { @@ -1001,51 +968,17 @@ fn run_with_bases( state::write(&receipt_path, &dead)?; } } - if selected.is_some() { - aliases::sweep_stranded(&root, pool, &lease, &identity, &alias_path); - aliases::sweep(pool, &lease, &identity, &alias_path)?; - } + aliases::sweep_stranded(&root, pool, &lease, &identity, &alias_path); + aliases::sweep(pool, &lease, &identity, &alias_path)?; let previous_bytes = previous.as_ref().and_then(|receipt| receipt.image_bytes); drop(lease); // Snapshots other attempts in this namespace stranded when they were killed. remove_stranded_snapshots(&directory); - // Step 2, unleased: resolve every base image to a pinned manifest. - let pins = if let Some(selected) = selected { - selected - .iter() - .map(|(name, base)| (name.clone(), base.pinned_reference.clone())) - .collect() - } else { - let mut pins = BTreeMap::new(); - for base in &inputs.images { - if canceled() { - return Err(canceled_early()); - } - if Instant::now() >= deadline { - return Err(expired_early()); - } - let resolved = pool.resolve(base, deadline, canceled).map_err(|error| { - if error.code.starts_with("registry_") && error.cause_code.is_some() { - error.with_build_base_reference(base.reference.canonical()) - } else { - error - } - })?; - if !image_id(&resolved.source_digest) - || !resolved - .pinned_reference - .ends_with(&format!("@{}", resolved.source_digest)) - { - return Err(refusal( - "native_build_base_image", - "A build base image did not resolve to a pinned manifest.", - )); - } - pins.insert(base.context_name.clone(), resolved.pinned_reference); - } - pins - }; + let pins: BTreeMap<_, _> = selected + .iter() + .map(|(name, base)| (name.clone(), base.pinned_reference.clone())) + .collect(); let builder = pool.builder()?; if canceled() { return Err(canceled_early()); @@ -1106,21 +1039,16 @@ fn run_with_bases( image_bytes: previous_bytes, base_pins: pins.clone(), base_image_ids: selected - .into_iter() - .flat_map(|bases| bases.values().map(|base| base.image_id.clone())) + .values() + .map(|base| base.image_id.clone()) .collect(), declaration: Some(inputs.declaration.clone()), // Kept from the last verified image of this key until this attempt verifies. sequence: previous.as_ref().and_then(|receipt| receipt.sequence), }; state::write(&receipt_path, &receipt)?; - let (aliases, worker_pins) = if let Some(bases) = selected { - let (aliases, contexts) = - aliases::Aliases::prepare(pool, &lease, &identity, alias_path, bases)?; - (Some(aliases), contexts) - } else { - (None, pins.clone()) - }; + let (aliases, worker_pins) = + aliases::Aliases::prepare(pool, &lease, &identity, alias_path, selected)?; drop(lease); // Step 4, unleased: run the client in its own process group. @@ -1808,19 +1736,6 @@ impl<'a> BuildPool for LivePool<'a> { Err(error) => Err(error), } } - fn resolve( - &self, - base: &BaseImage, - deadline: Instant, - canceled: &dyn Fn() -> bool, - ) -> Result { - let reference = base.reference.clone(); - interruptible( - move || registry_image::resolve_build_base(&reference, deadline), - deadline, - canceled, - ) - } fn tag_base( &self, lease: &Self::Lease, @@ -1899,44 +1814,6 @@ pub(super) fn prune_build_cache( }) } -/// Run a blocking, effect-free network step on its own thread and wait for it until -/// `deadline` or a cancellation request. An abandoned step ends by its own deadline; -/// its result is discarded and it changes no local state. -fn interruptible( - step: impl FnOnce() -> Result + Send + 'static, - deadline: Instant, - canceled: &dyn Fn() -> bool, -) -> Result { - let (sender, result) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let _ = sender.send(step()); - }); - loop { - match result.recv_timeout(POLL) { - Ok(outcome) => return outcome, - Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => { - return Err(refusal( - "native_build_base_image", - "Base-image resolution ended without a result.", - )); - } - Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} - } - if canceled() { - return Err(refusal( - "native_build_canceled", - "The image build was canceled before the build client started; no image was adopted.", - )); - } - if Instant::now() >= deadline { - return Err(refusal( - "native_build_timeout", - "The image build exceeded its time budget before the build client started; no image was adopted.", - )); - } - } -} - fn key_with_bases( key: &str, selected: &BTreeMap, @@ -1953,6 +1830,80 @@ fn key_with_bases( .map_err(|_| invalid("Cannot encode the build key.")) } +type EnsuredBase = (BuildBase, Option); + +fn ensure_build_base( + candidate: &Candidate, + reference: &str, + policy: &super::image_policy::ImagePolicy, +) -> Result { + let ensured = super::image_ensure::ensure(candidate, reference, policy)?; + let proof = super::image_ensure::recorded_proof( + candidate, + &ensured.pinned_reference, + super::image_platform::PlatformPolicy::Native, + )? + .ok_or_else(|| { + refusal( + "native_build_base_image", + "The verified base proof is missing.", + ) + })?; + let resolved = proof.verified_build_base(&ensured.pinned_reference, policy.archive_limit)?; + if resolved.image_id != ensured.image_id { + return Err(refusal( + "native_build_base_image", + "The build base proof differs from the loaded image.", + )); + } + Ok((resolved, ensured.tag_resolution)) +} + +struct BaseSelections { + selected: BTreeMap, + fallbacks: Vec, + selections: BTreeMap, +} + +fn acquire_bases( + inputs: &Inputs, + prior_pins: &BTreeMap, + mut policy: super::image_policy::ImagePolicy, + mut ensure: impl FnMut( + &str, + &super::image_policy::ImagePolicy, + ) -> Result, + deadline: Instant, +) -> Result { + let mut selected = BTreeMap::new(); + let mut fallbacks = Vec::new(); + let mut selections = BTreeMap::new(); + for base in &inputs.images { + if Instant::now() >= deadline { + return Err(late_stop(false)); + } + let reference = base.reference.canonical(); + policy.command_image_pin = prior_pins + .get(&reference) + .map(|pin| registry_image::pinned_syntax(pin).map(|(canonical, _)| canonical)) + .transpose()?; + let (resolved, tag) = ensure(&reference, &policy) + .map_err(|error| error.with_build_base_reference(reference.clone()))?; + if let Some(tag) = tag + && tag.source == super::image_tag_store::TagSource::Offline + { + fallbacks.push(tag); + } + selections.insert(reference, resolved.pinned_reference.clone()); + selected.insert(base.context_name.clone(), resolved); + } + Ok(BaseSelections { + selected, + fallbacks, + selections, + }) +} + /// `runtime build-image --request `: build or reuse one native image. pub fn build_image(candidate: &Candidate, request: &Path) -> Result { let request: BuildRequest = state::read_bounded(request, MAX_REQUEST_BYTES)?; @@ -1987,56 +1938,28 @@ pub fn build_image(candidate: &Candidate, request: &Path) -> Result= deadline { - return Err(late_stop(false)); - } - let reference = base.reference.canonical(); - policy.command_image_pin = prior_pins - .get(&reference) - .map(|pin| registry_image::pinned_syntax(pin).map(|(canonical, _)| canonical)) - .transpose()?; - let ensured = match super::image_ensure::ensure(candidate, &reference, &policy) { - Ok(ensured) => ensured, - Err(error) => { - if error.code.starts_with("registry_") - && let Some(outcome) = reuse_legacy(candidate, &pool, &inputs)? - { - return Ok(outcome); - } - return Err(error.with_build_base_reference(reference)); + let BaseSelections { + selected, + fallbacks, + selections, + } = match acquire_bases( + &inputs, + &prior_pins, + policy, + |reference, policy| ensure_build_base(candidate, reference, policy), + deadline, + ) { + Ok(bases) => bases, + Err(error) => { + if Instant::now() < deadline + && error.code.starts_with("registry_") + && let Some(outcome) = reuse_legacy(candidate, &pool, &inputs)? + { + return Ok(outcome); } - }; - let proof = super::image_ensure::recorded_proof( - candidate, - &ensured.pinned_reference, - super::image_platform::PlatformPolicy::Native, - )? - .ok_or_else(|| { - refusal( - "native_build_base_image", - "The verified base proof is missing.", - ) - })?; - let resolved = - proof.verified_build_base(&ensured.pinned_reference, policy.archive_limit)?; - if resolved.image_id != ensured.image_id { - return Err(refusal( - "native_build_base_image", - "The build base proof differs from the loaded image.", - )); - } - if let Some(tag) = ensured.tag_resolution - && tag.source == super::image_tag_store::TagSource::Offline - { - fallbacks.push(tag); + return Err(error); } - selections.insert(reference, resolved.pinned_reference.clone()); - selected.insert(base.context_name.clone(), resolved); - } + }; // Acquisition keeps the default signal dispositions, like ensure-image. // Exit releases its locks and the next cache writer recovers private // staging. No BuildKit client, temporary base alias or build receipt @@ -2044,14 +1967,7 @@ pub fn build_image(candidate: &Candidate, request: &Path) -> Result>, images: RefCell>, leases: RefCell, - resolve_error: bool, available: RefCell, prunes: RefCell>, - resolve_delay: Duration, - resolve_deadlines: RefCell>, output: Arc>>, /// Verify the image builder in this home before use, as the real pool does. builder_home: Option, + unavailable: std::cell::Cell, } impl FakePool { fn new(incarnation: &str) -> Self { @@ -176,13 +175,11 @@ impl FakePool { identities: RefCell::new(vec![identity(incarnation)]), images: RefCell::new(BTreeMap::new()), leases: RefCell::new(0), - resolve_error: false, available: RefCell::new(64 * GIB), prunes: RefCell::new(Vec::new()), - resolve_delay: Duration::ZERO, - resolve_deadlines: RefCell::new(Vec::new()), output: Arc::default(), builder_home: None, + unavailable: std::cell::Cell::new(false), } } /// Register `id` as the image the fake client in mode `given` "builds" for `inputs`. @@ -210,6 +207,9 @@ impl FakePool { impl BuildPool for FakePool { type Lease = (); fn lease(&self) -> Result<((), PoolIdentity), CandidateError> { + if self.unavailable.get() { + return Err(refusal("provider_busy", "Fake provider lease unavailable.")); + } *self.leases.borrow_mut() += 1; let mut identities = self.identities.borrow_mut(); let current = if identities.len() > 1 { @@ -222,23 +222,6 @@ impl BuildPool for FakePool { fn inspect(&self, _: &(), image: &str) -> Result, CandidateError> { Ok(self.images.borrow().get(image).cloned()) } - fn resolve( - &self, - base: &BaseImage, - deadline: Instant, - _: &dyn Fn() -> bool, - ) -> Result { - self.resolve_deadlines.borrow_mut().push(deadline); - std::thread::sleep(self.resolve_delay); - if self.resolve_error { - return Err(CandidateError::new("registry_image", "offline")); - } - Ok(BuildBase { - pinned_reference: format!("docker.io/{}@{PIN}", base.repository()), - source_digest: PIN.into(), - image_id: IMAGE.into(), - }) - } fn tag_base(&self, _: &(), id: &str, tag: &str) -> Result<(), CandidateError> { let mut images = self.images.borrow_mut(); let image = images @@ -295,6 +278,40 @@ fn never() -> bool { false } +fn run( + candidate: &Candidate, + pool: &FakePool, + inputs: &Inputs, + canceled: &dyn Fn() -> bool, +) -> Result { + const BASE_ID: &str = "sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; + pool.images + .borrow_mut() + .insert(BASE_ID.into(), serde_json::json!({"Id": BASE_ID})); + let selected = inputs + .images + .iter() + .map(|base| { + ( + base.context_name.clone(), + BuildBase { + pinned_reference: format!("docker.io/{}@{PIN}", base.repository()), + source_digest: PIN.into(), + image_id: BASE_ID.into(), + }, + ) + }) + .collect(); + run_with_bases( + candidate, + pool, + inputs, + canceled, + &selected, + Instant::now() + inputs.timeout, + ) +} + #[test] fn cold_build_passes_values_only_through_the_private_definition_and_records_the_result() { let fixture = Fixture::new(); @@ -348,12 +365,12 @@ fn cold_build_passes_values_only_through_the_private_definition_and_records_the_ serde_json::from_slice(&fs::read(scratch.join("seen-bake.json")).unwrap()).unwrap(); let target = &bake["target"]["build"]; assert_eq!(target["args"], serde_json::json!({"GREETING": SECRET})); - assert_eq!( - target["contexts"], - serde_json::json!({ - "alpine:3.20": format!("docker-image://docker.io/library/alpine@{PIN}") - }) - ); + let alias = target["contexts"]["alpine:3.20"] + .as_str() + .unwrap() + .strip_prefix("docker-image://") + .unwrap(); + assert!(aliases::allowed(alias)); assert_eq!(target["platforms"], serde_json::json!(["linux/arm64"])); assert_eq!(target["output"], serde_json::json!(["type=docker"])); assert_eq!(target["labels"]["io.hack-local.kind"], "build-image"); @@ -367,10 +384,9 @@ fn cold_build_passes_values_only_through_the_private_definition_and_records_the_ assert!(!policy_path.exists(), "the source policy outlived the run"); let policy: Value = serde_json::from_slice(&fs::read(scratch.join("seen-policy.json")).unwrap()).unwrap(); - let pinned = format!("docker.io/library/alpine@{PIN}"); - assert_eq!(policy, build_policy::document([pinned.as_str()]).unwrap()); + assert_eq!(policy, build_policy::build_document([alias]).unwrap()); assert_eq!( - policy_decision(&policy, &format!("docker-image://{pinned}")), + policy_decision(&policy, &format!("docker-image://{alias}")), "ALLOW" ); for denied in [ @@ -798,44 +814,6 @@ fn the_client_builds_the_scanned_dockerfile_and_ignore_rules_not_later_edits() { ); } -#[test] -fn the_time_budget_starts_before_base_resolution() { - let fixture = Fixture::new(); - let mut inputs = fixture.inputs(Policy::Missing); - inputs.timeout = Duration::from_millis(300); - let mut pool = FakePool::new("pool-1"); - pool.resolve_delay = Duration::from_millis(400); - fixture.client(&inputs, "ok"); - pool.built(&inputs, "pool-1", serde_json::json!({})); - let started = Instant::now(); - let error = run(&fixture.candidate, &pool, &inputs, &never).unwrap_err(); - let finished = Instant::now(); - assert_eq!(error.code, "native_build_timeout"); - assert_eq!(fixture.calls(&inputs), 0, "the client ran after the budget"); - // Resolution got the operation's deadline, which had passed when it returned. - let deadlines = pool.resolve_deadlines.borrow(); - assert_eq!(deadlines.len(), 1); - assert!(deadlines[0] >= started + inputs.timeout && deadlines[0] < finished); -} - -#[test] -fn blocking_resolution_yields_to_the_deadline_and_to_cancellation() { - let slow = || { - std::thread::sleep(Duration::from_secs(3)); - Ok(()) - }; - let started = Instant::now(); - let error = interruptible(slow, started + Duration::from_millis(100), &never).unwrap_err(); - assert_eq!(error.code, "native_build_timeout"); - let error = interruptible(slow, started + Duration::from_secs(60), &|| true).unwrap_err(); - assert_eq!(error.code, "native_build_canceled"); - assert!(started.elapsed() < Duration::from_secs(2)); - assert_eq!( - interruptible(|| Ok(7), Instant::now() + Duration::from_secs(5), &never).unwrap(), - 7 - ); -} - #[test] fn verified_image_is_reused_without_running_the_client() { let fixture = Fixture::new(); @@ -1113,22 +1091,6 @@ fn the_key_lock_and_the_down_fence_refuse_instead_of_waiting() { assert!(require_no_active_build(&fixture.candidate).is_ok()); } -#[test] -fn base_resolution_failures_run_nothing() { - let fixture = Fixture::new(); - let inputs = fixture.inputs(Policy::Missing); - fixture.client(&inputs, "ok"); - let mut pool = FakePool::new("pool-1"); - pool.resolve_error = true; - assert_eq!( - run(&fixture.candidate, &pool, &inputs, &never) - .unwrap_err() - .code, - "registry_image" - ); - assert_eq!(fixture.calls(&inputs), 0); -} - #[test] fn a_home_without_the_image_builder_refuses_by_name_and_runs_nothing() { let fixture = Fixture::new(); @@ -1435,6 +1397,7 @@ impl reclaim::ReclaimPool for FakePool { .images .borrow() .values() + .filter(|image| !image["Config"]["Labels"].is_null()) .map( |image| serde_json::json!({"Id": image["Id"], "Labels": image["Config"]["Labels"]}), ) @@ -1790,7 +1753,7 @@ fn ten_edits_of_one_build_leave_its_current_and_previous_images() { } keys.dedup(); assert_eq!(keys.len(), 10, "every edit had its own key"); - assert_eq!(pool.images.borrow().len(), 10); + assert_eq!(pool.build_images(&()).unwrap().len(), 10); // A retained run still references the image of edit 3. Its restore history names // the images of edits 2 to 8, as eight stopped generations would; history is // diagnostic, so those are not references (HACK-2554). @@ -1808,7 +1771,12 @@ fn ten_edits_of_one_build_leave_its_current_and_previous_images() { ) .unwrap(); let report = reclaim::run(&fixture.candidate, &pool).unwrap(); - let left: BTreeSet = pool.images.borrow().keys().cloned().collect(); + let left: BTreeSet = pool + .build_images(&()) + .unwrap() + .iter() + .map(|image| image["Id"].as_str().unwrap().to_owned()) + .collect(); assert_eq!( left, BTreeSet::from([numbered(3), numbered(9), numbered(10)]) @@ -1821,7 +1789,12 @@ fn ten_edits_of_one_build_leave_its_current_and_previous_images() { // Without the reference, exactly the current and previous images remain. fs::remove_dir_all(fixture.candidate.state_root.join("run/graphs")).unwrap(); reclaim::run(&fixture.candidate, &pool).unwrap(); - let left: BTreeSet = pool.images.borrow().keys().cloned().collect(); + let left: BTreeSet = pool + .build_images(&()) + .unwrap() + .iter() + .map(|image| image["Id"].as_str().unwrap().to_owned()) + .collect(); assert_eq!(left, BTreeSet::from([numbered(9), numbered(10)])); // Reverting to edit 9 reuses it and makes it current; edit 10 becomes previous. @@ -1837,7 +1810,12 @@ fn ten_edits_of_one_build_leave_its_current_and_previous_images() { build_as(&fixture, &pool, &eleventh, &numbered(11)); let report = reclaim::run(&fixture.candidate, &pool).unwrap(); assert_eq!(report.removed, vec![numbered(10)]); - let left: BTreeSet = pool.images.borrow().keys().cloned().collect(); + let left: BTreeSet = pool + .build_images(&()) + .unwrap() + .iter() + .map(|image| image["Id"].as_str().unwrap().to_owned()) + .collect(); assert_eq!(left, BTreeSet::from([numbered(9), numbered(11)])); } @@ -2077,7 +2055,7 @@ fn a_verified_base_selects_the_build_key_and_only_a_local_worker_source() { &pool, &inputs, &never, - Some(&bases), + &bases, Instant::now() + inputs.timeout, ) .unwrap(); @@ -2085,8 +2063,27 @@ fn a_verified_base_selects_the_build_key_and_only_a_local_worker_source() { outcome.base_pins["alpine:3.20"], format!("docker.io/library/alpine@{PIN}") ); - assert!(pool.resolve_deadlines.borrow().is_empty()); let scratch = fixture.scratch(&inputs); + let journal = scratch.join("base-aliases.json"); + state::write(&journal, &"invalid").unwrap(); + let pending = builds_root(&fixture.candidate) + .join(&inputs.namespace) + .join(format!("{}.pending", inputs.key)); + fs::write(&pending, "unfinished receipt").unwrap(); + assert!( + run_with_bases( + &fixture.candidate, + &pool, + &inputs, + &never, + &bases, + Instant::now() + inputs.timeout, + ) + .unwrap() + .reused + ); + assert!(journal.exists(), "reuse must precede journal inspection"); + assert!(!pending.exists()); let bake: Value = serde_json::from_slice(&fs::read(scratch.join("seen-bake.json")).unwrap()).unwrap(); let reference = bake["target"]["build"]["contexts"]["alpine:3.20"] @@ -2126,7 +2123,7 @@ fn reclaim_keeps_only_two_of_ten_base_keepers_for_one_build() { receipt.sequence = Some(revision + 1); receipt.build_key = format!("{revision:064x}"); let base = format!("sha256:{revision:064x}"); - receipt.base_image_ids.insert(base.clone()); + receipt.base_image_ids = BTreeSet::from([base.clone()]); pool.images.borrow_mut().insert( aliases::keeper(&base).unwrap(), serde_json::json!({"Id": base}), @@ -2138,7 +2135,6 @@ fn reclaim_keeps_only_two_of_ten_base_keepers_for_one_build() { .unwrap(); } reclaim::run(&fixture.candidate, &pool).unwrap(); - use reclaim::ReclaimPool; let kept = pool.base_images(&()).unwrap(); assert_eq!(kept.len(), 2); for revision in [9, 10] { @@ -2148,3 +2144,120 @@ fn reclaim_keeps_only_two_of_ten_base_keepers_for_one_build() { ); } } + +#[test] +fn command_build_pins_are_applied_under_the_requested_acquisition_policy() { + let fixture = Fixture::new(); + let inputs = fixture.inputs(Policy::Missing); + let reference = inputs.images[0].reference.canonical(); + let pin = format!("docker.io/library/alpine@{PIN}"); + let selected = acquire_bases( + &inputs, + &BTreeMap::from([(reference.clone(), pin.clone())]), + super::super::image_policy::ImagePolicy { + tag_mode: super::super::image_policy::ImageTagMode::Offline, + ..Default::default() + }, + |actual, policy| { + assert_eq!(actual, reference); + assert_eq!(policy.command_image_pin.as_deref(), Some(pin.as_str())); + assert_eq!( + policy.tag_mode, + super::super::image_policy::ImageTagMode::Offline + ); + Ok(( + BuildBase { + pinned_reference: pin.clone(), + source_digest: PIN.into(), + image_id: IMAGE.into(), + }, + None, + )) + }, + Instant::now() + inputs.timeout, + ) + .unwrap(); + assert_eq!(selected.selections[&reference], pin); + assert_eq!(selected.selected["alpine:3.20"].image_id, IMAGE); +} + +#[test] +fn aliases_restore_a_keeper_and_quarantine_a_malformed_journal() { + let fixture = Fixture::new(); + let inputs = fixture.inputs(Policy::Missing); + let pool = FakePool::new("pool-1"); + pool.built(&inputs, "pool-1", serde_json::json!({})); + let scratch = fixture.scratch(&inputs); + state::private_directory(&scratch).unwrap(); + let path = scratch.join("base-aliases.json"); + let (_, identity) = pool.lease().unwrap(); + let bases = BTreeMap::from([( + "fixture".into(), + BuildBase { + pinned_reference: format!("docker.io/library/alpine@{PIN}"), + source_digest: PIN.into(), + image_id: IMAGE.into(), + }, + )]); + let keeper = aliases::keeper(IMAGE).unwrap(); + for replacement in [None, Some(serde_json::json!({"Id": PIN}))] { + let (attempt, tags) = + aliases::Aliases::prepare(&pool, &(), &identity, path.clone(), &bases).unwrap(); + pool.images.borrow_mut().remove(&keeper); + if let Some(image) = replacement { + pool.images.borrow_mut().insert(keeper.clone(), image); + } + drop(attempt); + assert!(pool.inspect(&(), &tags["fixture"]).unwrap().is_none()); + assert_eq!(pool.inspect(&(), &keeper).unwrap().unwrap()["Id"], IMAGE); + } + let (attempt, tags) = + aliases::Aliases::prepare(&pool, &(), &identity, path.clone(), &bases).unwrap(); + pool.unavailable.set(true); + drop(attempt); + assert!(path.exists()); + let alias = &tags["fixture"]; + assert!(pool.inspect(&(), alias).unwrap().is_some()); + // A new incarnation discards the old journal without untagging names in the new guest. + aliases::sweep(&pool, &(), &self::identity("replacement"), &path).unwrap(); + assert!(!path.exists()); + assert!(pool.inspect(&(), alias).unwrap().is_some()); + state::write(&path, &"invalid").unwrap(); + aliases::sweep(&pool, &(), &identity, &path).unwrap(); + assert!(!path.exists()); + assert!(fs::read_dir(scratch).unwrap().any(|entry| { + entry + .unwrap() + .file_name() + .to_string_lossy() + .starts_with("base-aliases.invalid-") + })); +} + +#[test] +fn legacy_reuse_requires_the_original_context_and_a_verified_image() { + let fixture = Fixture::new(); + let inputs = fixture.inputs(Policy::Missing); + let pool = FakePool::new("pool-1"); + fixture.client(&inputs, "ok"); + pool.built(&inputs, "pool-1", serde_json::json!({})); + run(&fixture.candidate, &pool, &inputs, &never).unwrap(); + let result = reuse_legacy(&fixture.candidate, &pool, &inputs) + .unwrap() + .unwrap(); + assert!(result.reused && result.reused_legacy_key); + fs::write(fixture.project.join("app/main.txt"), "edited").unwrap(); + let changed = fixture.inputs(Policy::Missing); + assert!( + reuse_legacy(&fixture.candidate, &pool, &changed) + .unwrap() + .is_none() + ); + fs::write(fixture.project.join("app/Dockerfile"), "FROM scratch\n").unwrap(); + let changed = fixture.inputs(Policy::Missing); + assert!( + reuse_legacy(&fixture.candidate, &pool, &changed) + .unwrap() + .is_none() + ); +} diff --git a/packages/runtime-core/src/provider/registry_image.rs b/packages/runtime-core/src/provider/registry_image.rs index d8bb5be4d..274f3c61d 100644 --- a/packages/runtime-core/src/provider/registry_image.rs +++ b/packages/runtime-core/src/provider/registry_image.rs @@ -2041,52 +2041,6 @@ pub struct BuildBase { pub image_id: String, } -/// Resolve one normalized base-image reference for a native build, through the same -/// guarded, origin-bound client and address policy as acquisition. A tag resolves once -/// to its current manifest; a digest-pinned reference must resolve to exactly that pin. -/// Builds stay Docker Hub and Linux ARM64 only (the Dockerfile scan and the build source -/// policy admit nothing else), and the configuration must declare no `ONBUILD` -/// triggers: a stored trigger could pull images the Dockerfile scan never saw. Only -/// bounded metadata is fetched. `deadline` bounds the whole resolution, never beyond -/// the acquisition deadline. -pub fn resolve_build_base( - named: &NamedReference, - deadline: Instant, -) -> Result { - if named.docker_hub_repository().is_none() { - return Err(error( - "Only public Docker Hub [namespace/]repository[:tag][@sha256] references are supported.", - )); - } - let policy = ImagePolicy::default(); - let registry = registry(named, &policy)?; - let mut fetch = Fetch::new(®istry, &named.path, &policy)?; - fetch.deadline = fetch.deadline.min(deadline); - let (reference, expected) = match (&named.digest, &named.tag) { - (Some(pin), _) => (pin.as_str(), Some(pin.as_str())), - (None, Some(tag)) => (tag.as_str(), None), - (None, None) => ("latest", None), - }; - let initial = fetch.manifest(reference)?; - let source_digest = digest(&initial); - if expected.is_some_and(|expected| expected != source_digest) { - return Err(error("Registry manifest digest or size mismatch.") - .with_cause_code("registry_digest_mismatch".into())); - } - let (manifest, _, _, child) = - select(&mut fetch, &initial, &source_digest, PlatformPolicy::Native)?; - let pinned_reference = format!("{}/{}@{source_digest}", registry.domain, named.path); - // BuildKit pulls the base itself, outside acquisition's archive budget, so the sizes - // the manifest declares are bounded here before any build runs. - bounded_build_base(&manifest, &pinned_reference, policy.archive_limit)?; - let config = manifest - .config - .ok_or_else(|| error("Image config descriptor is missing."))?; - let config_bytes = fetch.object("blobs", &config)?; - ManifestProof::new(initial, child, config_bytes)? - .verified_build_base(&pinned_reference, policy.archive_limit) -} - /// Refuse a build base whose manifest declares more than `limit` compressed bytes of /// config and layers (the per-image archive budget acquisition applies), or no layers /// or more than the layer limit. Every descriptor's `size` is a required unsigned @@ -2110,9 +2064,6 @@ fn bounded_build_base( .config .as_ref() .ok_or_else(|| error("Image config descriptor is missing."))?; - // The same descriptor checks direct acquisition applies: BuildKit fetches these - // itself, and a foreign-layer `urls` entry or a non-distributable layer would be - // fetched from the guest's own namespace, outside the build network's isolation. let refused = |what: &str, reason: CandidateError| { CandidateError::new( "native_build_base_image", diff --git a/packages/runtime-core/src/provider/registry_image_test.rs b/packages/runtime-core/src/provider/registry_image_test.rs index bcbb9adab..b57150250 100644 --- a/packages/runtime-core/src/provider/registry_image_test.rs +++ b/packages/runtime-core/src/provider/registry_image_test.rs @@ -2024,22 +2024,6 @@ fn image_platform_fields_are_read_like_the_engine_and_refuse_repetition() { } } -#[test] -fn build_bases_accept_only_docker_hub_references() { - let named = |value: &str| match normalize(value).unwrap() { - ImageReference::Named(named) => named, - ImageReference::ImageId(_) => unreachable!(), - }; - for value in [ - "ghcr.io/example/app:1", - "registry.test:5000/app:1", - "localhost/app:1", - ] { - let error = resolve_build_base(&named(value), Instant::now()).unwrap_err(); - assert_eq!(error.code, "registry_image", "{value}"); - } -} - #[test] fn retry_token_and_manifest_stalled_headers_within_deadline() { retry_registry_preheader_failure(false); diff --git a/scripts/lib/tla-runtime-models.ts b/scripts/lib/tla-runtime-models.ts index 24578fd88..4563e9927 100644 --- a/scripts/lib/tla-runtime-models.ts +++ b/scripts/lib/tla-runtime-models.ts @@ -2812,11 +2812,18 @@ const contracts: readonly ModelContract[] = [ { name: "native-build-alias", module: "BuildAlias", - states: 9, + states: 23, invariant: "BaseSurvives", action: "Cleanup", fields: ["base = FALSE", "alias = FALSE"], additionalControls: [ + { + name: "old-order", + negative: true, + invariant: "CanRecover", + action: "Refuse", + fields: ['phase = "blocked"', "keeper = FALSE", "alias = TRUE"], + }, { name: "unsafe-remote", negative: true, diff --git a/src/backends/native-image-tags.ts b/src/backends/native-image-tags.ts index c297ff848..9c7127d03 100644 --- a/src/backends/native-image-tags.ts +++ b/src/backends/native-image-tags.ts @@ -32,6 +32,7 @@ import { type NativeRuntimeSelection, } from "./native-runtime-client.ts"; +const UP_BUILD_REFUSAL = /^Native foreground up cannot build /; const DISPLAY_IDENTITY = /^[A-Za-z0-9._:/@-]{1,512}$/; const TAG_REFERENCE = /^[A-Za-z0-9._:/-]{1,512}$/; const IMAGE_ID = /^sha256:[a-f0-9]{64}$/; @@ -111,18 +112,6 @@ export async function pullNativeProjectImages(opts: { invoke, }); - const builds = admitNativeProjectBuilds({ - services: Object.fromEntries(specs), - projectRoot: opts.project.projectRoot, - composeFile: opts.project.composeFile, - enabled: true, - }); - const bases = await nativeBuildBases({ - projectRoot: opts.project.projectRoot, - runtime: opts.runtime, - builds, - invoke, - }); const images = specs.flatMap(([name, spec]) => typeof spec.image === "string" ? [ @@ -133,14 +122,11 @@ export async function pullNativeProjectImages(opts: { ] : [] ); - for (const base of bases) { - images.push({ image: base, policy: undefined }); - } - for (const { image, policy } of images) { + const pull = async ({ image, policy }: (typeof images)[number]) => { const reference = canonical.get(image) ?? image; const selection = `${reference}\n${policy ?? "native"}`; if (seen.has(selection)) { - continue; + return; } const pin = pins.get(reference); const args = nativeEnsureImageArgs(reference, policy); @@ -200,6 +186,35 @@ export async function pullNativeProjectImages(opts: { } seen.add(selection); results.push(result); + }; + for (const image of images) { + await pull(image); + } + let bases: readonly string[]; + try { + const builds = admitNativeProjectBuilds({ + services: Object.fromEntries(specs), + projectRoot: opts.project.projectRoot, + composeFile: opts.project.composeFile, + enabled: true, + }); + bases = await nativeBuildBases({ + projectRoot: opts.project.projectRoot, + runtime: opts.runtime, + builds, + invoke, + }); + } catch (error) { + const detail = + error instanceof Error + ? error.message + : "Build bases could not be inspected."; + throw new ClosedCliError( + `Native pull could not confirm build bases: ${detail.replace(UP_BUILD_REFUSAL, "")}` + ); + } + for (const base of bases) { + await pull({ image: base, policy: undefined }); } return results; } diff --git a/src/backends/native-project-builds.ts b/src/backends/native-project-builds.ts index 0e8f290e3..ab0e86dfa 100644 --- a/src/backends/native-project-builds.ts +++ b/src/backends/native-project-builds.ts @@ -727,6 +727,8 @@ export async function resolveNativeRestartBuilds(opts: { /** `HACK_NATIVE_REBUILD=1`: every build runs again, as on `up`. */ readonly rebuild: boolean; readonly signal: AbortSignal; + readonly onNotice?: (line: string) => void; + readonly onImageWait?: (reference: string | null) => void; readonly invoke?: typeof invokeNativeBuild; }): Promise> { refuseManagedSecretBuildArguments({ @@ -984,14 +986,7 @@ const BUILD_SOURCE_POLICY: Readonly> = { "Remove VOLUME from the Dockerfile and its base images; declare volumes in Compose instead.", }; -/** - * Name the services of a failed `runtime build-image`. A refusal from the build - * source policy says so and what to change; a home without the image builder - * says so and how to add it, naming this install's own command; any other - * runtime failure keeps its message. The native code is kept for callers that - * classify failures. Cancellation and closed client errors carry no - * service-specific cause and pass through unchanged. - */ +/** Scan the admitted Dockerfiles and return distinct canonical base references. */ export async function nativeBuildBases(opts: { readonly projectRoot: string; readonly runtime: NativeRuntimeSelection; @@ -1055,6 +1050,14 @@ export async function nativeBuildBases(opts: { } } +/** + * Name the services of a failed `runtime build-image`. A refusal from the build + * source policy says so and what to change; a home without the image builder + * says so and how to add it, naming this install's own command; any other + * runtime failure keeps its message. The native code is kept for callers that + * classify failures. Cancellation and closed client errors carry no + * service-specific cause and pass through unchanged. + */ function nameBuildFailure( services: readonly string[], error: unknown diff --git a/src/backends/native-project-restart-preflight.ts b/src/backends/native-project-restart-preflight.ts index 5fbfe76b3..1a66349cd 100644 --- a/src/backends/native-project-restart-preflight.ts +++ b/src/backends/native-project-restart-preflight.ts @@ -4,6 +4,10 @@ import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { ClosedCliError, HackCliError } from "../lib/cli-result.ts"; import { isRecord } from "../lib/guards.ts"; +import { + reportNativeImageDownloadWait, + reportNativeImageNotice, +} from "../lib/native-detached-up.ts"; import { requireWrappableNativeProcesses } from "../lib/native-process-wrappers.ts"; import { adaptNativeAwsEnvironment } from "./native-aws-environment.ts"; import type { NativeDependencyOwnerResolver } from "./native-dependency-owners.ts"; @@ -355,6 +359,12 @@ async function pinRestartImages(opts: { managedSecretValues: opts.managedSecretValues ?? [], rebuild: nativeRebuildRequested(), signal: opts.signal ?? new AbortController().signal, + onNotice: (line) => { + if (!reportNativeImageNotice(line)) { + process.stderr.write(`${line}\n`); + } + }, + onImageWait: reportNativeImageDownloadWait, invoke: opts.build, }); for (const [name, spec] of Object.entries(opts.specs)) { diff --git a/tests/models/tla/README.md b/tests/models/tla/README.md index 15fa8e432..2dfcf2963 100644 --- a/tests/models/tla/README.md +++ b/tests/models/tla/README.md @@ -1874,13 +1874,32 @@ Not covered: ## Native build base aliases -`native-build-alias/BuildAlias.tla` models one loaded base and one attempt. -`Record` represents the cache tag and the durable alias journal written before -`Tag`. The build-key lock is inherited by the builder. `Crash` can leave an alias -and a live child; `Cleanup` is admitted only after the lock is free, or by the -live owner after the solver is done. The source allowlist contains only that -attempt's local alias. The negative controls remove the cache reference, allow -remote resolution, or sweep while the child still holds the lock. The model -does not simulate Docker's transport, key uniqueness, the registry, or disk -durability. The Rust alias sweep regression and the classic-worker wire count -cover separate implementation boundaries. +`native-build-alias/BuildAlias.tla` models one loaded base, one attempt and a +possible restart in a different runtime incarnation. The positive run visits 23 +states. The `old-order` control reaches `blocked`, where every retry sees the +same missing keeper and refuses. The other controls allow deleting the last tag, +registry fallback, or sweeping while the child holds the key lock. + +| Model action | Code or external step | +| --- | --- | +| `Record` | `Aliases::prepare` verifies the keeper and writes the alias journal | +| `Tag` | `Aliases::prepare` installs the attempt alias after journal publication | +| `Solve` | `run_with_bases` starts the client with the key lock | +| `ResolveMissing` | Negative control for a registry request forbidden by the builder source policy | +| `Finish` | The supervised client exits and the build can publish a verified receipt | +| `Crash` | The coordinator exits before alias cleanup | +| `ChildExits` | The surviving client exits and releases its inherited lock | +| `LoseKeeper` | An external deletion removes the keeper tag and leaves the alias | +| `RestoreKeeper` | `aliases::sweep` verifies the alias ID and restores its keeper | +| `Cleanup` | `Aliases::drop` or `aliases::sweep_stranded` untags and removes the journal after the worker releases the key | +| `Reuse` | `run_with_bases` returns a verified receipt before the alias sweep | +| `Refuse`, `Retry` | Old sweep runs before reuse and leaves the same journal on every refusal | +| `ChangeIncarnation` | The guest is replaced after the attempt ends | +| `DiscardJournal` | `aliases::sweep` discards the journal without using its tags in the replacement guest | + +The verified flag abstracts a receipt already available to a retry. The model +leaves out Docker transport, filesystem durability, and tag identity races +outside the provider lease. The Rust regressions exercise journal and tag +recovery, and the classic worker wire count exercises registry isolation. + +[Build alias state chart](native-build-alias/build-alias.svg) diff --git a/tests/models/tla/native-build-alias/BuildAlias.tla b/tests/models/tla/native-build-alias/BuildAlias.tla index cd03c9c44..d7c84f0be 100644 --- a/tests/models/tla/native-build-alias/BuildAlias.tla +++ b/tests/models/tla/native-build-alias/BuildAlias.tla @@ -1,38 +1,65 @@ ---- MODULE BuildAlias ---- EXTENDS Naturals -CONSTANT UnsafeUntag, UnsafeRemote, UnsafeSweep -VARIABLES phase, alias, base, keeper, child, wire, sweptLive -vars == <> +CONSTANT UnsafeUntag, UnsafeRemote, UnsafeSweep, OldOrder +VARIABLES phase, alias, base, keeper, child, wire, sweptLive, changed, verified +vars == <> Init == /\ phase = "idle" /\ alias = FALSE /\ base = TRUE /\ keeper = FALSE /\ child = FALSE /\ wire = FALSE /\ sweptLive = FALSE + /\ changed = FALSE /\ verified = FALSE Record == /\ phase = "idle" /\ phase' = "recorded" /\ keeper' = ~UnsafeUntag - /\ UNCHANGED <> + /\ UNCHANGED <> Tag == /\ phase = "recorded" /\ base /\ phase' = "tagged" /\ alias' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> Solve == /\ phase = "tagged" /\ alias /\ phase' = "solving" /\ child' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> ResolveMissing == /\ phase = "solving" /\ UnsafeRemote - /\ wire' = TRUE /\ UNCHANGED <> + /\ wire' = TRUE /\ UNCHANGED <> Finish == /\ phase = "solving" /\ phase' = "finished" /\ child' = FALSE - /\ UNCHANGED <> + /\ verified' = TRUE + /\ UNCHANGED <> Crash == /\ phase \in {"recorded", "tagged", "solving", "finished"} /\ phase' = "stranded" - /\ UNCHANGED <> + /\ UNCHANGED <> ChildExits == /\ phase = "stranded" /\ child /\ child' = FALSE - /\ UNCHANGED <> + /\ UNCHANGED <> Cleanup == /\ phase \in {"finished", "stranded"} /\ ~child \/ UnsafeSweep + /\ ~changed + /\ keeper \/ ~alias \/ UnsafeUntag /\ sweptLive' = (sweptLive \/ child) /\ base' = (base /\ (keeper \/ ~alias)) /\ alias' = FALSE /\ phase' = "idle" /\ child' = FALSE - /\ UNCHANGED <> + /\ UNCHANGED <> + +LoseKeeper == /\ phase = "stranded" /\ alias /\ keeper /\ ~child /\ ~changed + /\ keeper' = FALSE + /\ UNCHANGED <> +RestoreKeeper == /\ phase = "stranded" /\ alias /\ ~keeper /\ ~child /\ ~changed + /\ ~OldOrder /\ ~UnsafeUntag /\ keeper' = TRUE + /\ UNCHANGED <> +Reuse == /\ phase = "stranded" /\ verified /\ ~child /\ ~changed /\ ~OldOrder + /\ phase' = "reused" + /\ UNCHANGED <> +Refuse == /\ phase = "stranded" /\ alias /\ ~keeper /\ ~child /\ ~changed /\ OldOrder + /\ phase' = "blocked" + /\ UNCHANGED <> +Retry == /\ phase = "blocked" /\ UNCHANGED vars +ChangeIncarnation == /\ phase = "stranded" /\ ~child /\ ~changed + /\ changed' = TRUE /\ alias' = FALSE /\ keeper' = FALSE + /\ UNCHANGED <> +DiscardJournal == /\ phase = "stranded" /\ changed + /\ phase' = "idle" /\ changed' = FALSE /\ verified' = FALSE + /\ UNCHANGED <> Next == Record \/ Tag \/ Solve \/ ResolveMissing \/ Finish \/ Crash \/ ChildExits \/ Cleanup + \/ LoseKeeper \/ RestoreKeeper \/ Reuse \/ Refuse \/ Retry + \/ ChangeIncarnation \/ DiscardJournal Spec == Init /\ [][Next]_vars BaseSurvives == base NoRegistryFallback == ~wire NoLiveSweep == ~sweptLive IdleIsClean == phase = "idle" => ~alias +CanRecover == phase # "blocked" ==== diff --git a/tests/models/tla/native-build-alias/build-alias.mmd b/tests/models/tla/native-build-alias/build-alias.mmd new file mode 100644 index 000000000..2dc1be5ff --- /dev/null +++ b/tests/models/tla/native-build-alias/build-alias.mmd @@ -0,0 +1,31 @@ +--- +title: BuildAlias · local base recovery +--- +stateDiagram-v2 + direction TB + [*] --> idle + idle --> recorded : Record + recorded --> tagged : Tag + tagged --> solving : Solve + solving --> solving : ResolveMissing [control] + solving --> finished : Finish + recorded --> stranded : Crash + tagged --> stranded : Crash + solving --> stranded : Crash + finished --> stranded : Crash + finished --> idle : Cleanup + stranded --> stranded : ChildExits + stranded --> stranded : LoseKeeper + stranded --> stranded : RestoreKeeper + stranded --> stranded : ChangeIncarnation + stranded --> idle : Cleanup [keeper] + stranded --> idle : DiscardJournal [changed] + stranded --> reused : Reuse [verified receipt] + stranded --> blocked : Refuse [old order] + blocked --> blocked : Retry + classDef live stroke-width:1.6px + class idle idle + class recorded,tagged,solving live + class stranded wait + class finished,reused ok + class blocked fail diff --git a/tests/models/tla/native-build-alias/build-alias.svg b/tests/models/tla/native-build-alias/build-alias.svg new file mode 100644 index 000000000..1c6ff1917 --- /dev/null +++ b/tests/models/tla/native-build-alias/build-alias.svg @@ -0,0 +1,66 @@ +BuildAlias · local base recoveryRecordTagSolveResolveMissing [control]FinishCrashCrashCrashCrashCleanupChildExitsLoseKeeperRestoreKeeperChangeIncarnationCleanup [keeper]DiscardJournal [changed]Reuse [verified receipt]Refuse [old order]Retryidlerecordedtaggedsolvingfinishedstrandedreusedblocked \ No newline at end of file diff --git a/tests/models/tla/native-build-alias/negative.cfg b/tests/models/tla/native-build-alias/negative.cfg index 4c6a30e96..d5821045a 100644 --- a/tests/models/tla/native-build-alias/negative.cfg +++ b/tests/models/tla/native-build-alias/negative.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec -CONSTANTS UnsafeUntag = TRUE UnsafeRemote = FALSE UnsafeSweep = FALSE -INVARIANTS BaseSurvives NoRegistryFallback NoLiveSweep IdleIsClean +CONSTANTS UnsafeUntag = TRUE UnsafeRemote = FALSE UnsafeSweep = FALSE OldOrder = FALSE +INVARIANTS BaseSurvives NoRegistryFallback NoLiveSweep IdleIsClean CanRecover CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-build-alias/old-order.cfg b/tests/models/tla/native-build-alias/old-order.cfg new file mode 100644 index 000000000..96b040e90 --- /dev/null +++ b/tests/models/tla/native-build-alias/old-order.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS UnsafeUntag = FALSE UnsafeRemote = FALSE UnsafeSweep = FALSE OldOrder = TRUE +INVARIANTS BaseSurvives NoRegistryFallback NoLiveSweep IdleIsClean CanRecover +CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-build-alias/positive.cfg b/tests/models/tla/native-build-alias/positive.cfg index 7959e99ba..11aa92065 100644 --- a/tests/models/tla/native-build-alias/positive.cfg +++ b/tests/models/tla/native-build-alias/positive.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec -CONSTANTS UnsafeUntag = FALSE UnsafeRemote = FALSE UnsafeSweep = FALSE -INVARIANTS BaseSurvives NoRegistryFallback NoLiveSweep IdleIsClean +CONSTANTS UnsafeUntag = FALSE UnsafeRemote = FALSE UnsafeSweep = FALSE OldOrder = FALSE +INVARIANTS BaseSurvives NoRegistryFallback NoLiveSweep IdleIsClean CanRecover CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-build-alias/unsafe-remote.cfg b/tests/models/tla/native-build-alias/unsafe-remote.cfg index db489d3d2..3d0b1db54 100644 --- a/tests/models/tla/native-build-alias/unsafe-remote.cfg +++ b/tests/models/tla/native-build-alias/unsafe-remote.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec -CONSTANTS UnsafeUntag = FALSE UnsafeRemote = TRUE UnsafeSweep = FALSE -INVARIANTS BaseSurvives NoRegistryFallback NoLiveSweep IdleIsClean +CONSTANTS UnsafeUntag = FALSE UnsafeRemote = TRUE UnsafeSweep = FALSE OldOrder = FALSE +INVARIANTS BaseSurvives NoRegistryFallback NoLiveSweep IdleIsClean CanRecover CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-build-alias/unsafe-sweep.cfg b/tests/models/tla/native-build-alias/unsafe-sweep.cfg index bdce6ad67..dee716655 100644 --- a/tests/models/tla/native-build-alias/unsafe-sweep.cfg +++ b/tests/models/tla/native-build-alias/unsafe-sweep.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec -CONSTANTS UnsafeUntag = FALSE UnsafeRemote = FALSE UnsafeSweep = TRUE -INVARIANTS BaseSurvives NoRegistryFallback NoLiveSweep IdleIsClean +CONSTANTS UnsafeUntag = FALSE UnsafeRemote = FALSE UnsafeSweep = TRUE OldOrder = FALSE +INVARIANTS BaseSurvives NoRegistryFallback NoLiveSweep IdleIsClean CanRecover CHECK_DEADLOCK FALSE diff --git a/tests/native-image-tags.test.ts b/tests/native-image-tags.test.ts index 235474579..fc2960057 100644 --- a/tests/native-image-tags.test.ts +++ b/tests/native-image-tags.test.ts @@ -1,9 +1,15 @@ import { expect, test } from "bun:test"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { batchImageFailure, pendingImageProofReason, } from "../src/backends/native-image-policy.ts"; -import { nativeImageBlocker } from "../src/backends/native-image-tags.ts"; +import { + nativeImageBlocker, + pullNativeProjectImages, +} from "../src/backends/native-image-tags.ts"; const runtime = { binary: "/fixture/hack-native", home: "/fixture/home" }; const projectRoot = "/fixture/project"; @@ -53,3 +59,65 @@ test("an unsafe pending proof names only the admitted relative file", () => { }) ).toBeUndefined(); }); + +test.each([ + "supported", + "unsupported field", + "unsupported base", +])("native pull acquires service images first: %s", async (scenario) => { + const root = await mkdtemp(join(tmpdir(), "native-pull-build-")); + try { + const projectDir = join(root, ".hack"); + await mkdir(projectDir); + const composeFile = join(projectDir, "compose.yaml"); + const id = `sha256:${"a".repeat(64)}`; + const base = "docker.io/library/alpine:3.20"; + await writeFile( + composeFile, + `services: + service: + image: ${id} + app: + build: + context: .. +${scenario === "unsupported field" ? " ssh: [default]\n" : ""}` + ); + const confirmed: string[] = []; + const pull = pullNativeProjectImages({ + project: { projectDir, projectRoot: root, composeFile }, + runtime, + profiles: [], + invoke: async ({ args }) => { + if (args[1] === "build-image") { + expect(confirmed).toEqual([id]); + if (scenario === "unsupported base") { + throw new Error("Use public Docker Hub images."); + } + return [base]; + } + expect(args[1]).toBe("ensure-image"); + expect(args).toContain("refresh"); + confirmed.push(args[3] ?? ""); + return { + phase: "content-id-verified", + image_id: id, + pinned_reference: `docker.io/library/alpine@${id}`, + }; + }, + }); + if (scenario === "supported") { + expect(await pull).toHaveLength(2); + expect(confirmed).toEqual([id, base]); + } else { + const error = await pull.catch((cause: unknown) => cause); + expect(error).toBeInstanceOf(Error); + expect(String(error)).toContain( + "Native pull could not confirm build bases" + ); + expect(String(error)).not.toContain("foreground up"); + expect(confirmed).toEqual([id]); + } + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/tests/native-project-builds.test.ts b/tests/native-project-builds.test.ts index 097013bc0..1b846c8a1 100644 --- a/tests/native-project-builds.test.ts +++ b/tests/native-project-builds.test.ts @@ -16,6 +16,7 @@ import { buildNativeProjectImages, invokeNativeBuild, type NativeBuildRequest, + nativeBuildBases, nativeBuildIdentity, nativeBuildsDisabledRefusal, nativeBuildsEnabled, @@ -796,3 +797,98 @@ test("a native home without the image builder says so and how to add it", async expect(message).not.toContain(VALUE); expect(written.join("")).toBe("resolving base images\n"); }); + +test("build base scans deduplicate references and remove the private request", async () => { + const projectRoot = await root(); + const files: string[] = []; + const alpine = "docker.io/library/alpine:3.20"; + expect( + await nativeBuildBases({ + projectRoot, + runtime, + builds: new Map([ + ["one", request()], + ["two", request({})], + ]), + invoke: async ({ args }) => { + const path = args[3]; + if (!path) { + throw new Error("Expected a build request path"); + } + files.push(path); + expect(args.slice(4)).toEqual(["--bases", "--json"]); + expect((await stat(path)).mode & 0o777).toBe(0o600); + return files.length === 1 + ? [alpine] + : [alpine, "docker.io/library/busybox:latest"]; + }, + }) + ).toEqual([alpine, "docker.io/library/busybox:latest"]); + expect(files).toHaveLength(2); + expect(await Bun.file(files[0] ?? "").exists()).toBe(false); +}); + +test("later builds receive command base pins and each fallback notice is reported once", async () => { + const projectRoot = await root(); + const reference = "docker.io/library/alpine:3.20"; + const pin = `docker.io/library/alpine@${IMAGE}`; + const notice = "Registry unavailable, using the loaded build base."; + const notices: string[] = []; + let calls = 0; + await buildNativeProjectImages({ + runtime, + projectRoot, + branch: null, + profiles: [], + builds: new Map([ + ["one", request()], + ["two", request({})], + ]), + specs: { one: { build: "app" }, two: { build: "app" } }, + rebuild: false, + imageTagMode: "refresh", + signal: new AbortController().signal, + onNotice: (line) => notices.push(line), + invoke: async ({ requestFile }) => { + const body = JSON.parse(await readFile(requestFile, "utf8")); + expect(body.image_tag_mode).toBe("refresh"); + expect(body.command_base_pins).toEqual( + calls === 0 ? undefined : { [reference]: pin } + ); + calls += 1; + return { + imageId: IMAGE, + buildKey: KEY, + reused: true, + baseSelections: { [reference]: pin }, + baseFallbacks: [notice], + }; + }, + }); + expect(calls).toBe(2); + expect(notices).toEqual([notice]); +}); + +test("build output decodes lock progress and verified fallback notices", async () => { + const reference = "docker.io/library/alpine:3.20"; + const fake = await fakeRuntime( + `printf 'hack.image-wait:begin ${reference}\\nhack.image-wait:end ${reference}\\n' >&2 + printf '{"image_id":"${IMAGE}","build_key":"${KEY}","reused":true,"reused_legacy_key":true,"base_fallbacks":[{"reference":"${reference}","resolved_at_unix_seconds":0},{"reference":"invalid reference","resolved_at_unix_seconds":0}]}'` + ); + const waiting: (string | null)[] = []; + const built = await invokeNativeBuild({ + runtime: fake as never, + cwd: fake.home, + requestFile: join(fake.home, "request.json"), + onImageWait: (value) => waiting.push(value), + write: () => { + throw new Error("Expected the image-wait markers to be consumed"); + }, + }); + expect(waiting).toEqual([reference, null, null]); + expect(built.baseFallbacks).toHaveLength(2); + expect(built.baseFallbacks?.[0]).toContain(reference); + expect(built.baseFallbacks?.[1]).toContain( + "unchanged context and Dockerfile" + ); +}); From e1d450d29dfb1a17860696c552ece141e7d1f3cd Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:18:54 +0000 Subject: [PATCH 22/33] fix: release the image cache before waiting on another tag --- .../runtime-core/src/provider/image_build.rs | 13 ++++- .../src/provider/image_build/tests.rs | 7 ++- .../runtime-core/src/provider/image_ensure.rs | 55 ++++++++++++++++--- 3 files changed, 66 insertions(+), 9 deletions(-) diff --git a/packages/runtime-core/src/provider/image_build.rs b/packages/runtime-core/src/provider/image_build.rs index 18fa38fed..2c1de36df 100644 --- a/packages/runtime-core/src/provider/image_build.rs +++ b/packages/runtime-core/src/provider/image_build.rs @@ -959,6 +959,8 @@ fn run_with_bases( &receipt_path, previous, )? { + // Recovery cannot invalidate the verified reuse decision. + let _ = aliases::sweep(pool, &lease, &identity, &alias_path); return Ok(outcome); } if previous.phase == Phase::Building { @@ -1904,6 +1906,15 @@ fn acquire_bases( }) } +fn base_registry_failed(error: &CandidateError) -> bool { + error.code.starts_with("registry_") + || (error.code == "image_tag_offline_missing" + && error + .cause_code + .as_deref() + .is_some_and(|code| code.starts_with("registry_"))) +} + /// `runtime build-image --request `: build or reuse one native image. pub fn build_image(candidate: &Candidate, request: &Path) -> Result { let request: BuildRequest = state::read_bounded(request, MAX_REQUEST_BYTES)?; @@ -1952,7 +1963,7 @@ pub fn build_image(candidate: &Candidate, request: &Path) -> Result bases, Err(error) => { if Instant::now() < deadline - && error.code.starts_with("registry_") + && base_registry_failed(&error) && let Some(outcome) = reuse_legacy(candidate, &pool, &inputs)? { return Ok(outcome); diff --git a/packages/runtime-core/src/provider/image_build/tests.rs b/packages/runtime-core/src/provider/image_build/tests.rs index 791533208..f77df3395 100644 --- a/packages/runtime-core/src/provider/image_build/tests.rs +++ b/packages/runtime-core/src/provider/image_build/tests.rs @@ -2082,7 +2082,7 @@ fn a_verified_base_selects_the_build_key_and_only_a_local_worker_source() { .unwrap() .reused ); - assert!(journal.exists(), "reuse must precede journal inspection"); + assert!(!journal.exists()); assert!(!pending.exists()); let bake: Value = serde_json::from_slice(&fs::read(scratch.join("seen-bake.json")).unwrap()).unwrap(); @@ -2236,6 +2236,11 @@ fn aliases_restore_a_keeper_and_quarantine_a_malformed_journal() { #[test] fn legacy_reuse_requires_the_original_context_and_a_verified_image() { + let missing = || CandidateError::new("image_tag_offline_missing", "fixture"); + assert!(base_registry_failed( + &missing().with_cause_code("registry_unreachable".into()) + )); + assert!(!base_registry_failed(&missing())); let fixture = Fixture::new(); let inputs = fixture.inputs(Policy::Missing); let pool = FakePool::new("pool-1"); diff --git a/packages/runtime-core/src/provider/image_ensure.rs b/packages/runtime-core/src/provider/image_ensure.rs index 07ab7675d..cd898cf83 100644 --- a/packages/runtime-core/src/provider/image_ensure.rs +++ b/packages/runtime-core/src/provider/image_ensure.rs @@ -27,6 +27,7 @@ const IMAGE_WORKERS: usize = 3; #[derive(Default)] struct CacheState { lease: Option, + users: usize, reservations: BTreeMap, disk_reserved: u64, } @@ -64,11 +65,7 @@ impl ImageCache { } } - fn enter( - &self, - root: &Path, - policy: &ImagePolicy, - ) -> Result, CandidateError> { + fn enter(&self, root: &Path, policy: &ImagePolicy) -> Result, CandidateError> { let mut cache = self.state.lock().unwrap(); if cache.lease.is_none() { let lease = @@ -80,10 +77,33 @@ impl ImageCache { cache.lease = Some(lease); } cache.lease.as_ref().unwrap().verify_path(root)?; + cache.users += 1; + Ok(CacheLease(self)) + } +} + +/// Only workers using the cache hold this lease. Workers still resolving tags +/// can never keep it alive while another command needs it to confirm a tag. +struct CacheLease<'a>(&'a ImageCache); + +impl CacheLease<'_> { + fn lock(&self, root: &Path) -> Result, CandidateError> { + let cache = self.0.state.lock().unwrap(); + cache.lease.as_ref().unwrap().verify_path(root)?; Ok(cache) } } +impl Drop for CacheLease<'_> { + fn drop(&mut self) { + let mut cache = self.0.state.lock().unwrap(); + cache.users -= 1; + if cache.users == 0 { + cache.lease = None; + } + } +} + struct DiskReservation<'a> { cache: &'a ImageCache, bytes: u64, @@ -961,7 +981,8 @@ fn ensure_pinned_coordinated( .or_default() .clone(); let _pin = pin.lock().unwrap(); - let mut state = coordinator.enter(&root, policy)?; + let lease = coordinator.enter(&root, policy)?; + let mut state = lease.lock(&root)?; let inventory = || measure(Step::ImageCacheInventory, None, |_| usage(candidate, &root)); let mut occupied = inventory()?; // A cached entry is reused only for the platform the pinned image itself selects under @@ -1052,7 +1073,7 @@ fn ensure_pinned_coordinated( } state::write(&dir.join("receipt.json"), &receipt)?; inspect_entry(candidate, dir, &reference, acquired.platform)?; - let state = coordinator.enter(&root, policy)?; + let state = lease.lock(&root)?; let target = root.join(entry_key(&reference, acquired.platform)); if target.try_exists().map_err(state::io)? { return Err(refused( @@ -1067,6 +1088,7 @@ fn ensure_pinned_coordinated( drop(reservation); (target, receipt) }; + drop(lease); // Keep the import lease and the loader’s own live recheck unchanged. let _import = coordinator.importer.lock().unwrap(); load(candidate, &dir.join("image.tar"), &receipt, reused)?; @@ -1290,6 +1312,25 @@ mod tests { assert_eq!(usage(&f.1, &root).unwrap(), (0, 0)); } + #[test] + fn batch_releases_the_cache_lease_when_its_last_cache_worker_finishes() { + let f = Fixture::new(); + let root = f.1.state_root.join("artifacts/images"); + let cache = ImageCache::default(); + let policy = ImagePolicy::default(); + let first = cache.enter(&root, &policy).unwrap(); + let second = cache.enter(&root, &policy).unwrap(); + drop(first); + assert_eq!( + state::Lock::acquire(&root).err().unwrap().code, + "provider_busy" + ); + drop(second); + // The batch can still be waiting on another tag at this point. That + // tag's owner is now free to enter the cache from another command. + assert!(state::Lock::acquire(&root).is_ok()); + } + #[test] fn a_failed_fetch_can_settle_while_another_verified_archive_imports() { let f = Fixture::new(); From f66545a8dbd7818101e108731f1bf0b69edb8a45 Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:24:39 +0000 Subject: [PATCH 23/33] fix: finish build alias recovery after canceled solves --- .../runtime-core/src/provider/image_build.rs | 45 ++++++++--- .../src/provider/image_build/aliases.rs | 17 ++--- .../src/provider/image_build/reclaim.rs | 7 +- .../src/provider/image_build/tests.rs | 75 ++++++++++++++++++- tests/models/tla/README.md | 2 +- 5 files changed, 118 insertions(+), 28 deletions(-) diff --git a/packages/runtime-core/src/provider/image_build.rs b/packages/runtime-core/src/provider/image_build.rs index 2c1de36df..a3a523a59 100644 --- a/packages/runtime-core/src/provider/image_build.rs +++ b/packages/runtime-core/src/provider/image_build.rs @@ -49,8 +49,8 @@ //! bounds. //! - The client builds from a private copy of the Dockerfile and ignore bytes that were //! scanned and hashed, never from the project paths again. -//! - Every build runs under [`build_policy::document`] for its pins, a BuildKit source -//! policy the client sends with the solve: only the pinned base references resolve as +//! - Every build runs under [`build_policy::build_document`] for its aliases, a BuildKit source +//! policy the client sends with the solve: only the attempt's local base aliases resolve as //! images, and network sources (`ADD` URLs, git, image blobs) are denied, including //! ones a base image's stored `ONBUILD` triggers add. //! - Build arguments are not secrets, as with Docker: an image records their values in @@ -270,6 +270,9 @@ pub(super) trait BuildPool { type Lease; /// Take the provider lease, verify the running pool, its build network and engine. fn lease(&self) -> Result<(Self::Lease, PoolIdentity), CandidateError>; + fn cleanup_lease(&self) -> Result<(Self::Lease, PoolIdentity), CandidateError> { + self.lease() + } /// Inspect one image by content ID or tag; `None` when the engine reports it absent. fn inspect(&self, lease: &Self::Lease, image: &str) -> Result, CandidateError>; fn tag_base(&self, lease: &Self::Lease, id: &str, tag: &str) -> Result<(), CandidateError>; @@ -1454,7 +1457,7 @@ fn command( let encoded = serde_json::to_vec(&bake_definition(inputs, context, &dockerfile, pins, labels)) .map_err(|_| invalid("Cannot encode the build definition."))?; write_private(&definition, &encoded)?; - // The policy allows exactly the pinned references the definition names as + // The policy allows exactly the private aliases the definition names as // contexts, and denies every other image and network source. let policy = bake.join(SOURCE_POLICY); let policy_bytes = serde_json::to_vec(&build_policy::build_document( @@ -1645,7 +1648,7 @@ fn connect( super::engine::Engine::connect_until( candidate, deadline.unwrap_or_else(|| Instant::now() + LEASE_WAIT), - || CANCEL_REQUESTED.load(Ordering::Acquire), + || deadline.is_some() && CANCEL_REQUESTED.load(Ordering::Acquire), ) } #[cfg(not(target_os = "macos"))] @@ -1727,6 +1730,13 @@ impl<'a> BuildPool for LivePool<'a> { }; Ok((engine, identity)) } + fn cleanup_lease(&self) -> Result<(Self::Lease, PoolIdentity), CandidateError> { + Self { + candidate: self.candidate, + build_deadline: None, + } + .lease() + } fn inspect(&self, lease: &Self::Lease, image: &str) -> Result, CandidateError> { match lease.request( reqwest::Method::GET, @@ -1915,6 +1925,22 @@ fn base_registry_failed(error: &CandidateError) -> bool { .is_some_and(|code| code.starts_with("registry_"))) } +fn recover_base_error( + error: CandidateError, + mode: super::image_policy::ImageTagMode, + deadline: Instant, + reuse: impl FnOnce() -> Result, CandidateError>, +) -> Result { + if mode == super::image_policy::ImageTagMode::Normal + && Instant::now() < deadline + && base_registry_failed(&error) + && let Ok(Some(outcome)) = reuse() + { + return Ok(outcome); + } + Err(error) +} + /// `runtime build-image --request `: build or reuse one native image. pub fn build_image(candidate: &Candidate, request: &Path) -> Result { let request: BuildRequest = state::read_bounded(request, MAX_REQUEST_BYTES)?; @@ -1949,6 +1975,7 @@ pub fn build_image(candidate: &Candidate, request: &Path) -> Result Result bases, Err(error) => { - if Instant::now() < deadline - && base_registry_failed(&error) - && let Some(outcome) = reuse_legacy(candidate, &pool, &inputs)? - { - return Ok(outcome); - } - return Err(error); + return recover_base_error(error, tag_mode, deadline, || { + reuse_legacy(candidate, &pool, &inputs) + }); } }; // Acquisition keeps the default signal dispositions, like ensure-image. diff --git a/packages/runtime-core/src/provider/image_build/aliases.rs b/packages/runtime-core/src/provider/image_build/aliases.rs index 3492683a7..b15202913 100644 --- a/packages/runtime-core/src/provider/image_build/aliases.rs +++ b/packages/runtime-core/src/provider/image_build/aliases.rs @@ -137,7 +137,7 @@ impl<'a, P: BuildPool> Aliases<'a, P> { impl Drop for Aliases<'_, P> { fn drop(&mut self) { if self.path.exists() - && let Ok((lease, identity)) = self.pool.lease() + && let Ok((lease, identity)) = self.pool.cleanup_lease() { let _ = sweep(self.pool, &lease, &identity, &self.path); } @@ -186,19 +186,21 @@ pub(super) fn sweep( { return quarantine(path); } + let mut mismatch = false; for (alias, id) in journal.aliases { if let Some(image) = pool.inspect(lease, &alias)? { if image["Id"] != id { - return Err(refusal( - "native_build_base_image", - "The recorded build alias differs from its image ID.", - )); + mismatch = true; + continue; } let keeper = format!("{DOMAIN}/{CACHE}:{}", id.trim_start_matches("sha256:")); tag(pool, lease, &id, &keeper)?; pool.untag_base(lease, &alias)?; } } + if mismatch { + return quarantine(path); + } } fs::remove_file(path).map_err(state::io) } @@ -210,10 +212,7 @@ fn quarantine(path: &Path) -> Result<(), CandidateError> { .map_err(state::io)?; let saved = path.with_extension(format!("invalid-{:x}.json", crate::Hex(nonce))); fs::rename(path, &saved).map_err(state::io)?; - eprintln!( - "Set aside a malformed build alias journal at {}", - saved.display() - ); + eprintln!("Set aside an invalid build alias journal at {saved:?}"); Ok(()) } diff --git a/packages/runtime-core/src/provider/image_build/reclaim.rs b/packages/runtime-core/src/provider/image_build/reclaim.rs index f97e268c6..c53438365 100644 --- a/packages/runtime-core/src/provider/image_build/reclaim.rs +++ b/packages/runtime-core/src/provider/image_build/reclaim.rs @@ -374,7 +374,7 @@ pub(super) fn run( } } } - for image in pool.base_images(&lease)? { + for image in pool.base_images(&lease).unwrap_or_default() { let Some(id) = image["Id"].as_str() else { continue; }; @@ -382,12 +382,13 @@ pub(super) fn run( continue; }; if !current.bases.contains(id) + && !referenced.contains(id) && image["RepoTags"] .as_array() .is_some_and(|tags| tags.iter().any(|tag| tag == &keeper)) && pool - .inspect(&lease, &keeper)? - .is_some_and(|image| image["Id"] == id) + .inspect(&lease, &keeper) + .is_ok_and(|value| value.is_some_and(|image| image["Id"] == id)) { let _ = pool.untag_base(&lease, &keeper); } diff --git a/packages/runtime-core/src/provider/image_build/tests.rs b/packages/runtime-core/src/provider/image_build/tests.rs index f77df3395..e6b095ce3 100644 --- a/packages/runtime-core/src/provider/image_build/tests.rs +++ b/packages/runtime-core/src/provider/image_build/tests.rs @@ -166,6 +166,7 @@ struct FakePool { /// Verify the image builder in this home before use, as the real pool does. builder_home: Option, unavailable: std::cell::Cell, + build_lease_ends: std::cell::Cell>, } impl FakePool { fn new(incarnation: &str) -> Self { @@ -180,6 +181,7 @@ impl FakePool { output: Arc::default(), builder_home: None, unavailable: std::cell::Cell::new(false), + build_lease_ends: std::cell::Cell::new(None), } } /// Register `id` as the image the fake client in mode `given` "builds" for `inputs`. @@ -207,6 +209,16 @@ impl FakePool { impl BuildPool for FakePool { type Lease = (); fn lease(&self) -> Result<((), PoolIdentity), CandidateError> { + if self + .build_lease_ends + .get() + .is_some_and(|end| Instant::now() >= end) + { + return Err(late_stop(false)); + } + self.cleanup_lease() + } + fn cleanup_lease(&self) -> Result<((), PoolIdentity), CandidateError> { if self.unavailable.get() { return Err(refusal("provider_busy", "Fake provider lease unavailable.")); } @@ -954,10 +966,13 @@ fn timeout_and_cancellation_stop_the_whole_client_group() { let pool = FakePool::new("pool-1"); fixture.client(&inputs, "sleep"); let started = Instant::now(); + pool.build_lease_ends.set(Some(started + inputs.timeout)); let error = run(&fixture.candidate, &pool, &inputs, &never).unwrap_err(); assert_eq!(error.code, "native_build_timeout"); assert!(started.elapsed() < Duration::from_secs(20)); assert_eq!(fixture.receipt(&inputs).phase, Phase::Canceled); + assert!(!fixture.scratch(&inputs).join("base-aliases.json").exists()); + assert!(!pool.images.borrow().keys().any(|tag| aliases::allowed(tag))); // On a loaded host the client may not have forked its child within the budget. let child = fixture.scratch(&inputs).join("child"); if let Ok(pid) = fs::read_to_string(&child) { @@ -968,13 +983,23 @@ fn timeout_and_cancellation_stop_the_whole_client_group() { fixture.client(&inputs, "sleep"); let _ = fs::remove_file(&child); let marker = child.clone(); - let cancel = move || marker.exists(); + pool.build_lease_ends.set(None); + let cancel = || { + if marker.exists() { + pool.build_lease_ends.set(Some(Instant::now())); + return true; + } + false + }; let error = run(&fixture.candidate, &pool, &inputs, &cancel).unwrap_err(); assert_eq!(error.code, "native_build_canceled"); assert_eq!(fixture.receipt(&inputs).phase, Phase::Canceled); + assert!(!fixture.scratch(&inputs).join("base-aliases.json").exists()); + assert!(!pool.images.borrow().keys().any(|tag| aliases::allowed(tag))); // Cancellation was requested only once the child existed (published atomically). wait_dead(&fs::read_to_string(&child).unwrap()); + pool.build_lease_ends.set(None); // A request canceled before the client starts never runs it. let error = run(&fixture.candidate, &pool, &inputs, &|| true).unwrap_err(); assert_eq!(error.code, "native_build_canceled"); @@ -2134,6 +2159,17 @@ fn reclaim_keeps_only_two_of_ten_base_keepers_for_one_build() { ) .unwrap(); } + let graphs = fixture.candidate.state_root.join("run/graphs/0123"); + state::private_directory(&graphs).unwrap(); + let retained_base = format!("sha256:{:064x}", 1); + state::write( + &graphs.join("receipt.json"), + &serde_json::json!({"image": retained_base}), + ) + .unwrap(); + reclaim::run(&fixture.candidate, &pool).unwrap(); + assert_eq!(pool.base_images(&()).unwrap().len(), 3); + fs::remove_file(graphs.join("receipt.json")).unwrap(); reclaim::run(&fixture.candidate, &pool).unwrap(); let kept = pool.base_images(&()).unwrap(); assert_eq!(kept.len(), 2); @@ -2179,6 +2215,14 @@ fn command_build_pins_are_applied_under_the_requested_acquisition_policy() { .unwrap(); assert_eq!(selected.selections[&reference], pin); assert_eq!(selected.selected["alpine:3.20"].image_id, IMAGE); + let expired = acquire_bases( + &inputs, + &BTreeMap::new(), + Default::default(), + |_, _| panic!("an expired build must not acquire a base"), + Instant::now(), + ); + assert_eq!(expired.err().unwrap().code, "native_build_timeout"); } #[test] @@ -2247,9 +2291,32 @@ fn legacy_reuse_requires_the_original_context_and_a_verified_image() { fixture.client(&inputs, "ok"); pool.built(&inputs, "pool-1", serde_json::json!({})); run(&fixture.candidate, &pool, &inputs, &never).unwrap(); - let result = reuse_legacy(&fixture.candidate, &pool, &inputs) - .unwrap() - .unwrap(); + use super::super::image_policy::ImageTagMode::{Normal, Offline, Refresh}; + let registry_error = || missing().with_cause_code("registry_unreachable".into()); + let soon = Instant::now() + Duration::from_secs(5); + for mode in [Offline, Refresh] { + let error = + recover_base_error(registry_error(), mode, soon, || panic!("must refuse")).unwrap_err(); + assert_eq!(error.code, "image_tag_offline_missing"); + } + assert_eq!( + recover_base_error(registry_error(), Normal, Instant::now(), || panic!( + "must refuse" + )) + .unwrap_err() + .code, + "image_tag_offline_missing" + ); + assert_eq!( + recover_base_error(registry_error(), Normal, soon, || Err(late_stop(false))) + .unwrap_err() + .code, + "image_tag_offline_missing" + ); + let result = recover_base_error(registry_error(), Normal, soon, || { + reuse_legacy(&fixture.candidate, &pool, &inputs) + }) + .unwrap(); assert!(result.reused && result.reused_legacy_key); fs::write(fixture.project.join("app/main.txt"), "edited").unwrap(); let changed = fixture.inputs(Policy::Missing); diff --git a/tests/models/tla/README.md b/tests/models/tla/README.md index 2dfcf2963..38772c37c 100644 --- a/tests/models/tla/README.md +++ b/tests/models/tla/README.md @@ -1892,7 +1892,7 @@ registry fallback, or sweeping while the child holds the key lock. | `LoseKeeper` | An external deletion removes the keeper tag and leaves the alias | | `RestoreKeeper` | `aliases::sweep` verifies the alias ID and restores its keeper | | `Cleanup` | `Aliases::drop` or `aliases::sweep_stranded` untags and removes the journal after the worker releases the key | -| `Reuse` | `run_with_bases` returns a verified receipt before the alias sweep | +| `Reuse` | `run_with_bases` decides verified reuse before a best-effort alias sweep | | `Refuse`, `Retry` | Old sweep runs before reuse and leaves the same journal on every refusal | | `ChangeIncarnation` | The guest is replaced after the attempt ends | | `DiscardJournal` | `aliases::sweep` discards the journal without using its tags in the replacement guest | From 2c756ce3b7fccc59fdcb35da7c5cb195ad933fd5 Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:33:13 +0000 Subject: [PATCH 24/33] fix: keep managed build arguments out of native pull --- .../runtime-core/src/provider/image_ensure.rs | 6 +++-- src/backends/native-image-tags.ts | 5 ++++ tests/native-image-tags.test.ts | 24 ++++++++++++++++++- 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/packages/runtime-core/src/provider/image_ensure.rs b/packages/runtime-core/src/provider/image_ensure.rs index cd898cf83..21be011d9 100644 --- a/packages/runtime-core/src/provider/image_ensure.rs +++ b/packages/runtime-core/src/provider/image_ensure.rs @@ -67,16 +67,18 @@ impl ImageCache { fn enter(&self, root: &Path, policy: &ImagePolicy) -> Result, CandidateError> { let mut cache = self.state.lock().unwrap(); - if cache.lease.is_none() { + if let Some(lease) = &cache.lease { + lease.verify_path(root)?; + } else { let lease = lifecycle::startup_lease(root, policy.image_wait(lifecycle::STARTUP_LEASE_WAIT)?)?; let staging = root.with_file_name("image-staging"); if staging.try_exists().map_err(state::io)? { clean_staging(&staging, 0)?; } + lease.verify_path(root)?; cache.lease = Some(lease); } - cache.lease.as_ref().unwrap().verify_path(root)?; cache.users += 1; Ok(CacheLease(self)) } diff --git a/src/backends/native-image-tags.ts b/src/backends/native-image-tags.ts index 9c7127d03..645a226f8 100644 --- a/src/backends/native-image-tags.ts +++ b/src/backends/native-image-tags.ts @@ -13,6 +13,7 @@ import { admitNativeProjectBuilds, nativeBuildBases, nativeServiceActive, + refuseManagedSecretBuildArguments, } from "./native-project-builds.ts"; import { admitNativeProjectImages } from "./native-project-image-admission.ts"; import { @@ -198,6 +199,10 @@ export async function pullNativeProjectImages(opts: { composeFile: opts.project.composeFile, enabled: true, }); + refuseManagedSecretBuildArguments({ + builds, + managedSecretValues: input.managedSecretValues ?? [], + }); bases = await nativeBuildBases({ projectRoot: opts.project.projectRoot, runtime: opts.runtime, diff --git a/tests/native-image-tags.test.ts b/tests/native-image-tags.test.ts index fc2960057..78b05371f 100644 --- a/tests/native-image-tags.test.ts +++ b/tests/native-image-tags.test.ts @@ -11,6 +11,9 @@ import { pullNativeProjectImages, } from "../src/backends/native-image-tags.ts"; +import { PROJECT_ENV_KEY_FILENAME } from "../src/constants.ts"; +import { setProjectEnvValue } from "../src/lib/project-env-config.ts"; + const runtime = { binary: "/fixture/hack-native", home: "/fixture/home" }; const projectRoot = "/fixture/project"; @@ -64,6 +67,7 @@ test.each([ "supported", "unsupported field", "unsupported base", + "managed argument", ])("native pull acquires service images first: %s", async (scenario) => { const root = await mkdtemp(join(tmpdir(), "native-pull-build-")); try { @@ -72,6 +76,19 @@ test.each([ const composeFile = join(projectDir, "compose.yaml"); const id = `sha256:${"a".repeat(64)}`; const base = "docker.io/library/alpine:3.20"; + const fixtureValue = "synthetic-managed-fixture"; + if (scenario === "managed argument") { + await writeFile(join(root, PROJECT_ENV_KEY_FILENAME), "synthetic-key"); + await setProjectEnvValue({ + projectRoot: root, + projectDir, + envName: null, + scope: "global", + key: "FIXTURE_KEY", + value: fixtureValue, + secret: true, + }); + } await writeFile( composeFile, `services: @@ -80,7 +97,7 @@ test.each([ app: build: context: .. -${scenario === "unsupported field" ? " ssh: [default]\n" : ""}` +${scenario === "unsupported field" ? " ssh: [default]\n" : ""}${scenario === "managed argument" ? ` args: { BASE: ${fixtureValue} }\n` : ""}` ); const confirmed: string[] = []; const pull = pullNativeProjectImages({ @@ -90,6 +107,7 @@ ${scenario === "unsupported field" ? " ssh: [default]\n" : ""}` invoke: async ({ args }) => { if (args[1] === "build-image") { expect(confirmed).toEqual([id]); + expect(scenario).not.toBe("managed argument"); if (scenario === "unsupported base") { throw new Error("Use public Docker Hub images."); } @@ -115,6 +133,10 @@ ${scenario === "unsupported field" ? " ssh: [default]\n" : ""}` "Native pull could not confirm build bases" ); expect(String(error)).not.toContain("foreground up"); + if (scenario === "managed argument") { + expect(String(error)).toContain("build arg BASE"); + expect(String(error)).not.toContain(fixtureValue); + } expect(confirmed).toEqual([id]); } } finally { From 10986ac34b589560d2d98b69d5835aac1f86109d Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:12:37 +0000 Subject: [PATCH 25/33] fix: protect service images during native base reclamation --- docs/versions/v5/release-notes.md | 7 ++ packages/runtime-core/src/main.rs | 2 +- .../runtime-core/src/provider/image_build.rs | 47 ++++++-- .../src/provider/image_build/reclaim.rs | 6 +- .../src/provider/image_build/tests.rs | 42 ++++++- .../runtime-core/src/provider/image_ensure.rs | 24 +++- .../runtime-core/src/provider/image_load.rs | 5 +- .../src/provider/image_tag_store.rs | 106 ++++++++++++++++-- .../src/provider/registry_image.rs | 9 +- packages/runtime-core/src/provider/state.rs | 33 ++++++ scripts/lib/tla-runtime-models.ts | 8 ++ src/backends/native-project-builds.ts | 2 +- src/backends/native-project-start.ts | 14 ++- src/lib/native-detached-up.ts | 9 ++ tests/models/tla/README.md | 11 ++ .../native-keeper-reclaim/KeeperReclaim.tla | 16 +++ .../tla/native-keeper-reclaim/negative.cfg | 4 + .../tla/native-keeper-reclaim/positive.cfg | 4 + 18 files changed, 306 insertions(+), 43 deletions(-) create mode 100644 tests/models/tla/native-keeper-reclaim/KeeperReclaim.tla create mode 100644 tests/models/tla/native-keeper-reclaim/negative.cfg create mode 100644 tests/models/tla/native-keeper-reclaim/positive.cfg diff --git a/docs/versions/v5/release-notes.md b/docs/versions/v5/release-notes.md index 42c6a5c7d..e88b080f1 100644 --- a/docs/versions/v5/release-notes.md +++ b/docs/versions/v5/release-notes.md @@ -56,6 +56,13 @@ flowchart LR Follow [Upgrade from v4](upgrade.md). It is a backup-first procedure, and it says how to go back. +### Native build receipts and downgrades + +New native build receipts record verified base image IDs for reclamation. After +a downgrade to a runtime that rejects the new receipt field, build-image +reclamation skips cleanup when it encounters those receipts. Upgrade to the +newer runtime to reclaim the images. + ## 2. What you will notice every day **`hack env list` hides every value.** It shows names, scopes and source files. diff --git a/packages/runtime-core/src/main.rs b/packages/runtime-core/src/main.rs index aa2dee07c..bd71fb773 100644 --- a/packages/runtime-core/src/main.rs +++ b/packages/runtime-core/src/main.rs @@ -1285,7 +1285,7 @@ fn run() -> Result<(), CandidateError> { &discover_candidate(&requested)?, &jobs, &image_policy(flags)?, - ))?; + )?)?; } [ "runtime", diff --git a/packages/runtime-core/src/provider/image_build.rs b/packages/runtime-core/src/provider/image_build.rs index a3a523a59..e5ccdc647 100644 --- a/packages/runtime-core/src/provider/image_build.rs +++ b/packages/runtime-core/src/provider/image_build.rs @@ -746,6 +746,20 @@ impl Drop for Flock { } } +pub(super) fn image_fence( + candidate: &Candidate, + mode: libc::c_int, +) -> Result { + let root = builds_root(candidate); + state::private_directory(&root)?; + Flock::try_lock(Flock::open(&root.join("active.lock"))?, mode)?.ok_or_else(|| { + refusal( + "provider_busy", + "Image acquisition or reclamation is in progress; wait for it and retry.", + ) + }) +} + /// Refuse to stop the engine while a build operation is admitted. The caller holds the /// provider lease: a build takes its shared fence only under that lease, so a build /// cannot start between this check and the caller's effect. @@ -758,7 +772,7 @@ pub(super) fn require_no_active_build(candidate: &Candidate) -> Result<(), Candi Some(_probe) => Ok(()), None => Err(refusal( "provider_busy", - "A native image build is running; let it finish or cancel it, then stop the runtime.", + "A native image operation is running; let it finish or cancel it, then stop the runtime.", )), } } @@ -1647,7 +1661,10 @@ fn connect( ) -> Result, CandidateError> { super::engine::Engine::connect_until( candidate, - deadline.unwrap_or_else(|| Instant::now() + LEASE_WAIT), + deadline.map_or_else( + || Instant::now() + LEASE_WAIT, + |deadline| deadline.min(Instant::now() + LEASE_WAIT), + ), || deadline.is_some() && CANCEL_REQUESTED.load(Ordering::Acquire), ) } @@ -1917,12 +1934,17 @@ fn acquire_bases( } fn base_registry_failed(error: &CandidateError) -> bool { - error.code.starts_with("registry_") - || (error.code == "image_tag_offline_missing" - && error - .cause_code - .as_deref() - .is_some_and(|code| code.starts_with("registry_"))) + let cause = error.cause_code.as_deref().unwrap_or(error.code); + matches!( + cause, + "registry_http_429" + | "registry_unreachable" + | "registry_headers_stalled" + | "registry_body_stalled" + ) || cause + .strip_prefix("registry_http_") + .and_then(|status| status.parse::().ok()) + .is_some_and(|status| (500..600).contains(&status)) } fn recover_base_error( @@ -1931,9 +1953,14 @@ fn recover_base_error( deadline: Instant, reuse: impl FnOnce() -> Result, CandidateError>, ) -> Result { - if mode == super::image_policy::ImageTagMode::Normal + use super::image_policy::ImageTagMode::{Normal, Offline, Refresh}; + let eligible = match mode { + Normal => base_registry_failed(&error), + Offline => error.code == "image_tag_offline_missing" && error.cause_code.is_none(), + Refresh => false, + }; + if eligible && Instant::now() < deadline - && base_registry_failed(&error) && let Ok(Some(outcome)) = reuse() { return Ok(outcome); diff --git a/packages/runtime-core/src/provider/image_build/reclaim.rs b/packages/runtime-core/src/provider/image_build/reclaim.rs index c53438365..31c7e0d44 100644 --- a/packages/runtime-core/src/provider/image_build/reclaim.rs +++ b/packages/runtime-core/src/provider/image_build/reclaim.rs @@ -29,7 +29,7 @@ //! BuildKit cache is then pruned to the build cache budget; that never removes images. use super::{ BuildPool, CACHE_BUDGET, LivePool, Phase, RESERVED_LABEL_PREFIXES, Receipt, builds_root, hex64, - image_id, owner_label, refusal, require_no_active_build, + image_fence, image_id, owner_label, refusal, }; use crate::{Candidate, CandidateError}; use serde::Serialize; @@ -347,7 +347,7 @@ pub(super) fn run( pool: &P, ) -> Result { let (lease, identity) = pool.lease()?; - require_no_active_build(candidate)?; + let _fence = image_fence(candidate, libc::LOCK_EX)?; super::aliases::sweep_stranded( &builds_root(candidate), pool, @@ -374,6 +374,7 @@ pub(super) fn run( } } } + let protected = super::super::image_tag_store::protected_image_ids(candidate); for image in pool.base_images(&lease).unwrap_or_default() { let Some(id) = image["Id"].as_str() else { continue; @@ -383,6 +384,7 @@ pub(super) fn run( }; if !current.bases.contains(id) && !referenced.contains(id) + && protected.as_ref().is_ok_and(|ids| !ids.contains(id)) && image["RepoTags"] .as_array() .is_some_and(|tags| tags.iter().any(|tag| tag == &keeper)) diff --git a/packages/runtime-core/src/provider/image_build/tests.rs b/packages/runtime-core/src/provider/image_build/tests.rs index e6b095ce3..c99a8ae7f 100644 --- a/packages/runtime-core/src/provider/image_build/tests.rs +++ b/packages/runtime-core/src/provider/image_build/tests.rs @@ -2167,6 +2167,13 @@ fn reclaim_keeps_only_two_of_ten_base_keepers_for_one_build() { &serde_json::json!({"image": retained_base}), ) .unwrap(); + let fence = image_fence(&fixture.candidate, libc::LOCK_SH).unwrap(); + assert_eq!( + reclaim::run(&fixture.candidate, &pool).unwrap_err().code, + "provider_busy" + ); + assert_eq!(pool.base_images(&()).unwrap().len(), 11); + drop(fence); reclaim::run(&fixture.candidate, &pool).unwrap(); assert_eq!(pool.base_images(&()).unwrap().len(), 3); fs::remove_file(graphs.join("receipt.json")).unwrap(); @@ -2294,10 +2301,37 @@ fn legacy_reuse_requires_the_original_context_and_a_verified_image() { use super::super::image_policy::ImageTagMode::{Normal, Offline, Refresh}; let registry_error = || missing().with_cause_code("registry_unreachable".into()); let soon = Instant::now() + Duration::from_secs(5); - for mode in [Offline, Refresh] { - let error = - recover_base_error(registry_error(), mode, soon, || panic!("must refuse")).unwrap_err(); - assert_eq!(error.code, "image_tag_offline_missing"); + assert_eq!( + recover_base_error(registry_error(), Refresh, soon, || panic!("must refuse")) + .unwrap_err() + .code, + "image_tag_offline_missing" + ); + assert!( + recover_base_error(missing(), Offline, soon, || { + reuse_legacy(&fixture.candidate, &pool, &inputs) + }) + .unwrap() + .reused_legacy_key + ); + for cause in [ + "registry_http_401", + "registry_http_404", + "registry_digest_mismatch", + "registry_image", + ] { + let error = CandidateError::new("registry_image", "fixture").with_cause_code(cause.into()); + assert!(!base_registry_failed(&error), "{cause}"); + } + for cause in [ + "registry_http_429", + "registry_http_500", + "registry_http_503", + "registry_headers_stalled", + "registry_body_stalled", + ] { + let error = CandidateError::new("registry_image", "fixture").with_cause_code(cause.into()); + assert!(base_registry_failed(&error), "{cause}"); } assert_eq!( recover_base_error(registry_error(), Normal, Instant::now(), || panic!( diff --git a/packages/runtime-core/src/provider/image_ensure.rs b/packages/runtime-core/src/provider/image_ensure.rs index 21be011d9..82b1de58c 100644 --- a/packages/runtime-core/src/provider/image_ensure.rs +++ b/packages/runtime-core/src/provider/image_ensure.rs @@ -70,8 +70,11 @@ impl ImageCache { if let Some(lease) = &cache.lease { lease.verify_path(root)?; } else { - let lease = - lifecycle::startup_lease(root, policy.image_wait(lifecycle::STARTUP_LEASE_WAIT)?)?; + let lease = state::wait_for_image_lock( + policy.image_wait(std::time::Duration::from_secs(590))?, + "image-cache", + || state::Lock::acquire(root), + )?; let staging = root.with_file_name("image-staging"); if staging.try_exists().map_err(state::io)? { clean_staging(&staging, 0)?; @@ -520,6 +523,7 @@ pub fn ensure_with( policy: &ImagePolicy, platform: PlatformPolicy, ) -> Result { + let _fence = super::image_build::image_fence(candidate, libc::LOCK_SH)?; timed_acquire( Step::ImageEnsure, candidate, @@ -531,12 +535,15 @@ pub fn ensure_with( ) } +type ImageBatchEntry = (usize, Result, u64); + /// Distinct references can prepare archives together. Only the existing loader imports. pub fn ensure_batch( candidate: &Candidate, jobs: &[(String, PlatformPolicy)], policy: &ImagePolicy, -) -> Vec<(usize, Result, u64)> { +) -> Result, CandidateError> { + let _fence = super::image_build::image_fence(candidate, libc::LOCK_SH)?; let cache = ImageCache::default(); let queue = std::sync::atomic::AtomicUsize::new(0); let finished = Mutex::new(Vec::with_capacity(jobs.len())); @@ -575,7 +582,7 @@ pub fn ensure_batch( }); } }); - finished.into_inner().unwrap() + Ok(finished.into_inner().unwrap()) } pub use super::image_tag_store::{present as present_tags, status as tag_status}; @@ -613,7 +620,14 @@ fn timed_acquire( }); attrs.registry_requests = Some(count); attrs.image_index = index.map(|index| index as u64); - result + let image = result?; + if import + && policy.build_deadline.is_none() + && (reference.contains('@') || reference.starts_with("sha256:")) + { + image_tag_store::protect_service_image(candidate, &image.image_id)?; + } + Ok(image) }) } diff --git a/packages/runtime-core/src/provider/image_load.rs b/packages/runtime-core/src/provider/image_load.rs index 7174ae0fd..b0d9d8283 100644 --- a/packages/runtime-core/src/provider/image_load.rs +++ b/packages/runtime-core/src/provider/image_load.rs @@ -755,7 +755,10 @@ pub(super) fn load_cached( resolved_config, |file| { let engine = measure(Step::ImageImportConnect, None, |_| { - connect_for_import(candidate, policy.image_wait(IMPORT_LEASE_WAIT)?) + connect_for_import( + candidate, + policy.image_wait(IMPORT_LEASE_WAIT)?.min(IMPORT_LEASE_WAIT), + ) })?; import(candidate, archive, Some(archive.pin), policy, file, &engine) }, diff --git a/packages/runtime-core/src/provider/image_tag_store.rs b/packages/runtime-core/src/provider/image_tag_store.rs index d6725c44a..f48073247 100644 --- a/packages/runtime-core/src/provider/image_tag_store.rs +++ b/packages/runtime-core/src/provider/image_tag_store.rs @@ -210,6 +210,72 @@ fn record_directory(candidate: &Candidate, reference: &str) -> std::path::PathBu candidate.state_root.join("artifacts/image-tags").join(key) } +fn service_pins(candidate: &Candidate) -> std::path::PathBuf { + candidate.state_root.join("artifacts/service-image-pins") +} + +/// Immutable service inputs have no mutable tag record. Record the verified ID +/// under the shared fence before returning it to the caller. +pub(super) fn protect_service_image(candidate: &Candidate, id: &str) -> Result<(), CandidateError> { + if !matches!(normalize(id), Ok(ImageReference::ImageId(_))) { + return Err(invalid()); + } + state::private_directory(&service_pins(candidate).join(id)) +} + +/// Current selections are retained even after their registry freshness expires. +pub(super) fn protected_image_ids( + candidate: &Candidate, +) -> Result, CandidateError> { + let root = candidate.state_root.join("artifacts/image-tags"); + crate::reject_aliased_state(&root)?; + let mut ids = std::collections::BTreeSet::new(); + let pins = service_pins(candidate); + crate::reject_aliased_state(&pins)?; + if pins.try_exists().map_err(state::io)? { + for entry in std::fs::read_dir(&pins).map_err(state::io)? { + let entry = entry.map_err(state::io)?; + let id = entry.file_name().into_string().map_err(|_| invalid())?; + if !matches!(normalize(&id), Ok(ImageReference::ImageId(_))) { + return Err(invalid()); + } + state::check_private_directory(&entry.path())?; + ids.insert(id); + } + } + let entries = match std::fs::read_dir(&root) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(ids), + Err(error) => return Err(state::io(error)), + }; + for entry in entries { + let directory = entry.map_err(state::io)?.path(); + crate::reject_aliased_state(&directory)?; + let path = directory.join("resolution.json"); + match std::fs::symlink_metadata(&path) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue, + Err(error) => return Err(state::io(error)), + Ok(_) => {} + } + let record: TagRecord = state::read_bounded(&path, 4096)?; + let ImageReference::Named(named) = normalize(&record.reference).map_err(|_| invalid())? + else { + return Err(invalid()); + }; + record.validate(&named)?; + if record_directory(candidate, &record.reference) != directory { + return Err(invalid()); + } + ids.extend( + record + .selections + .into_iter() + .map(|selection| selection.image_id), + ); + } + Ok(ids) +} + #[derive(Serialize)] pub struct TagStatus { #[serde(flatten)] @@ -424,20 +490,13 @@ fn resolve_pending( // resolution another process just published. let lock = match state::Lock::acquire(&root) { Err(error) if error.code == "provider_busy" => { - let report_wait = std::env::var("HACK_INTERNAL_REPORT_IMAGE_WAIT").unwrap_or_default(); - match report_wait.as_str() { - "batch" => eprintln!("hack.image-wait:begin {canonical}"), - "1" => eprintln!("hack.image-wait:begin"), - _ => (), - } let lock = policy .image_wait(std::time::Duration::from_secs(590)) - .and_then(|wait| state::Lock::acquire_existing_waiting(&root, wait)); - match report_wait.as_str() { - "batch" => eprintln!("hack.image-wait:end {canonical}"), - "1" => eprintln!("hack.image-wait:end"), - _ => (), - } + .and_then(|wait| { + state::wait_for_image_lock(wait, &canonical, || { + state::Lock::acquire_existing(&root) + }) + }); lock.map_err(|error| { if error.code == "provider_busy" { CandidateError::new( @@ -654,6 +713,29 @@ mod tests { } } + #[test] + fn keeper_retention_collects_current_tag_selections_and_immutable_service_ids() { + let f = Fixture::new(); + protect_service_image(&f.0, &digest('e')).unwrap(); + let policy = ImagePolicy::default(); + resolve_pending( + &f.0, + TAG, + &policy, + PlatformPolicy::Native, + || Ok(1), + |_| Ok(false), + |_, _, _| Ok(result('a')), + ) + .unwrap() + .publish() + .unwrap(); + assert_eq!( + protected_image_ids(&f.0).unwrap(), + [digest('d'), digest('e')].into_iter().collect() + ); + } + #[test] fn unconfirmed_refresh_does_not_replace_the_published_record() { let f = Fixture::new(); diff --git a/packages/runtime-core/src/provider/registry_image.rs b/packages/runtime-core/src/provider/registry_image.rs index 274f3c61d..bdcd1333d 100644 --- a/packages/runtime-core/src/provider/registry_image.rs +++ b/packages/runtime-core/src/provider/registry_image.rs @@ -1320,8 +1320,8 @@ impl<'a> Fetch<'a> { /// A layer body can fail after its response headers, while it streams: a timeout, /// a connection that ends early, or bytes that do not match. Each such attempt is /// retried up to [`ATTEMPTS`] times, because the blob is content-addressed and the - /// request an idempotent GET. Every attempt's time limit is the layer's size-scaled - /// timeout, cut to what remains of the acquisition deadline, which is never + /// request an idempotent GET. A build uses its remaining acquisition budget. + /// Other callers use the size-scaled timeout, cut to the acquisition deadline, never /// extended; an attempt that would start after it, or a backoff that would outlast /// it, stops with [`NetworkFailureReason::Deadline`]. A failure names the host that /// served the body (after redirects), the attempts made and the last reason. Each @@ -1329,8 +1329,9 @@ impl<'a> Fetch<'a> { /// removed when it is dropped. fn layer(&mut self, d: &Descriptor, directory: &Path) -> Result { let url = self.url("blobs", &d.digest)?; - let timeout = - self.request_timeout + Duration::from_secs(d.size / MIN_BLOB_BYTES_PER_SECOND); + let timeout = self.policy.image_wait( + self.request_timeout + Duration::from_secs(d.size / MIN_BLOB_BYTES_PER_SECOND), + )?; let mut host = url.host_str().unwrap_or("unknown").to_owned(); for attempt in 1..=ATTEMPTS { if self.remaining().is_err() { diff --git a/packages/runtime-core/src/provider/state.rs b/packages/runtime-core/src/provider/state.rs index afe695db5..443bd999f 100644 --- a/packages/runtime-core/src/provider/state.rs +++ b/packages/runtime-core/src/provider/state.rs @@ -154,6 +154,7 @@ impl Lock { } /// Retry acquisition without creating the lock file. + #[cfg(any(target_os = "macos", test))] pub fn acquire_existing_waiting(root: &Path, wait: Duration) -> Result { wait_for_acquisition( Instant::now() + wait, @@ -226,6 +227,38 @@ pub(super) fn wait_for_acquisition( } } +/// Report a contended image lock after two seconds, then clear its progress line. +pub(super) fn wait_for_image_lock( + wait: Duration, + subject: &str, + acquire: impl FnMut() -> Result, +) -> Result { + let started = Instant::now(); + let mut reported = false; + let result = wait_for_acquisition( + started + wait, + || { + if !reported + && started.elapsed() >= Duration::from_secs(2) + && matches!( + std::env::var("HACK_INTERNAL_REPORT_IMAGE_WAIT").as_deref(), + Ok("1" | "batch") + ) + { + eprintln!("hack.image-wait:begin {subject}"); + reported = true; + } + Ok(()) + }, + acquire, + acquisition_expired, + ); + if reported { + eprintln!("hack.image-wait:end {subject}"); + } + result +} + /// Apply a flock operation to a borrowed descriptor. Closing it releases the lock. pub(crate) fn flock(file: &File, operation: libc::c_int) -> std::io::Result<()> { // SAFETY: file is a live owned descriptor; flock does not retain pointers. diff --git a/scripts/lib/tla-runtime-models.ts b/scripts/lib/tla-runtime-models.ts index 4563e9927..a55e61d31 100644 --- a/scripts/lib/tla-runtime-models.ts +++ b/scripts/lib/tla-runtime-models.ts @@ -2840,6 +2840,14 @@ const contracts: readonly ModelContract[] = [ }, ], }, + { + name: "native-keeper-reclaim", + module: "KeeperReclaim", + states: 5, + invariant: "PinPreservesImage", + action: "Reclaim", + fields: ['fence = "pinning"', "keeper = FALSE"], + }, { name: "native-build-retention", module: "BuildRetention", diff --git a/src/backends/native-project-builds.ts b/src/backends/native-project-builds.ts index ab0e86dfa..09e66ec6e 100644 --- a/src/backends/native-project-builds.ts +++ b/src/backends/native-project-builds.ts @@ -375,7 +375,7 @@ function parseBuilt(value: unknown): NativeBuiltImage { : []; if (value.reused_legacy_key === true && value.reused) { fallbacks.push( - "Registry unavailable, using the verified build image for the unchanged context and Dockerfile." + "Using the verified pre-upgrade build image for the unchanged context and Dockerfile." ); } const selections = isRecord(value.base_selections) diff --git a/src/backends/native-project-start.ts b/src/backends/native-project-start.ts index e3b7a62ff..d06b54ad3 100644 --- a/src/backends/native-project-start.ts +++ b/src/backends/native-project-start.ts @@ -821,8 +821,10 @@ async function ensureNativeProjectImage(opts: { ...(opts.imageTagMode ? ["--image-tag-mode", opts.imageTagMode] : []), ], timeoutMs: NATIVE_IMAGE_ENSURE_TIMEOUT_MS, - onImageWait: (waiting) => - reportNativeImageDownloadWait(waiting ? opts.waitReference : null), + onImageWait: (waiting, subject) => + reportNativeImageDownloadWait( + waiting ? (subject ?? opts.waitReference) : null + ), }) .catch((error: unknown) => { if ( @@ -941,7 +943,13 @@ async function pinNativeImageBatch( } return; } - if (!(reference && wave.some((job) => job.reference === reference))) { + if ( + !( + reference && + (reference === "image-cache" || + wave.some((job) => job.reference === reference)) + ) + ) { return; } if (active) { diff --git a/src/lib/native-detached-up.ts b/src/lib/native-detached-up.ts index fb8a2feee..cacc5156b 100644 --- a/src/lib/native-detached-up.ts +++ b/src/lib/native-detached-up.ts @@ -598,6 +598,15 @@ function writeHotReload(value: unknown): boolean { export function reportNativeImageDownloadWait(reference: string | null): void { publishImageDownloadWait?.(reference); + if (reference) { + const line = + reference === "image-cache" + ? "Waiting for the native image cache lock." + : `Waiting for another start to resolve or download ${reference}.`; + if (!reportNativeImageNotice(line)) { + process.stderr.write(`${line}\n`); + } + } } export function reportNativeImageNotice(notice: string): boolean { diff --git a/tests/models/tla/README.md b/tests/models/tla/README.md index 38772c37c..b6f9f3710 100644 --- a/tests/models/tla/README.md +++ b/tests/models/tla/README.md @@ -1903,3 +1903,14 @@ outside the provider lease. The Rust regressions exercise journal and tag recovery, and the classic worker wire count exercises registry isolation. [Build alias state chart](native-build-alias/build-alias.svg) + +## Keeper reclamation + +`native-keeper-reclaim/KeeperReclaim.tla` models a superseded base whose keeper +is its last engine tag. `BeginPin` takes the shared image fence in +`image_ensure`; `PublishPin` publishes a tag resolution or immutable service ID +before the shared fence drops. `Reclaim` represents exclusive fence acquisition, +the protected-ID scan, and keeper removal under the provider lease. The negative +control removes the fence guard and can remove the base while pinning. The model +abstracts failed requests, multiple IDs, graph and build receipts, and Docker's +last-tag deletion behavior. diff --git a/tests/models/tla/native-keeper-reclaim/KeeperReclaim.tla b/tests/models/tla/native-keeper-reclaim/KeeperReclaim.tla new file mode 100644 index 000000000..88ea0c726 --- /dev/null +++ b/tests/models/tla/native-keeper-reclaim/KeeperReclaim.tla @@ -0,0 +1,16 @@ +---- MODULE KeeperReclaim ---- +CONSTANT UnsafeFence +VARIABLES fence, keeper, tagged +vars == <> +Init == /\ fence = "free" /\ keeper = TRUE /\ tagged = FALSE +BeginPin == /\ fence = "free" /\ keeper + /\ fence' = "pinning" /\ UNCHANGED <> +PublishPin == /\ fence = "pinning" /\ keeper + /\ tagged' = TRUE /\ fence' = "free" /\ UNCHANGED keeper +Reclaim == /\ fence = "free" \/ UnsafeFence + /\ keeper /\ ~tagged + /\ keeper' = FALSE /\ UNCHANGED <> +Next == BeginPin \/ PublishPin \/ Reclaim +Spec == Init /\ [][Next]_vars +PinPreservesImage == (fence = "pinning" \/ tagged) => keeper +==== diff --git a/tests/models/tla/native-keeper-reclaim/negative.cfg b/tests/models/tla/native-keeper-reclaim/negative.cfg new file mode 100644 index 000000000..97c18fb2a --- /dev/null +++ b/tests/models/tla/native-keeper-reclaim/negative.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANT UnsafeFence = TRUE +INVARIANT PinPreservesImage +CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-keeper-reclaim/positive.cfg b/tests/models/tla/native-keeper-reclaim/positive.cfg new file mode 100644 index 000000000..7b74acbd8 --- /dev/null +++ b/tests/models/tla/native-keeper-reclaim/positive.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANT UnsafeFence = FALSE +INVARIANT PinPreservesImage +CHECK_DEADLOCK FALSE From 7046ea1ebe0f73e9ccf195e48093a875baa2b796 Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:16:15 +0000 Subject: [PATCH 26/33] fix: scope the native lease helper to macOS --- packages/runtime-core/src/provider/state.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/runtime-core/src/provider/state.rs b/packages/runtime-core/src/provider/state.rs index 443bd999f..49a3e964a 100644 --- a/packages/runtime-core/src/provider/state.rs +++ b/packages/runtime-core/src/provider/state.rs @@ -154,7 +154,7 @@ impl Lock { } /// Retry acquisition without creating the lock file. - #[cfg(any(target_os = "macos", test))] + #[cfg(target_os = "macos")] pub fn acquire_existing_waiting(root: &Path, wait: Duration) -> Result { wait_for_acquisition( Instant::now() + wait, From c602cc8ff0f05202087609d4c2549468ccf10fb3 Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:39:12 +0000 Subject: [PATCH 27/33] fix: wait for image reclamation before pinning services --- .../runtime-core/src/provider/image_build.rs | 28 +++++++++-------- .../src/provider/image_build/reclaim.rs | 2 +- .../src/provider/image_build/tests.rs | 6 ++++ .../runtime-core/src/provider/image_ensure.rs | 31 +++++++++++++++++-- .../src/provider/image_tag_store.rs | 3 +- .../runtime-core/src/provider/lifecycle.rs | 4 +-- src/backends/native-project-start.ts | 1 + src/lib/native-detached-up.ts | 8 ++--- tests/models/tla/README.md | 4 +-- 9 files changed, 62 insertions(+), 25 deletions(-) diff --git a/packages/runtime-core/src/provider/image_build.rs b/packages/runtime-core/src/provider/image_build.rs index e5ccdc647..083f9f1ad 100644 --- a/packages/runtime-core/src/provider/image_build.rs +++ b/packages/runtime-core/src/provider/image_build.rs @@ -760,9 +760,21 @@ pub(super) fn image_fence( }) } +/// Take the shared fence before asking for the provider lease. +pub(super) fn wait_for_image_fence( + candidate: &Candidate, + policy: &super::image_policy::ImagePolicy, +) -> Result { + let limit = Duration::from_secs(60); + state::wait_for_image_lock( + policy.image_wait(limit)?.min(limit), + "image-reclaim", + || image_fence(candidate, libc::LOCK_SH), + ) +} + /// Refuse to stop the engine while a build operation is admitted. The caller holds the -/// provider lease: a build takes its shared fence only under that lease, so a build -/// cannot start between this check and the caller's effect. +/// provider lease, which prevents further build admission while it stops the engine. pub(super) fn require_no_active_build(candidate: &Candidate) -> Result<(), CandidateError> { let path = builds_root(candidate).join("active.lock"); if !path.try_exists().map_err(state::io)? { @@ -1989,18 +2001,8 @@ pub fn build_image(candidate: &Candidate, request: &Path) -> Result( candidate: &Candidate, pool: &P, ) -> Result { - let (lease, identity) = pool.lease()?; let _fence = image_fence(candidate, libc::LOCK_EX)?; + let (lease, identity) = pool.lease()?; super::aliases::sweep_stranded( &builds_root(candidate), pool, diff --git a/packages/runtime-core/src/provider/image_build/tests.rs b/packages/runtime-core/src/provider/image_build/tests.rs index c99a8ae7f..d79be8b21 100644 --- a/packages/runtime-core/src/provider/image_build/tests.rs +++ b/packages/runtime-core/src/provider/image_build/tests.rs @@ -2168,10 +2168,16 @@ fn reclaim_keeps_only_two_of_ten_base_keepers_for_one_build() { ) .unwrap(); let fence = image_fence(&fixture.candidate, libc::LOCK_SH).unwrap(); + let leases = *pool.leases.borrow(); assert_eq!( reclaim::run(&fixture.candidate, &pool).unwrap_err().code, "provider_busy" ); + assert_eq!( + *pool.leases.borrow(), + leases, + "reclaim took the provider lease" + ); assert_eq!(pool.base_images(&()).unwrap().len(), 11); drop(fence); reclaim::run(&fixture.candidate, &pool).unwrap(); diff --git a/packages/runtime-core/src/provider/image_ensure.rs b/packages/runtime-core/src/provider/image_ensure.rs index 82b1de58c..90b29b40f 100644 --- a/packages/runtime-core/src/provider/image_ensure.rs +++ b/packages/runtime-core/src/provider/image_ensure.rs @@ -523,7 +523,7 @@ pub fn ensure_with( policy: &ImagePolicy, platform: PlatformPolicy, ) -> Result { - let _fence = super::image_build::image_fence(candidate, libc::LOCK_SH)?; + let _fence = super::image_build::wait_for_image_fence(candidate, policy)?; timed_acquire( Step::ImageEnsure, candidate, @@ -543,7 +543,7 @@ pub fn ensure_batch( jobs: &[(String, PlatformPolicy)], policy: &ImagePolicy, ) -> Result, CandidateError> { - let _fence = super::image_build::image_fence(candidate, libc::LOCK_SH)?; + let _fence = super::image_build::wait_for_image_fence(candidate, policy)?; let cache = ImageCache::default(); let queue = std::sync::atomic::AtomicUsize::new(0); let finished = Mutex::new(Vec::with_capacity(jobs.len())); @@ -1167,6 +1167,33 @@ mod tests { platform: platform.candidates()[0], }) } + #[test] + fn ensure_waits_out_reclaim_without_taking_the_provider_lease() { + let f = Fixture::new(); + let candidate = &f.1; + let exclusive = super::super::image_build::image_fence(candidate, libc::LOCK_EX).unwrap(); + let (send, receive) = std::sync::mpsc::channel(); + std::thread::scope(|scope| { + scope.spawn(move || { + let result = ensure(candidate, "invalid reference", &ImagePolicy::default()); + send.send(result.unwrap_err().code).unwrap(); + }); + assert!(matches!( + receive.recv_timeout(std::time::Duration::from_millis(150)), + Err(std::sync::mpsc::RecvTimeoutError::Timeout) + )); + let provider = state::Lock::acquire(&candidate.state_root.join("run/smolvm")).unwrap(); + drop(exclusive); + assert_eq!( + receive + .recv_timeout(std::time::Duration::from_secs(5)) + .unwrap(), + "registry_image" + ); + drop(provider); + }); + } + #[test] fn disk_budget_waits_for_the_current_fetch_and_refuses_an_oversized_archive() { let cache = ImageCache::default(); diff --git a/packages/runtime-core/src/provider/image_tag_store.rs b/packages/runtime-core/src/provider/image_tag_store.rs index f48073247..eb878c536 100644 --- a/packages/runtime-core/src/provider/image_tag_store.rs +++ b/packages/runtime-core/src/provider/image_tag_store.rs @@ -215,7 +215,8 @@ fn service_pins(candidate: &Candidate) -> std::path::PathBuf { } /// Immutable service inputs have no mutable tag record. Record the verified ID -/// under the shared fence before returning it to the caller. +/// under the shared fence before returning it to the caller. The pin store grows by +/// one empty directory per immutable service image. Eviction owns removal (HACK-2569). pub(super) fn protect_service_image(candidate: &Candidate, id: &str) -> Result<(), CandidateError> { if !matches!(normalize(id), Ok(ImageReference::ImageId(_))) { return Err(invalid()); diff --git a/packages/runtime-core/src/provider/lifecycle.rs b/packages/runtime-core/src/provider/lifecycle.rs index 89d884cbe..0acb554a5 100644 --- a/packages/runtime-core/src/provider/lifecycle.rs +++ b/packages/runtime-core/src/provider/lifecycle.rs @@ -2678,7 +2678,7 @@ fn down_observed(candidate: &Candidate) -> Result return Ok(initial); } let lock = state::Lock::acquire(&root(candidate))?; - // Builds take their shared fence only under this lease, so none can start after this. + // The provider lease prevents a build from being admitted after this check. super::image_build::require_no_active_build(candidate)?; let mut owner = Owner::load(candidate)?; let stopped = provider_stopped(&owner.phase, initial.process_alive); @@ -2901,7 +2901,7 @@ fn stop_silent_guest(candidate: &Candidate, owner: &mut Owner) -> Result<(), Can /// (`run/image-builds/active.lock`), so the lease alone does not prove the engine is idle. /// The fence is a `flock`: it is released when the build's processes exit, including on /// SIGKILL, so a refusal lasts only while a build process is alive. Callers hold the -/// operation lease, under which no new build can take the fence. +/// operation lease, which prevents new build admission. fn require_no_build_for_silent_stop(candidate: &Candidate) -> Result<(), CandidateError> { super::image_build::require_no_active_build(candidate).map_err(|error| { if error.code == "provider_busy" { diff --git a/src/backends/native-project-start.ts b/src/backends/native-project-start.ts index d06b54ad3..74a6371c1 100644 --- a/src/backends/native-project-start.ts +++ b/src/backends/native-project-start.ts @@ -947,6 +947,7 @@ async function pinNativeImageBatch( !( reference && (reference === "image-cache" || + reference === "image-reclaim" || wave.some((job) => job.reference === reference)) ) ) { diff --git a/src/lib/native-detached-up.ts b/src/lib/native-detached-up.ts index cacc5156b..7446b63e3 100644 --- a/src/lib/native-detached-up.ts +++ b/src/lib/native-detached-up.ts @@ -599,10 +599,10 @@ function writeHotReload(value: unknown): boolean { export function reportNativeImageDownloadWait(reference: string | null): void { publishImageDownloadWait?.(reference); if (reference) { - const line = - reference === "image-cache" - ? "Waiting for the native image cache lock." - : `Waiting for another start to resolve or download ${reference}.`; + const lock = reference === "image-cache" || reference === "image-reclaim"; + const line = lock + ? `Waiting for the native ${reference === "image-cache" ? "image cache lock" : "image reclamation lock"}.` + : `Waiting for another start to resolve or download ${reference}.`; if (!reportNativeImageNotice(line)) { process.stderr.write(`${line}\n`); } diff --git a/tests/models/tla/README.md b/tests/models/tla/README.md index b6f9f3710..b51793784 100644 --- a/tests/models/tla/README.md +++ b/tests/models/tla/README.md @@ -1909,8 +1909,8 @@ recovery, and the classic worker wire count exercises registry isolation. `native-keeper-reclaim/KeeperReclaim.tla` models a superseded base whose keeper is its last engine tag. `BeginPin` takes the shared image fence in `image_ensure`; `PublishPin` publishes a tag resolution or immutable service ID -before the shared fence drops. `Reclaim` represents exclusive fence acquisition, -the protected-ID scan, and keeper removal under the provider lease. The negative +before the shared fence drops. `Reclaim` represents exclusive fence acquisition before taking the provider lease, followed by the +protected-ID scan and keeper removal. The negative control removes the fence guard and can remove the base while pinning. The model abstracts failed requests, multiple IDs, graph and build receipts, and Docker's last-tag deletion behavior. From 02e1e6cd1dcb706e12ba9cc345d1c8b711441131 Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:39:49 +0000 Subject: [PATCH 28/33] fix: keep the image fence guard independent of policy --- packages/runtime-core/src/provider/image_build.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/runtime-core/src/provider/image_build.rs b/packages/runtime-core/src/provider/image_build.rs index 083f9f1ad..4434c8840 100644 --- a/packages/runtime-core/src/provider/image_build.rs +++ b/packages/runtime-core/src/provider/image_build.rs @@ -749,7 +749,7 @@ impl Drop for Flock { pub(super) fn image_fence( candidate: &Candidate, mode: libc::c_int, -) -> Result { +) -> Result, CandidateError> { let root = builds_root(candidate); state::private_directory(&root)?; Flock::try_lock(Flock::open(&root.join("active.lock"))?, mode)?.ok_or_else(|| { @@ -764,7 +764,7 @@ pub(super) fn image_fence( pub(super) fn wait_for_image_fence( candidate: &Candidate, policy: &super::image_policy::ImagePolicy, -) -> Result { +) -> Result, CandidateError> { let limit = Duration::from_secs(60); state::wait_for_image_lock( policy.image_wait(limit)?.min(limit), From f472316d927e85b5f50cc7143778daff1975198b Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:07:48 +0000 Subject: [PATCH 29/33] fix: canonicalize native runtime request directories --- .../src/provider/image_build/tests.rs | 33 ++++++ src/backends/native-preflight.ts | 6 +- src/backends/native-project-builds.ts | 8 +- .../native-project-restart-preflight.ts | 8 +- src/backends/native-project-review.ts | 6 +- src/backends/native-project-start.ts | 7 +- src/lib/native-runtime-temp.ts | 16 +++ tests/native-project-builds.test.ts | 105 ++++++++++++------ 8 files changed, 139 insertions(+), 50 deletions(-) create mode 100644 src/lib/native-runtime-temp.ts diff --git a/packages/runtime-core/src/provider/image_build/tests.rs b/packages/runtime-core/src/provider/image_build/tests.rs index e4fc99f45..e36b4520f 100644 --- a/packages/runtime-core/src/provider/image_build/tests.rs +++ b/packages/runtime-core/src/provider/image_build/tests.rs @@ -1144,6 +1144,39 @@ fn code(fixture: &Fixture, request: BuildRequest) -> &'static str { .code } +#[test] +fn shared_batch_checks_request_parent_before_admitting_the_build() { + let fixture = Fixture::new(); + let physical = fixture.root.join("physical"); + let batch = physical.join("batch"); + state::private_directory(&batch).unwrap(); + let alias = fixture.root.join("alias"); + std::os::unix::fs::symlink(&physical, &alias).unwrap(); + let request = batch.join("request.json"); + // An invalid version keeps this test inside admission, before any pool work. + state::write( + &request, + &serde_json::json!({ + "version": 0, + "project_root": fixture.project, + "context": "app", + "policy": "missing", + "share_command_base_pins": true, + }), + ) + .unwrap(); + assert_eq!( + build_image(&fixture.candidate, &alias.join("batch/request.json")) + .unwrap_err() + .code, + "aliased_state" + ); + assert_eq!( + build_image(&fixture.candidate, &request).unwrap_err().code, + "native_build_request" + ); +} + #[test] fn requests_refuse_unsafe_paths_arguments_and_bounds() { let fixture = Fixture::new(); diff --git a/src/backends/native-preflight.ts b/src/backends/native-preflight.ts index 9ee9c0f91..6025ef5ce 100644 --- a/src/backends/native-preflight.ts +++ b/src/backends/native-preflight.ts @@ -1,6 +1,5 @@ import { createHash } from "node:crypto"; -import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, rm, writeFile } from "node:fs/promises"; import { join, relative } from "node:path"; import { DEFAULT_CADDY_IP } from "../constants.ts"; import { HackCliError } from "../lib/cli-result.ts"; @@ -11,6 +10,7 @@ import { RESERVED_OWNERSHIP_LABEL_PREFIXES, } from "../lib/native-compose-backend-features.ts"; import { NATIVE_ROOT_DOTENV_IGNORED_NOTICE } from "../lib/native-environment-notices.ts"; +import { nativeRuntimeTempDirectory } from "../lib/native-runtime-temp.ts"; import { probeProxyLoopback, resolveProxyLoopbackAddresses, @@ -1526,7 +1526,7 @@ async function collectNativeRuntimeFindings(opts: { let directory: string | undefined; let reply: unknown; try { - directory = await mkdtemp(join(tmpdir(), "hack-native-preflight-")); + directory = await nativeRuntimeTempDirectory("hack-native-preflight-"); const original = await invoke({ runtime: opts.runtime, cwd: opts.projectRoot, diff --git a/src/backends/native-project-builds.ts b/src/backends/native-project-builds.ts index a2fe49516..983768951 100644 --- a/src/backends/native-project-builds.ts +++ b/src/backends/native-project-builds.ts @@ -1,5 +1,4 @@ -import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { realpath, rm, writeFile } from "node:fs/promises"; import { dirname, isAbsolute, @@ -18,6 +17,7 @@ import { type NativeBuilderCommandOptions, nativeBuilderRemedy, } from "../lib/native-image-builder.ts"; +import { nativeRuntimeTempDirectory } from "../lib/native-runtime-temp.ts"; import { nativeImagePolicyArgs, nativeImageRegistryReason, @@ -925,7 +925,7 @@ async function runPendingBuilds(opts: { const imagePolicyArgs = nativeImagePolicyArgs(); // The runtime requires the exact canonical root; it also derives the namespace. const projectRoot = await realpath(opts.projectRoot); - const directory = await mkdtemp(join(tmpdir(), "hack-native-build-")); + const directory = await nativeRuntimeTempDirectory("hack-native-build-"); const cpus = opts.guestCpus ?? 1; const cap = Number.isSafeInteger(cpus) && cpus > 0 @@ -1106,7 +1106,7 @@ export async function nativeBuildBases(opts: { return []; } const projectRoot = await realpath(opts.projectRoot); - const directory = await mkdtemp(join(tmpdir(), "hack-native-build-scan-")); + const directory = await nativeRuntimeTempDirectory("hack-native-build-scan-"); const file = join(directory, "request.json"); const bases = new Set(); try { diff --git a/src/backends/native-project-restart-preflight.ts b/src/backends/native-project-restart-preflight.ts index 1a66349cd..e174bccbc 100644 --- a/src/backends/native-project-restart-preflight.ts +++ b/src/backends/native-project-restart-preflight.ts @@ -1,6 +1,5 @@ import { createHash } from "node:crypto"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { rm, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { ClosedCliError, HackCliError } from "../lib/cli-result.ts"; import { isRecord } from "../lib/guards.ts"; @@ -9,6 +8,7 @@ import { reportNativeImageNotice, } from "../lib/native-detached-up.ts"; import { requireWrappableNativeProcesses } from "../lib/native-process-wrappers.ts"; +import { nativeRuntimeTempDirectory } from "../lib/native-runtime-temp.ts"; import { adaptNativeAwsEnvironment } from "./native-aws-environment.ts"; import type { NativeDependencyOwnerResolver } from "./native-dependency-owners.ts"; import { adaptNativeGcloudEnvironment } from "./native-gcloud-environment.ts"; @@ -150,7 +150,9 @@ async function verifyNativeRestartListeners(opts: { if (opts.cleanedRetry) { return; } - const directory = await mkdtemp(join(tmpdir(), "hack-native-restart-deps-")); + const directory = await nativeRuntimeTempDirectory( + "hack-native-restart-deps-" + ); try { const path = join(directory, "dependencies.json"); await writeFile( diff --git a/src/backends/native-project-review.ts b/src/backends/native-project-review.ts index 2ce06757e..212f480ea 100644 --- a/src/backends/native-project-review.ts +++ b/src/backends/native-project-review.ts @@ -1,9 +1,9 @@ -import { chmod, mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, realpath, rm, writeFile } from "node:fs/promises"; import { join, relative } from "node:path"; import type { BranchDroppedSites } from "../lib/branch-hosts.ts"; import { ClosedCliError, HackCliError } from "../lib/cli-result.ts"; import { isRecord } from "../lib/guards.ts"; +import { nativeRuntimeTempDirectory } from "../lib/native-runtime-temp.ts"; import { nativeEnvironmentUnsetsReviewed } from "./native-environment-unsets.ts"; import { nativeProjectBranchArgs, @@ -367,7 +367,7 @@ export async function withNativeProjectReview(opts: { } const { namespace, projectArgs, retainedGeneration } = identity; const invoke = opts.invoke ?? invokeNativeRuntime; - const directory = await mkdtemp(join(tmpdir(), "hack-native-review-")); + const directory = await nativeRuntimeTempDirectory("hack-native-review-"); try { await chmod(directory, 0o700); const normalized = join(directory, "compose.json"); diff --git a/src/backends/native-project-start.ts b/src/backends/native-project-start.ts index cc28b5802..5535ff28d 100644 --- a/src/backends/native-project-start.ts +++ b/src/backends/native-project-start.ts @@ -1,6 +1,5 @@ import { createHash, randomBytes } from "node:crypto"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { rm, writeFile } from "node:fs/promises"; import { dirname, isAbsolute, join } from "node:path"; import { noteActivityFailedServices } from "../lib/activity-log.ts"; import type { BranchDroppedSites } from "../lib/branch-hosts.ts"; @@ -27,6 +26,7 @@ import { type NativeProcessRefusal, requireWrappableNativeProcesses, } from "../lib/native-process-wrappers.ts"; +import { nativeRuntimeTempDirectory } from "../lib/native-runtime-temp.ts"; import { adaptNativeAwsEnvironment } from "./native-aws-environment.ts"; import { scheduleNativeAwsExpiryWarnings } from "./native-aws-expiry.ts"; import type { NativeDependencyOwnerResolver } from "./native-dependency-owners.ts"; @@ -3205,7 +3205,8 @@ async function startNativeProjectAttempt( restoreRevision: runSelection.sourceRevision, invoke: deps.invoke, }); - const directory = await mkdtemp(join(tmpdir(), "hack-native-start-")); + const directory = + await nativeRuntimeTempDirectory("hack-native-start-"); const run = runSelection.run; const stop = hooks?.stop ? createNativeForegroundStop({ diff --git a/src/lib/native-runtime-temp.ts b/src/lib/native-runtime-temp.ts new file mode 100644 index 000000000..c57c8faea --- /dev/null +++ b/src/lib/native-runtime-temp.ts @@ -0,0 +1,16 @@ +import { mkdtemp, realpath, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +/** Private request directories may become runtime state and must use a physical path. */ +export async function nativeRuntimeTempDirectory( + prefix: string +): Promise { + const directory = await mkdtemp(join(tmpdir(), prefix)); + try { + return await realpath(directory); + } catch (error) { + await rm(directory, { recursive: true, force: true }); + throw error; + } +} diff --git a/tests/native-project-builds.test.ts b/tests/native-project-builds.test.ts index aeae672d1..6c7ddd051 100644 --- a/tests/native-project-builds.test.ts +++ b/tests/native-project-builds.test.ts @@ -4,12 +4,15 @@ import { mkdir, mkdtemp, readFile, + realpath, rm, stat, + symlink, writeFile, } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; import { admitNativeProjectBuild, admitNativeProjectBuilds, @@ -1022,7 +1025,7 @@ test.each([ } }); -test("concurrent builds share a command pin directory and deduplicate notices", async () => { +test("concurrent builds share a physical command pin directory and deduplicate notices", async () => { const projectRoot = await root(); const arrived = Promise.withResolvers(); const directories: string[] = []; @@ -1030,40 +1033,74 @@ test("concurrent builds share a command pin directory and deduplicate notices", const base = "docker.io/library/alpine:latest"; const pin = `docker.io/library/alpine@${IMAGE}`; const notice = "Using a previously verified base."; - await buildNativeProjectImages({ - runtime, - projectRoot, - branch: null, - profiles: [], - builds: new Map([ - ["one", request()], - ["two", request({})], - ]), - specs: { one: { build: "app" }, two: { build: "app" } }, - rebuild: false, - guestCpus: 2, - imageTagMode: "refresh", - signal: new AbortController().signal, - onNotice: (line) => notices.push(line), - invoke: async ({ requestFile }) => { - const body = JSON.parse(await readFile(requestFile, "utf8")); - expect(body.share_command_base_pins).toBe(true); - expect(body.image_tag_mode).toBe("refresh"); - directories.push(dirname(requestFile)); - if (directories.length === 2) { - arrived.resolve(); - } - await arrived.promise; - return { - imageId: IMAGE, - buildKey: KEY, - reused: false, - baseSelections: { [base]: pin }, - baseFallbacks: [notice], - }; - }, - }); + const physical = join(await realpath(projectRoot), "physical"); + const alias = join(projectRoot, "alias"); + const previous = process.env.TMPDIR; + await mkdir(join(physical, "tmp"), { recursive: true }); + await symlink(physical, alias); + process.env.TMPDIR = join(alias, "tmp"); + try { + await buildNativeProjectImages({ + runtime, + projectRoot, + branch: null, + profiles: [], + builds: new Map([ + ["one", request()], + ["two", request({})], + ]), + specs: { one: { build: "app" }, two: { build: "app" } }, + rebuild: false, + guestCpus: 2, + imageTagMode: "refresh", + signal: new AbortController().signal, + onNotice: (line) => notices.push(line), + invoke: async ({ requestFile }) => { + const body = JSON.parse(await readFile(requestFile, "utf8")); + expect(body.share_command_base_pins).toBe(true); + expect(body.image_tag_mode).toBe("refresh"); + directories.push(dirname(requestFile)); + if (directories.length === 2) { + arrived.resolve(); + } + await arrived.promise; + return { + imageId: IMAGE, + buildKey: KEY, + reused: false, + baseSelections: { [base]: pin }, + baseFallbacks: [notice], + }; + }, + }); + } finally { + if (previous === undefined) { + Reflect.deleteProperty(process.env, "TMPDIR"); + } else { + process.env.TMPDIR = previous; + } + } expect(directories).toHaveLength(2); + expect(new Set(directories.map(dirname))).toEqual( + new Set([join(physical, "tmp")]) + ); expect(new Set(directories).size).toBe(1); expect(notices).toEqual([notice]); }); + +test("native runtime requests centralize temporary paths", async () => { + const backends = fileURLToPath(new URL("../src/backends/", import.meta.url)); + const unresolved: string[] = []; + for await (const file of new Bun.Glob("*.ts").scan(backends)) { + const source = await Bun.file(join(backends, file)).text(); + // The HTTPS FIFO is consumed by the shell before exec, not by the runtime. + const requests = source.replace( + 'mkdtempSync(join(tmpdir(), "hk-https-pipe-"))', + "" + ); + if (requests.replaceAll("realpath(tmpdir())", "").includes("tmpdir()")) { + unresolved.push(file); + } + } + expect(unresolved).toEqual([]); +}); From aa27e42cf24e7917321c2acb0d397a81ae827568 Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:22:48 +0000 Subject: [PATCH 30/33] fix: keep native build base retention off startup --- docs/guides/native-candidate.md | 6 +- docs/reference/v5-model-coverage.md | 2 + .../v5/native/existing-compose-project.md | 21 +- packages/runtime-core/src/main.rs | 7 + .../runtime-core/src/provider/build_policy.rs | 14 +- packages/runtime-core/src/provider/engine.rs | 7 + .../runtime-core/src/provider/image_build.rs | 291 ++++++++++++++---- .../src/provider/image_build/aliases.rs | 2 +- .../src/provider/image_build/reclaim.rs | 34 +- .../src/provider/image_build/retain.rs | 115 +++++++ .../src/provider/image_build/tests.rs | 87 +++++- .../runtime-core/src/provider/image_ensure.rs | 34 +- .../runtime-core/src/provider/image_load.rs | 5 +- scripts/lib/tla-runtime-models.ts | 17 + src/backends/native-project-start.ts | 72 +++++ .../BaseScheduling.tla | 33 ++ .../native-build-base-scheduling/negative.cfg | 4 + .../native-build-base-scheduling/positive.cfg | 4 + .../unsafe-overlap.cfg | 4 + 19 files changed, 653 insertions(+), 106 deletions(-) create mode 100644 packages/runtime-core/src/provider/image_build/retain.rs create mode 100644 tests/models/tla/native-build-base-scheduling/BaseScheduling.tla create mode 100644 tests/models/tla/native-build-base-scheduling/negative.cfg create mode 100644 tests/models/tla/native-build-base-scheduling/positive.cfg create mode 100644 tests/models/tla/native-build-base-scheduling/unsafe-overlap.cfg diff --git a/docs/guides/native-candidate.md b/docs/guides/native-candidate.md index 161e8f41b..ace6ca486 100644 --- a/docs/guides/native-candidate.md +++ b/docs/guides/native-candidate.md @@ -507,8 +507,10 @@ With it: not trigger a rebuild. Native checks base-image tags according to the image tag policy and rebuilds when the selected base digest changes. `hack up --offline` uses locally recorded selections even after they expire. `hack up --refresh-images` - checks the registry for current tags. `HACK_NATIVE_REBUILD=1` forces BuildKit to - run on `up` or `hack restart` and keeps the usual base tag freshness policy. + checks the registry for current tags. Ordinary expiry is checked after readiness. + `HACK_NATIVE_REBUILD=1` forces BuildKit to run with the recorded selection. + Cold solves let BuildKit fetch missing bases by digest. Background retention + tags a verified local base or downloads and loads it after readiness. - When an image is actually built, BuildKit reads a private copy of the included context, made and checked against the build key right before it runs, so edits during a build never reach the image. The copy keeps hard links as links and gives every diff --git a/docs/reference/v5-model-coverage.md b/docs/reference/v5-model-coverage.md index a4715ac8a..5ad743688 100644 --- a/docs/reference/v5-model-coverage.md +++ b/docs/reference/v5-model-coverage.md @@ -78,6 +78,7 @@ must be attached to the eventual exact integration revision. | Cached image presence before archive reads | [native-image-presence](../../tests/models/tla/native-image-presence/COVERAGE.md) | `image_load::load_waiting` requires live exact image and platform readback for receipt reuse and verifies the archive on any upload path. Explicit archive loads retain their early hash. | One request, one archive, one lease, one boot. Expiry and registry availability may change before tag selection. Guest eviction may precede readback or create. Guest ownership, filesystem behavior, interrupted imports and performance require separate runtime evidence. | | Native up build batch: authored dispatch, bounded concurrency, stop and drain | [native-build-batch](../../tests/models/tla/native-build-batch/COVERAGE.md) | `runPendingBuilds` captures the first failure and drains every started invocation. Controlled runtime and source CLI SIGINT regressions cover cancellation and caller exit. | Four distinct keys and a cap of three. Per-key leases and receipts are covered by native-build-retention; actual VM settlement remains host evidence. | | Native image builds: unleased build versus engine stop, crash mid-build, storage recreation, foreign or forged images, reclamation versus retained graph references | native-build-retention | `provider::image_build` (shared build fence, per-key lock, incarnation/boot/engine recheck and label check at adoption, dead-attempt recording) and `image_build::reclaim` (owned labels, current receipts, retained graph state scan, engine non-force removal); `image_build` regressions | One key and namespace. Since key version 2 (HACK-2533) every edited build context makes a new key with its own receipt; reclamation keeps, per build declaration, the current and one previous key's image, plus every image retained state (except its diagnostic restore history, HACK-2554) or a container references and every receipt without a declaration, and an `up` that built runs it best-effort after readiness (`image_build::tests::ten_edits_of_one_build_leave_its_current_and_previous_images`); the model's retained-reference safety is unchanged, and which receipt is current is regression-tested, not modeled. Snapshots of a dead owner are removed at the next build in the namespace, only after the owner is proven gone and under that key's lock (`snapshots_of_dead_owners_are_removed_at_the_next_build_of_any_key`). Which inputs a key covers (context walk, ignore rules, hard-link groups, stat cache) and restore's per-up build decision are regression-tested in `image_build::context` and `image_build` and in `tests/native-project-builds.test.ts`, not modeled. A build client orphaned by a killed `hack-native` is not modeled (the client inherits the build fence and per-key lock, so both stay held until it exits: `image_build::tests::a_killed_coordinator_leaves_its_client_fenced`); real BuildKit, engine removal semantics and guest storage are host evidence. | +| Native build-base scheduling | native-build-base-scheduling | `reuse_receipt` uses local proof and read-only engine observation. `run_with_bases` sends cold pins to BuildKit. `retain::run` checks the image fence and provider lease before retaining pinned inputs. | One base, one build receipt, and one background worker. A foreground request may arrive while the worker holds the provider lease. The model covers admitted work, not provider wait budgets, transfer, or guest-side cancellation. | | Native build-base alias lifetime | native-build-alias | `image_build::aliases` journals before publishing, keeps a cache reference, and sweeps only while holding the attempt key lock; tests exercise the live lock and stranded journal. | One base and one attempt. The verified pin and per-attempt name are enforced in Rust. The model abstracts registry transport and Docker's image deletion behavior. | | Runtime service per native home (HACK-2460, design): start race, crash at any step, version skew and drain, lost replies, resends on new connections, one-shot fallback, inspection of started but unfinished work | runtime-service | Process half implemented as a library; nothing starts or calls it yet. `TakeLock`, `LoseRace` and `Bind` map to `service::start` (a lock on the private `run/service/` directory, then `service.lock`, each checked against its path and held for the process's whole life, drain included; an existing socket is probed and kept if anything answers). `IdleExit`, `Retire`, `RefuseDraining` and `ExitDrained` map to `run`, `refuse_queued` and `shut_down`, with `settle` releasing ownership only after a complete drain. The tests in `packages/runtime-core/src/service/tests.rs` walk each action (concurrent starts, lock replacement while serving and while draining, stale and live sockets, idle exit with a held session, retire, connections queued at shutdown, drain timeout). `Crash` gets its real-process SIGKILL test in the next slice. Intent records, admission of mutations, skew, fallback and inspection are not implemented; each later slice adds the regression that walks its actions, behind `HACK_RUNTIME_SERVICE` (default `off`) | Not modelled, covered by regression tests instead: a lock held for a moment after its owner let go, because a forked child shares the open file description until it runs `exec` (the starter's bounded retry window, `service/tests.rs`); the time bound on that window; a drain that runs out of time ending the process at once with exit code 3; a signal (TERM, INT, HUP) draining like retire; and a starter that never reads the notify line (`tests/runtime_service_contract.rs`, `tests/runtime_service_hooks.rs`). The model treats a release as immediate and every drain as finishing. Implemented slice assumes the `run/service/` directory itself is not replaced (replacing `service.lock` is covered) and that the process exits after a drain that ran out of its 10 s bound; it refuses, never serves, connections queued at stop. Assumption each mutation slice must meet: its inspector distinguishes proven absence from missing evidence (for example work a provider accepted but has not yet made visible), and missing evidence yields "unknown", never "not done"; the model makes dispatched work visible at once. Liveness, several leases, cancellation of joined attempts, event cursors, dashboard authentication, the idle-exit queue race and intent-write durability are not modelled. | | MCP cold start, cancellation and duplicate launches | mcp-startup, mcp-startup-cancellation | Shared MCP bundle identity, startup deduplication and cancellation regressions | Fresh supported client sessions, full workflow coverage and measured overhead (WU16/WU20/WU28). | @@ -153,6 +154,7 @@ liveness/reachability controls have their own documented assumptions. | [native-pool-stop](../../tests/models/tla/native-pool-stop/PoolStop.tla) | 210 | 10 | | [start-graph](../../tests/models/tla/start-graph/COVERAGE.md) | 1,656,372 + 81,534 two-boot | 10 | | [probe-readiness](../../tests/models/tla/probe-readiness/ProbeReadiness.tla) | 175,757 | 7 | +| [native-build-base-scheduling](../../tests/models/tla/native-build-base-scheduling/BaseScheduling.tla) | 12 | 2 | | [native-build-alias](../../tests/models/tla/native-build-alias/BuildAlias.tla) | 23 | 5 | | [native-build-batch](../../tests/models/tla/native-build-batch/BuildBatch.tla) | 296 | 2 | | [native-build-retention](../../tests/models/tla/native-build-retention/BuildRetention.tla) | 6,181 | 4 | diff --git a/docs/versions/v5/native/existing-compose-project.md b/docs/versions/v5/native/existing-compose-project.md index 82653db9b..47542aa99 100644 --- a/docs/versions/v5/native/existing-compose-project.md +++ b/docs/versions/v5/native/existing-compose-project.md @@ -83,12 +83,21 @@ the build read. Change any of them and the next `up` builds again, also after volumes are kept. `hack restart` checks the same inputs before it stops anything: a build that fails leaves the current project running, and a rebuilt image is what the restarted project runs. A changed download in a `RUN` step or changed cache mount -contents do not trigger a rebuild. A changed base digest does. Use -`hack up --refresh-images` to check base tags now or `hack up --offline` to use -locally recorded selections even after they expire. `HACK_NATIVE_REBUILD=1` forces -a build with the usual base tag freshness policy. After an `up` that built, native removes the -older images of each build, keeping the current one, the one before it and any image -a run still uses. +contents do not trigger a rebuild. A changed base digest does. An unchanged build +verifies its receipt from local state before acquiring any base. Ordinary tag expiry +is checked in the background after readiness. Use `hack up --refresh-images` to +check base tags during startup. `HACK_NATIVE_REBUILD=1` forces a build with the +recorded selection. + +For a cold build, BuildKit fetches any missing base by digest during the solve. After +readiness, native tries to retain the exact bases from current and previous builds, +one at a time. It tags a matching local engine image when available and otherwise +downloads and imports the base. It defers when startup, stop, build, or reclamation +already holds the required locks. Retention has a 30-minute budget and logs failures +without changing the startup result. `hack up --offline` can reuse an unchanged +build. An edited build also needs its verified base loaded in the guest. After an +`up` that built, native removes superseded build images while keeping the current +and previous image and any image a run still uses. **Host aliases** (`extra_hosts` with `host-gateway`, or `internal.extra_hosts`). Native's VM has no route to your machine except through a binding to one host diff --git a/packages/runtime-core/src/main.rs b/packages/runtime-core/src/main.rs index bd71fb773..2f83ae5db 100644 --- a/packages/runtime-core/src/main.rs +++ b/packages/runtime-core/src/main.rs @@ -120,6 +120,7 @@ Usage: hack-local runtime admit-image --reference <[registry/]repository[:tag][@sha256:digest]|sha256:image-id> --json [IMAGE-POLICY] hack-local runtime build-image --request --json hack-local runtime reclaim-build-images [--best-effort] --json + hack-local runtime retain-build-bases --json [IMAGE-POLICY] hack-local runtime ensure-image --reference <[registry/]repository[:tag]|[registry/]repository@sha256:digest|sha256:image-id> [--emulation native|prefer-native|amd64] --json [IMAGE-POLICY] hack-local runtime cache-image --reference REF [--emulation native|prefer-native|amd64] --json [IMAGE-POLICY] hack-local runtime image-tag-status --json [REFERENCE...] @@ -1346,6 +1347,12 @@ fn run() -> Result<(), CandidateError> { Path::new(request), )?)?; } + ["runtime", "retain-build-bases", "--json", policy @ ..] => { + print_json(&hack_runtime_core::provider::image_build::retain::run( + &discover_candidate(&requested)?, + image_policy(policy)?, + )?)?; + } ["runtime", "reclaim-build-images", "--best-effort", "--json"] => { // Never fails: a refusal is reported as `skipped`, for callers such as `up`. print_json( diff --git a/packages/runtime-core/src/provider/build_policy.rs b/packages/runtime-core/src/provider/build_policy.rs index 37300aca6..41519e763 100644 --- a/packages/runtime-core/src/provider/build_policy.rs +++ b/packages/runtime-core/src/provider/build_policy.rs @@ -58,11 +58,7 @@ pub fn document<'a>(pinned: impl IntoIterator) -> Result( sources: impl IntoIterator, ) -> Result { - let sources: Vec<_> = sources.into_iter().collect(); - let aliases = sources - .iter() - .any(|source| super::image_build::aliases::allowed(source)); - document_for(sources, aliases) + document_for(sources, true) } fn document_for<'a>( @@ -71,13 +67,7 @@ fn document_for<'a>( ) -> Result { let mut allowed = BTreeSet::new(); for reference in pinned { - if aliases { - if !super::image_build::aliases::allowed(reference) { - return Err(CandidateError::new( - "native_build_base_image", - "BuildKit requires an owned local base alias.", - )); - } + if aliases && super::image_build::aliases::allowed(reference) { allowed.insert(format!("docker-image://{reference}")); continue; } diff --git a/packages/runtime-core/src/provider/engine.rs b/packages/runtime-core/src/provider/engine.rs index 10f1bdc37..06880c6c7 100644 --- a/packages/runtime-core/src/provider/engine.rs +++ b/packages/runtime-core/src/provider/engine.rs @@ -669,6 +669,13 @@ impl<'a> Observer<'a> { Ok(value) } + pub(super) fn identity_document(&self) -> Result { + self.guest.verify()?; + let result = self.transport.request(Method::GET, "/v1.53/info", None); + self.guest.verify()?; + result + } + /// Fixed read-only image endpoint. Recheck ownership on both success and /// 404 so an absence after a guest change cannot authorize a load. pub(super) fn image(&self, image: &str) -> Result { diff --git a/packages/runtime-core/src/provider/image_build.rs b/packages/runtime-core/src/provider/image_build.rs index eac670d1b..9d39c2914 100644 --- a/packages/runtime-core/src/provider/image_build.rs +++ b/packages/runtime-core/src/provider/image_build.rs @@ -87,6 +87,7 @@ mod client_relay; mod context; mod output; pub mod reclaim; +pub mod retain; #[cfg(test)] mod tests; @@ -272,6 +273,13 @@ pub(super) trait BuildPool { type Lease; /// Take the provider lease, verify the running pool, its build network and engine. fn lease(&self) -> Result<(Self::Lease, PoolIdentity), CandidateError>; + fn try_lease(&self) -> Result<(Self::Lease, PoolIdentity), CandidateError> { + self.lease() + } + fn observe_build(&self, image: &str) -> Result<(PoolIdentity, Option), CandidateError> { + let (lease, identity) = self.try_lease()?; + Ok((identity, self.inspect(&lease, image)?)) + } fn cleanup_lease(&self) -> Result<(Self::Lease, PoolIdentity), CandidateError> { self.lease() } @@ -313,6 +321,7 @@ pub(super) struct Inputs { target: Option, args: BTreeMap, images: Vec, + tag_mode: super::image_policy::ImageTagMode, policy: Policy, timeout: Duration, /// Every included context entry the key walk hashed; a build copies exactly these @@ -681,6 +690,7 @@ pub(super) fn prepare(request: BuildRequest, builds: &Path) -> Result Result { + let root = builds_root(candidate); + state::private_directory(&root)?; + let lock = Flock::try_lock(Flock::open(&root.join("active.lock"))?, libc::LOCK_EX)? + .ok_or_else(|| refusal("provider_busy", "The image fence is in use."))?; + // SAFETY: the descriptor remains owned by lock. The provider lease already + // excludes mutating work across the flock conversion. + if unsafe { libc::flock(lock.0.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) } != 0 { + return Err(refusal("provider_busy", "The image fence is in use.")); + } + Ok(lock) +} + pub(super) fn wait_for_image_fence( candidate: &Candidate, policy: &super::image_policy::ImagePolicy, @@ -845,13 +868,12 @@ fn owned_image( } } -fn reuse_verified( +fn reuse_verified( candidate: &Candidate, - pool: &P, - (lease, identity): (&P::Lease, &PoolIdentity), inputs: &Inputs, path: &Path, previous: &Receipt, + observe: impl FnOnce(&str) -> Result<(PoolIdentity, Option), CandidateError>, ) -> Result, CandidateError> { if inputs.policy == Policy::Missing && previous.version == 1 @@ -859,12 +881,16 @@ fn reuse_verified( && previous.build_key == inputs.key && previous.phase == Phase::ContentIdVerified && previous.checkout == candidate.checkout - && previous.provider_incarnation == identity.incarnation - && previous.engine_id == identity.engine_id && let Some(id) = previous.image_id.as_deref().filter(|id| image_id(id)) - && let Some(inspected) = pool.inspect(lease, id)? - && owned_image(&inspected, id, &labels(inputs, identity)).is_ok() { + let (identity, inspected) = observe(id)?; + if previous.provider_incarnation != identity.incarnation + || previous.engine_id != identity.engine_id + || !inspected + .is_some_and(|image| owned_image(&image, id, &labels(inputs, &identity)).is_ok()) + { + return Ok(None); + } let mut current = previous.clone(); current.provider_boot_id = identity.boot_id.clone(); current.declaration = Some(inputs.declaration.clone()); @@ -875,10 +901,11 @@ fn reuse_verified( Ok(None) } -fn reuse_legacy( +fn reuse_receipt( candidate: &Candidate, pool: &P, inputs: &Inputs, + expected: Option<&BTreeMap>, ) -> Result, CandidateError> { if inputs.policy != Policy::Missing { return Ok(None); @@ -888,7 +915,7 @@ fn reuse_legacy( if !path.try_exists().map_err(state::io)? { return Ok(None); } - let (lease, identity) = pool.lease()?; + let _fence = image_fence(candidate, libc::LOCK_SH)?; let lock = Flock::open(&directory.join(format!("{}.lock", inputs.key)))?; let Some(_lock) = Flock::try_lock(lock, libc::LOCK_EX)? else { return Ok(None); @@ -896,6 +923,17 @@ fn reuse_legacy( let Some(previous) = read_receipt(&path)? else { return Ok(None); }; + if let Some(expected) = expected + && (expected.len() != previous.base_pins.len() + || expected + .iter() + .any(|(name, base)| previous.base_pins.get(name) != Some(&base.pinned_reference))) + { + return Err(refusal( + "native_build_receipt", + "A build receipt has unexpected base pins.", + )); + } if path .with_extension("pending") .try_exists() @@ -903,15 +941,38 @@ fn reuse_legacy( { return Ok(None); } - let mut outcome = reuse_verified( - candidate, - pool, - (&lease, &identity), - inputs, - &path, - &previous, - )?; + reuse_verified(candidate, inputs, &path, &previous, |id| { + pool.observe_build(id) + }) +} + +fn reuse_legacy( + candidate: &Candidate, + pool: &P, + inputs: &Inputs, +) -> Result, CandidateError> { + let mut outcome = reuse_receipt(candidate, pool, inputs, None)?; if let Some(reused) = &mut outcome { + for base in &inputs.images { + let reference = base.reference.canonical(); + let Some(pin) = reused.base_pins.get(&base.context_name) else { + return Ok(None); + }; + let (canonical, _) = registry_image::pinned_syntax(pin)?; + let matches = if reference.contains('@') { + reference == canonical + } else { + reference.rsplit_once(':').is_some_and(|(repo, _)| { + canonical + .strip_prefix(repo) + .is_some_and(|suffix| suffix.starts_with('@')) + }) + }; + if !matches || canonical != *pin { + return Ok(None); + } + reused.base_selections.insert(reference, canonical); + } reused.reused_legacy_key = true; } Ok(outcome) @@ -982,14 +1043,9 @@ fn run_with_bases( "A build receipt does not match its path; no image was adopted or replaced.", )); } - if let Some(outcome) = reuse_verified( - candidate, - pool, - (&lease, &identity), - inputs, - &receipt_path, - previous, - )? { + if let Some(outcome) = reuse_verified(candidate, inputs, &receipt_path, previous, |id| { + Ok((identity.clone(), pool.inspect(&lease, id)?)) + })? { // Recovery cannot invalidate the verified reuse decision. let _ = aliases::sweep(pool, &lease, &identity, &alias_path); return Ok(outcome); @@ -1057,6 +1113,22 @@ fn run_with_bases( "The native runtime's storage disk has too little free space for this build (at least 6 GiB, or twice the last image of this build). Inspect it with `runtime guest-disk-usage` and remove unused images or data; nothing was deleted.", )); } + let mut local = BTreeMap::new(); + for (name, base) in selected { + let present = pool.inspect(&lease, &base.image_id)?.is_some_and(|image| { + image["Id"] == base.image_id + && image["Os"] == "linux" + && image["Architecture"] == "arm64" + }); + if present { + local.insert(name.clone(), base.clone()); + } else if inputs.tag_mode == super::image_policy::ImageTagMode::Offline { + return Err(refusal( + "image_archive_offline_missing", + "The verified build base is not loaded in the guest.", + )); + } + } let mut receipt = Receipt { version: 1, checkout: candidate.checkout.clone(), @@ -1080,8 +1152,10 @@ fn run_with_bases( sequence: previous.as_ref().and_then(|receipt| receipt.sequence), }; state::write(&receipt_path, &receipt)?; - let (aliases, worker_pins) = - aliases::Aliases::prepare(pool, &lease, &identity, alias_path, selected)?; + let (aliases, local_pins) = + aliases::Aliases::prepare(pool, &lease, &identity, alias_path, &local)?; + let mut worker_pins = pins.clone(); + worker_pins.extend(local_pins); drop(lease); // Step 4, unleased: run the client in its own process group. @@ -1740,19 +1814,12 @@ fn verify_build_network(engine: &super::engine::Engine<'_>) -> Result<(), Candid Ok(()) } -impl<'a> BuildPool for LivePool<'a> { - type Lease = super::engine::Engine<'a>; - fn lease(&self) -> Result<(Self::Lease, PoolIdentity), CandidateError> { - let engine = connect(self.candidate, self.build_deadline)?; - verify_build_network(&engine)?; +impl<'a> LivePool<'a> { + fn identify( + engine: super::engine::Engine<'a>, + ) -> Result<(super::engine::Engine<'a>, PoolIdentity), CandidateError> { let info = engine.request(reqwest::Method::GET, "/v1.53/info", None)?; - let engine_id = info["ID"] - .as_str() - .filter(|id| { - !id.is_empty() && id.len() <= 128 && id.bytes().all(|b| b.is_ascii_graphic()) - }) - .ok_or_else(|| refusal("engine_protocol", "The engine reported no usable identity."))? - .to_owned(); + let engine_id = engine_id(&info)?; let identity = PoolIdentity { incarnation: engine.guest().incarnation().to_owned(), boot_id: engine.guest().boot_id().to_owned(), @@ -1761,6 +1828,41 @@ impl<'a> BuildPool for LivePool<'a> { }; Ok((engine, identity)) } +} + +fn engine_id(info: &Value) -> Result { + info["ID"] + .as_str() + .filter(|id| !id.is_empty() && id.len() <= 128 && id.bytes().all(|b| b.is_ascii_graphic())) + .map(str::to_owned) + .ok_or_else(|| refusal("engine_protocol", "The engine reported no usable identity.")) +} +impl<'a> BuildPool for LivePool<'a> { + type Lease = super::engine::Engine<'a>; + fn lease(&self) -> Result<(Self::Lease, PoolIdentity), CandidateError> { + let engine = connect(self.candidate, self.build_deadline)?; + verify_build_network(&engine)?; + Self::identify(engine) + } + fn try_lease(&self) -> Result<(Self::Lease, PoolIdentity), CandidateError> { + Self::identify(super::engine::Engine::connect(self.candidate)?) + } + fn observe_build(&self, image: &str) -> Result<(PoolIdentity, Option), CandidateError> { + let observer = super::engine::Observer::connect(self.candidate)?; + observer.info()?; + let identity = PoolIdentity { + incarnation: observer.guest().incarnation().to_owned(), + boot_id: observer.guest().boot_id()?.to_owned(), + engine_id: engine_id(&observer.identity_document()?)?, + socket: observer.guest().engine_socket()?, + }; + let inspected = match observer.image(image) { + Ok(value) => Some(value), + Err(error) if error.code == "engine_not_found" => None, + Err(error) => return Err(error), + }; + Ok((identity, inspected)) + } fn cleanup_lease(&self) -> Result<(Self::Lease, PoolIdentity), CandidateError> { Self { candidate: self.candidate, @@ -1875,31 +1977,61 @@ fn key_with_bases( type EnsuredBase = (BuildBase, Option); -fn ensure_build_base( +fn select_build_base( candidate: &Candidate, reference: &str, policy: &super::image_policy::ImagePolicy, + observer: Option<&super::engine::Observer<'_>>, ) -> Result { - let ensured = super::image_ensure::ensure(candidate, reference, policy)?; - let proof = super::image_ensure::recorded_proof( - candidate, - &ensured.pinned_reference, - super::image_platform::PlatformPolicy::Native, - )? - .ok_or_else(|| { - refusal( - "native_build_base_image", - "The verified base proof is missing.", - ) - })?; - let resolved = proof.verified_build_base(&ensured.pinned_reference, policy.archive_limit)?; - if resolved.image_id != ensured.image_id { - return Err(refusal( - "native_build_base_image", - "The build base proof differs from the loaded image.", - )); - } - Ok((resolved, ensured.tag_resolution)) + use super::{ + image_ensure, image_platform::PlatformPolicy, image_policy::ImageTagMode, image_tag_store, + }; + let platform = PlatformPolicy::Native; + let mut tag = if reference.contains('@') { + None + } else { + Some(image_tag_store::resolve( + candidate, reference, policy, platform, observer, + )?) + }; + let pin = tag.as_ref().map_or(reference, |tag| &tag.pinned_reference); + let proof = match image_ensure::recorded_proof(candidate, pin, platform)? { + Some(proof) => proof, + None if policy.tag_mode != ImageTagMode::Offline && tag.is_none() => { + let resolved = registry_image::resolve_pinned(pin, policy, platform)?; + image_ensure::publish_proof(candidate, pin, platform, &resolved.proof)?; + resolved.proof + } + None => { + return Err(refusal( + "image_archive_offline_missing", + "The verified base proof is missing.", + )); + } + }; + let base = proof.verified_build_base(pin, policy.archive_limit)?; + let tag = tag + .as_mut() + .map(|tag| { + tag.confirm(|tag| { + if tag.image_id != base.image_id { + return Err(refusal( + "native_build_base_image", + "The build base proof differs from the selected image.", + )); + } + Ok(super::image_ensure::EnsuredTag { + reference: tag.record.reference.clone(), + registry: tag.record.registry.clone(), + source_digest: tag.source_digest.clone(), + resolved_at_unix_seconds: tag.resolved_at_unix_seconds, + source: tag.source, + fallback_reason: tag.fallback_reason.clone(), + }) + }) + }) + .transpose()?; + Ok((base, tag)) } /// Serialize selection only for this reference within the caller's build batch. @@ -2054,10 +2186,32 @@ pub fn build_image(candidate: &Candidate, request: &Path) -> Result Result share_command_base(batch, reference, policy, ensure), None => ensure(reference), diff --git a/packages/runtime-core/src/provider/image_build/aliases.rs b/packages/runtime-core/src/provider/image_build/aliases.rs index b15202913..11862b227 100644 --- a/packages/runtime-core/src/provider/image_build/aliases.rs +++ b/packages/runtime-core/src/provider/image_build/aliases.rs @@ -42,7 +42,7 @@ pub(super) struct Journal { aliases: BTreeMap, } -fn tag( +pub(super) fn tag( pool: &P, lease: &P::Lease, id: &str, diff --git a/packages/runtime-core/src/provider/image_build/reclaim.rs b/packages/runtime-core/src/provider/image_build/reclaim.rs index a3d208bdf..49cf2ddb4 100644 --- a/packages/runtime-core/src/provider/image_build/reclaim.rs +++ b/packages/runtime-core/src/provider/image_build/reclaim.rs @@ -196,12 +196,20 @@ fn scan_directory( /// The images build receipts protect, with why: per namespace and declaration, the /// most recent and the previous verified key (see the module documentation). #[derive(Default)] -struct CurrentImages { +pub(super) struct CurrentImages { builds: BTreeMap, bases: BTreeSet, + pub(super) inputs: BTreeSet<(String, String)>, } -fn current_images(candidate: &Candidate) -> Result { +impl CurrentImages { + fn add_bases(&mut self, receipt: Receipt) { + self.bases.extend(receipt.base_image_ids); + self.inputs.extend(receipt.base_pins); + } +} + +pub(super) fn current_images(candidate: &Candidate) -> Result { let root = builds_root(candidate); let mut protected = CurrentImages::default(); let namespaces = match fs::read_dir(&root) { @@ -209,6 +217,7 @@ fn current_images(candidate: &Candidate) -> Result return Ok(protected), Err(_) => return Err(unprovable()), }; + let mut visited = 0; for namespace in namespaces { let namespace = namespace.map_err(|_| unprovable())?.path(); let name = namespace.file_name().and_then(|n| n.to_str()).unwrap_or(""); @@ -220,9 +229,12 @@ fn current_images(candidate: &Candidate) -> Result)>> = - BTreeMap::new(); + let mut declarations: BTreeMap> = BTreeMap::new(); for entry in fs::read_dir(&namespace).map_err(|_| unprovable())? { + visited += 1; + if visited > MAX_SCAN_ENTRIES { + return Err(unprovable()); + } let path = entry.map_err(|_| unprovable())?.path(); if path.extension().and_then(|e| e.to_str()) != Some("json") { continue; @@ -233,15 +245,17 @@ fn current_images(candidate: &Candidate) -> Result declarations .entry(declaration) .or_default() - .push((sequence, id, receipt.base_image_ids)), + .push((sequence, id, receipt)), _ => { protected.builds.insert(id, Retained::Current); - protected.bases.extend(receipt.base_image_ids); + protected.add_bases(receipt); } } } @@ -252,7 +266,7 @@ fn current_images(candidate: &Candidate) -> Result>(); sequences.dedup(); - for (sequence, id, bases) in keys { + for (sequence, id, receipt) in keys { let reason = if Some(&sequence) == sequences.first() { Retained::Current } else if Some(&sequence) == sequences.get(1) { @@ -261,7 +275,7 @@ fn current_images(candidate: &Candidate) -> Result, +} + +fn busy(error: &CandidateError) -> bool { + error.code == "provider_busy" +} + +pub(super) fn retain_verified( + pool: &P, + lease: &P::Lease, + base: &super::BuildBase, + import: impl FnOnce() -> Result<(), CandidateError>, +) -> Result<(), CandidateError> { + let keeper = aliases::keeper(&base.image_id).expect("verified base content ID"); + let present = pool.inspect(lease, &base.image_id)?.is_some_and(|image| { + image["Id"] == base.image_id && image["Os"] == "linux" && image["Architecture"] == "arm64" + }); + if !present { + import()?; + } + aliases::tag(pool, lease, &base.image_id, &keeper) +} + +pub fn run( + candidate: &Candidate, + mut policy: ImagePolicy, +) -> Result { + policy.local_registries.clear(); + policy.tag_mode = ImageTagMode::Normal; + let deadline = Instant::now() + BUDGET; + policy.build_deadline = Some(deadline); + let mut report = RetentionReport::default(); + let _worker = match state::Lock::acquire(&candidate.state_root.join("run/build-base-retention")) + { + Ok(worker) => worker, + Err(error) if busy(&error) => { + report.deferred = true; + return Ok(report); + } + Err(error) => return Err(error), + }; + let pool = LivePool { + candidate, + build_deadline: Some(deadline), + }; + let inputs = { + let _fence = match image_fence(candidate, libc::LOCK_EX) { + Ok(fence) => fence, + Err(error) if busy(&error) => { + report.deferred = true; + return Ok(report); + } + Err(error) => return Err(error), + }; + reclaim::current_images(candidate)?.inputs + }; + let mut pins = BTreeSet::new(); + let mut tags = BTreeSet::new(); + for (reference, pin) in inputs { + if Instant::now() >= deadline { + report.deferred = true; + break; + } + let result = (|| { + let (lease, _) = pool.try_lease()?; + let _fence = idle_retention_fence(candidate)?; + if pins.insert(pin.clone()) { + let (base, _) = select_build_base(candidate, &pin, &policy, None)?; + retain_verified(&pool, &lease, &base, || { + image_ensure::retain_build_image(candidate, &pin, &policy, &lease).map(|_| ()) + })?; + report.retained += 1; + } + if !reference.contains('@') && tags.insert(reference.clone()) { + // Metadata only. A newly available pin will be used for the next + // solve, whose receipt can then schedule its exact digest. + select_build_base(candidate, &reference, &policy, None)?; + } + Ok::<_, CandidateError>(()) + })(); + if let Err(error) = result { + if busy(&error) { + report.deferred = true; + break; + } + report.failures.insert(error.code); + } + } + Ok(report) +} diff --git a/packages/runtime-core/src/provider/image_build/tests.rs b/packages/runtime-core/src/provider/image_build/tests.rs index e36b4520f..791ad6edc 100644 --- a/packages/runtime-core/src/provider/image_build/tests.rs +++ b/packages/runtime-core/src/provider/image_build/tests.rs @@ -298,9 +298,10 @@ fn run( canceled: &dyn Fn() -> bool, ) -> Result { const BASE_ID: &str = "sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; - pool.images - .borrow_mut() - .insert(BASE_ID.into(), serde_json::json!({"Id": BASE_ID})); + pool.images.borrow_mut().insert( + BASE_ID.into(), + serde_json::json!({"Id": BASE_ID, "Architecture": "arm64", "Os": "linux"}), + ); let selected = inputs .images .iter() @@ -2087,6 +2088,79 @@ fn a_dead_build_alias_is_swept_only_after_the_worker_releases_its_key() { assert!(!path.exists()); } +#[test] +fn idle_retention_reuses_loaded_base_and_imports_an_absent_base_once() { + let fixture = Fixture::new(); + let pool = FakePool::new("pool-1"); + let base = BuildBase { + pinned_reference: format!("docker.io/library/alpine@{PIN}"), + source_digest: PIN.into(), + image_id: PIN.into(), + }; + let build = image_fence(&fixture.candidate, libc::LOCK_SH).unwrap(); + assert!(idle_retention_fence(&fixture.candidate).is_err()); + drop(build); + let _idle = idle_retention_fence(&fixture.candidate).unwrap(); + let _observer = image_fence(&fixture.candidate, libc::LOCK_SH).unwrap(); + assert!(image_fence(&fixture.candidate, libc::LOCK_EX).is_err()); + + retain::retain_verified(&pool, &(), &base, || { + pool.images.borrow_mut().insert( + PIN.into(), + serde_json::json!({ + "Id": PIN, "Architecture": "arm64", "Os": "linux", + }), + ); + Ok(()) + }) + .unwrap(); + retain::retain_verified(&pool, &(), &base, || panic!("loaded base imported twice")).unwrap(); + assert_eq!( + pool.inspect(&(), &aliases::keeper(PIN).unwrap()) + .unwrap() + .unwrap()["Id"], + PIN + ); +} + +#[test] +fn an_unloaded_pin_goes_to_the_cold_client_and_an_offline_solve_refuses_it() { + let fixture = Fixture::new(); + let mut inputs = fixture.inputs(Policy::Missing); + let pool = FakePool::new("pool-1"); + let pin = format!("docker.io/library/alpine@{PIN}"); + let bases = BTreeMap::from([( + "alpine:3.20".into(), + BuildBase { + pinned_reference: pin.clone(), + source_digest: PIN.into(), + image_id: PIN.into(), + }, + )]); + inputs.key = key_with_bases(&inputs.key, &bases).unwrap(); + fixture.client(&inputs, "ok"); + pool.built(&inputs, "pool-1", serde_json::json!({})); + let deadline = Instant::now() + inputs.timeout; + inputs.tag_mode = super::super::image_policy::ImageTagMode::Offline; + assert_eq!( + run_with_bases(&fixture.candidate, &pool, &inputs, &never, &bases, deadline) + .unwrap_err() + .code, + "image_archive_offline_missing" + ); + assert_eq!(fixture.calls(&inputs), 0); + inputs.tag_mode = super::super::image_policy::ImageTagMode::Normal; + run_with_bases(&fixture.candidate, &pool, &inputs, &never, &bases, deadline).unwrap(); + let scratch = fixture.scratch(&inputs); + let bake: Value = + serde_json::from_slice(&fs::read(scratch.join("seen-bake.json")).unwrap()).unwrap(); + assert_eq!( + bake["target"]["build"]["contexts"]["alpine:3.20"], + format!("docker-image://{pin}") + ); + assert!(fixture.receipt(&inputs).base_image_ids.contains(PIN)); +} + #[test] fn a_verified_base_selects_the_build_key_and_only_a_local_worker_source() { let fixture = Fixture::new(); @@ -2106,9 +2180,10 @@ fn a_verified_base_selects_the_build_key_and_only_a_local_worker_source() { inputs.key = key; fixture.client(&inputs, "ok"); pool.built(&inputs, "pool-1", serde_json::json!({})); - pool.images - .borrow_mut() - .insert(PIN.into(), serde_json::json!({"Id":PIN})); + pool.images.borrow_mut().insert( + PIN.into(), + serde_json::json!({"Id": PIN, "Architecture": "arm64", "Os": "linux"}), + ); let outcome = run_with_bases( &fixture.candidate, &pool, diff --git a/packages/runtime-core/src/provider/image_ensure.rs b/packages/runtime-core/src/provider/image_ensure.rs index 90b29b40f..106bc172c 100644 --- a/packages/runtime-core/src/provider/image_ensure.rs +++ b/packages/runtime-core/src/provider/image_ensure.rs @@ -741,7 +741,7 @@ fn acquire_selection( policy, platform, observer, - cache, + (cache, None), Some(tag), ) })?, @@ -751,7 +751,7 @@ fn acquire_selection( policy, platform, observer, - cache, + (cache, None), tag.as_ref(), )?, }; @@ -769,13 +769,32 @@ fn acquire_selection( Ok(ensured) } +/// Retain an immutable build input under an already-held idle provider lease. +pub(super) fn retain_build_image( + candidate: &Candidate, + pin: &str, + policy: &ImagePolicy, + engine: &engine::Engine<'_>, +) -> Result { + let observer = engine::Observer::connect(candidate)?; + confirm_selection( + candidate, + pin, + policy, + PlatformPolicy::Native, + Some(&observer), + (&ImageCache::default(), Some(engine)), + None, + ) +} + fn confirm_selection( candidate: &Candidate, reference: &str, policy: &ImagePolicy, platform: PlatformPolicy, observer: Option<&engine::Observer<'_>>, - cache: &ImageCache, + (cache, existing_engine): (&ImageCache, Option<&engine::Engine<'_>>), tag: Option<&image_tag_store::TagResolution>, ) -> Result { let requested_platform = platform; @@ -930,7 +949,14 @@ fn confirm_selection( recorded_config: selection.as_ref().map(|(_, config)| config.as_str()), require_present: offline, }; - image_load::load_cached(candidate, &archive, policy, observer, config).map(|_| ()) + image_load::load_cached( + candidate, + &archive, + policy, + (observer, existing_engine), + config, + ) + .map(|_| ()) }, )? }; diff --git a/packages/runtime-core/src/provider/image_load.rs b/packages/runtime-core/src/provider/image_load.rs index b0d9d8283..0f122f9f9 100644 --- a/packages/runtime-core/src/provider/image_load.rs +++ b/packages/runtime-core/src/provider/image_load.rs @@ -737,7 +737,7 @@ pub(super) fn load_cached( candidate: &Candidate, archive: &CachedArchive<'_>, policy: &ImagePolicy, - observer: &Observer<'_>, + (observer, existing_engine): (&Observer<'_>, Option<&Engine<'_>>), resolved_config: impl FnOnce() -> Result, ) -> Result { let guest = observer.guest(); @@ -754,6 +754,9 @@ pub(super) fn load_cached( || observer.image(archive.image), resolved_config, |file| { + if let Some(engine) = existing_engine { + return import(candidate, archive, Some(archive.pin), policy, file, engine); + } let engine = measure(Step::ImageImportConnect, None, |_| { connect_for_import( candidate, diff --git a/scripts/lib/tla-runtime-models.ts b/scripts/lib/tla-runtime-models.ts index d39730c35..dd96adf18 100644 --- a/scripts/lib/tla-runtime-models.ts +++ b/scripts/lib/tla-runtime-models.ts @@ -2809,6 +2809,23 @@ const contracts: readonly ModelContract[] = [ }, ], }, + { + name: "native-build-base-scheduling", + module: "BaseScheduling", + states: 12, + invariant: "NoForegroundImport", + action: "Cold", + fields: ['phase = "solving"', "foregroundDownload = TRUE"], + additionalControls: [ + { + name: "unsafe-overlap", + negative: true, + invariant: "OnlyIdleRetention", + action: "Stop", + fields: ['phase = "stopping"', "retention = TRUE"], + }, + ], + }, { name: "native-build-alias", module: "BuildAlias", diff --git a/src/backends/native-project-start.ts b/src/backends/native-project-start.ts index 5535ff28d..b5af4a4e2 100644 --- a/src/backends/native-project-start.ts +++ b/src/backends/native-project-start.ts @@ -9,6 +9,7 @@ import { withComposeServiceEnvFingerprints, } from "../lib/compose-env-fingerprint.ts"; import { isRecord } from "../lib/guards.ts"; +import { appendLifecycleLogRecord } from "../lib/lifecycle-runtime.ts"; import { isNativeDetachedOwnerProcess, nativeDetachedUpBranchDropped, @@ -3288,6 +3289,30 @@ async function startNativeProjectAttempt( }); let code = 1; let serveFailure: unknown; + let retentionTimer: ReturnType | undefined; + let retentionStopped = false; + const scheduleRetention = (attempt: number) => { + if (retentionStopped || controller.signal.aborted) { + return; + } + retentionTimer = setTimeout( + () => { + if (!controller.signal.aborted) { + void retainReadyBuildBases({ + scope: opts.scope, + run, + runtime: opts.runtime, + invoke: deps.invoke, + }).then((deferred) => { + if (deferred && attempt < 3) { + scheduleRetention(attempt + 1); + } + }); + } + }, + attempt === 0 ? 2000 : 5000 + ).unref(); + }; let nativeExitCode: string | undefined; let nativeProcessRefusals: | readonly NativeProcessRefusal[] @@ -3503,6 +3528,9 @@ async function startNativeProjectAttempt( httpsPort, }) ); + if (built.size > 0 && opts.imageTagMode !== "offline") { + scheduleRetention(0); + } // Superseded build images go once the new ones run; this never // fails or delays the start (HACK-2533). void reclaimNativeBuildImagesAfterRebuild({ @@ -3516,6 +3544,8 @@ async function startNativeProjectAttempt( } catch (error) { serveFailure = error; } finally { + retentionStopped = true; + clearTimeout(retentionTimer); await startupStatus.stop(); delivery.payload?.fill(0); await stopWatching?.(); @@ -3673,6 +3703,48 @@ async function startNativeProjectAttempt( } } } +async function retainReadyBuildBases(opts: { + readonly scope: NativeProjectRunScope; + readonly run: string; + readonly runtime: NativeRuntimeSelection; + readonly invoke: typeof invokeNativeRuntime; +}): Promise { + try { + const result = await opts.invoke({ + runtime: opts.runtime, + cwd: opts.scope.projectRoot, + args: [ + "runtime", + "retain-build-bases", + "--json", + ...nativeImagePolicyArgs(), + ], + timeoutMs: 30 * 60_000 + 5000, + }); + if ( + isRecord(result) && + Array.isArray(result.failures) && + result.failures.length === 0 + ) { + return result.deferred === true; + } + } catch { + // Maintenance failures are private lifecycle notes. + } + await appendLifecycleLogRecord({ + projectDir: opts.scope.projectDir, + composeProject: opts.run, + record: { + timestamp: new Date().toISOString(), + service: "build-base-retention", + stream: "meta", + message: + "Background build base retention failed. The startup result is unaffected.", + }, + }).catch(() => undefined); + return false; +} + /** A failed stop hook replaces the interrupted status, never a startup error. */ function reportForegroundStopFailure(failure: unknown, failed: boolean): void { if (failure !== undefined && !failed) { diff --git a/tests/models/tla/native-build-base-scheduling/BaseScheduling.tla b/tests/models/tla/native-build-base-scheduling/BaseScheduling.tla new file mode 100644 index 000000000..72c0dd7ed --- /dev/null +++ b/tests/models/tla/native-build-base-scheduling/BaseScheduling.tla @@ -0,0 +1,33 @@ +---- MODULE BaseScheduling ---- +CONSTANTS OldColdOrder, UnsafeOverlap +VARIABLES phase, verified, retained, retention, foregroundDownload +vars == <> +Init == /\ phase = "idle" /\ verified = FALSE /\ retained = FALSE + /\ retention = FALSE /\ foregroundDownload = FALSE + +(* Receipt verification is read-only and needs no provider mutation lease. *) +Reuse == /\ phase = "idle" /\ verified + /\ phase' = "reused" /\ UNCHANGED <> +Cold == /\ phase = "idle" /\ ~verified /\ ~retention + /\ phase' = "solving" /\ foregroundDownload' = OldColdOrder + /\ UNCHANGED <> +Finish == /\ phase = "solving" /\ phase' = "starting" /\ verified' = TRUE + /\ UNCHANGED <> +Start == /\ phase \in {"starting", "reused"} /\ ~retention + /\ phase' = "idle" /\ UNCHANGED <> +Stop == /\ phase = "idle" /\ (~retention \/ UnsafeOverlap) /\ phase' = "stopping" + /\ UNCHANGED <> +Stopped == /\ phase = "stopping" /\ phase' = "idle" + /\ UNCHANGED <> +IdleAdmission == /\ phase = "idle" /\ verified /\ ~retained /\ ~retention + /\ retention' = TRUE + /\ UNCHANGED <> +Retain == /\ retention /\ retention' = FALSE /\ retained' = TRUE + /\ UNCHANGED <> +Fail == /\ retention /\ retention' = FALSE + /\ UNCHANGED <> +Next == Reuse \/ Cold \/ Finish \/ Start \/ Stop \/ Stopped \/ IdleAdmission \/ Retain \/ Fail +Spec == Init /\ [][Next]_vars +NoForegroundImport == ~foregroundDownload +OnlyIdleRetention == retention => phase \in {"idle", "reused"} +==== diff --git a/tests/models/tla/native-build-base-scheduling/negative.cfg b/tests/models/tla/native-build-base-scheduling/negative.cfg new file mode 100644 index 000000000..a2943031b --- /dev/null +++ b/tests/models/tla/native-build-base-scheduling/negative.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANT OldColdOrder = TRUE +CONSTANT UnsafeOverlap = FALSE +INVARIANTS NoForegroundImport OnlyIdleRetention diff --git a/tests/models/tla/native-build-base-scheduling/positive.cfg b/tests/models/tla/native-build-base-scheduling/positive.cfg new file mode 100644 index 000000000..7814cb379 --- /dev/null +++ b/tests/models/tla/native-build-base-scheduling/positive.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANT OldColdOrder = FALSE +CONSTANT UnsafeOverlap = FALSE +INVARIANTS NoForegroundImport OnlyIdleRetention diff --git a/tests/models/tla/native-build-base-scheduling/unsafe-overlap.cfg b/tests/models/tla/native-build-base-scheduling/unsafe-overlap.cfg new file mode 100644 index 000000000..36e0c9d4b --- /dev/null +++ b/tests/models/tla/native-build-base-scheduling/unsafe-overlap.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANT OldColdOrder = FALSE +CONSTANT UnsafeOverlap = TRUE +INVARIANTS NoForegroundImport OnlyIdleRetention From 53e5546d7535f9dc0c6243d5dcfd4b1d6aa0dee3 Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:27:24 +0000 Subject: [PATCH 31/33] fix: publish refreshed build tags after their bases are retained --- .../src/provider/image_build/retain.rs | 51 +++++++++++++++++-- .../runtime-core/src/provider/image_ensure.rs | 14 +++-- .../runtime-core/src/provider/image_policy.rs | 2 + .../src/provider/image_tag_store.rs | 2 +- 4 files changed, 58 insertions(+), 11 deletions(-) diff --git a/packages/runtime-core/src/provider/image_build/retain.rs b/packages/runtime-core/src/provider/image_build/retain.rs index 7fec48210..3ac166d8f 100644 --- a/packages/runtime-core/src/provider/image_build/retain.rs +++ b/packages/runtime-core/src/provider/image_build/retain.rs @@ -7,8 +7,9 @@ use super::{ }; use crate::provider::{ image_ensure, + image_platform::PlatformPolicy, image_policy::{ImagePolicy, ImageTagMode}, - state, + image_tag_store, state, }; use crate::{Candidate, CandidateError}; use serde::Serialize; @@ -52,6 +53,7 @@ pub fn run( ) -> Result { policy.local_registries.clear(); policy.tag_mode = ImageTagMode::Normal; + policy.opportunistic_locks = true; let deadline = Instant::now() + BUDGET; policy.build_deadline = Some(deadline); let mut report = RetentionReport::default(); @@ -89,17 +91,56 @@ pub fn run( let result = (|| { let (lease, _) = pool.try_lease()?; let _fence = idle_retention_fence(candidate)?; - if pins.insert(pin.clone()) { + // An intervening solve can retire a queued input between visits. + if !reclaim::current_images(candidate)? + .inputs + .contains(&(reference.clone(), pin.clone())) + { + return Ok(()); + } + if !pins.contains(&pin) { let (base, _) = select_build_base(candidate, &pin, &policy, None)?; retain_verified(&pool, &lease, &base, || { image_ensure::retain_build_image(candidate, &pin, &policy, &lease).map(|_| ()) })?; + pins.insert(pin.clone()); report.retained += 1; } if !reference.contains('@') && tags.insert(reference.clone()) { - // Metadata only. A newly available pin will be used for the next - // solve, whose receipt can then schedule its exact digest. - select_build_base(candidate, &reference, &policy, None)?; + let mut tag = image_tag_store::resolve( + candidate, + &reference, + &policy, + PlatformPolicy::Native, + None, + )?; + tag.confirm(|tag| { + if pins.contains(&tag.pinned_reference) { + return Ok(()); + } + let (base, _) = + select_build_base(candidate, &tag.pinned_reference, &policy, None)?; + if base.image_id != tag.image_id { + return Err(super::refusal( + "native_build_base_image", + "The refreshed build base proof differs from its selection.", + )); + } + // Keep the previous selection usable offline until the + // replacement has both a verified image and its keeper. + retain_verified(&pool, &lease, &base, || { + image_ensure::retain_build_image( + candidate, + &tag.pinned_reference, + &policy, + &lease, + ) + .map(|_| ()) + })?; + pins.insert(tag.pinned_reference.clone()); + report.retained += 1; + Ok(()) + })?; } Ok::<_, CandidateError>(()) })(); diff --git a/packages/runtime-core/src/provider/image_ensure.rs b/packages/runtime-core/src/provider/image_ensure.rs index 106bc172c..97e0a9b0e 100644 --- a/packages/runtime-core/src/provider/image_ensure.rs +++ b/packages/runtime-core/src/provider/image_ensure.rs @@ -70,11 +70,15 @@ impl ImageCache { if let Some(lease) = &cache.lease { lease.verify_path(root)?; } else { - let lease = state::wait_for_image_lock( - policy.image_wait(std::time::Duration::from_secs(590))?, - "image-cache", - || state::Lock::acquire(root), - )?; + let lease = if policy.opportunistic_locks { + state::Lock::acquire(root)? + } else { + state::wait_for_image_lock( + policy.image_wait(std::time::Duration::from_secs(590))?, + "image-cache", + || state::Lock::acquire(root), + )? + }; let staging = root.with_file_name("image-staging"); if staging.try_exists().map_err(state::io)? { clean_staging(&staging, 0)?; diff --git a/packages/runtime-core/src/provider/image_policy.rs b/packages/runtime-core/src/provider/image_policy.rs index 1b4ce2a69..f5ae1b1d3 100644 --- a/packages/runtime-core/src/provider/image_policy.rs +++ b/packages/runtime-core/src/provider/image_policy.rs @@ -68,6 +68,7 @@ pub struct ImagePolicy { pub tag_mode: ImageTagMode, pub(crate) short_tag_refresh: bool, pub(crate) build_deadline: Option, + pub(super) opportunistic_locks: bool, pub(crate) command_image_pin: Option, /// Registries that are refused as local unless named here. pub local_registries: Vec, @@ -91,6 +92,7 @@ impl Default for ImagePolicy { tag_mode: ImageTagMode::Normal, short_tag_refresh: false, build_deadline: None, + opportunistic_locks: false, command_image_pin: None, local_registries: Vec::new(), docker_config: None, diff --git a/packages/runtime-core/src/provider/image_tag_store.rs b/packages/runtime-core/src/provider/image_tag_store.rs index eb878c536..0791a7709 100644 --- a/packages/runtime-core/src/provider/image_tag_store.rs +++ b/packages/runtime-core/src/provider/image_tag_store.rs @@ -490,7 +490,7 @@ fn resolve_pending( // Recheck under the writer lock so an automatic refresh can reuse a // resolution another process just published. let lock = match state::Lock::acquire(&root) { - Err(error) if error.code == "provider_busy" => { + Err(error) if error.code == "provider_busy" && !policy.opportunistic_locks => { let lock = policy .image_wait(std::time::Duration::from_secs(590)) .and_then(|wait| { From 6d09a7fe89d79b4a8f70f6da94b3601d80f05688 Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:53:13 +0000 Subject: [PATCH 32/33] fix: prioritize foreground work over build base retention --- docs/reference/v5-model-coverage.md | 2 +- .../v5/native/existing-compose-project.md | 4 +- .../runtime-core/src/provider/image_build.rs | 126 +++++++++++++----- .../src/provider/image_build/reclaim.rs | 2 +- .../src/provider/image_build/retain.rs | 95 +++++++++---- .../src/provider/image_build/tests.rs | 25 ++++ .../runtime-core/src/provider/image_ensure.rs | 8 +- .../runtime-core/src/provider/image_policy.rs | 4 +- .../src/provider/image_tag_store.rs | 2 +- .../src/provider/registry_image.rs | 14 ++ src/backends/native-project-start.ts | 18 ++- src/backends/native-runtime-client.ts | 14 +- tests/native-runtime-client.test.ts | 20 +++ 13 files changed, 258 insertions(+), 76 deletions(-) diff --git a/docs/reference/v5-model-coverage.md b/docs/reference/v5-model-coverage.md index 5ad743688..37afe5a65 100644 --- a/docs/reference/v5-model-coverage.md +++ b/docs/reference/v5-model-coverage.md @@ -78,7 +78,7 @@ must be attached to the eventual exact integration revision. | Cached image presence before archive reads | [native-image-presence](../../tests/models/tla/native-image-presence/COVERAGE.md) | `image_load::load_waiting` requires live exact image and platform readback for receipt reuse and verifies the archive on any upload path. Explicit archive loads retain their early hash. | One request, one archive, one lease, one boot. Expiry and registry availability may change before tag selection. Guest eviction may precede readback or create. Guest ownership, filesystem behavior, interrupted imports and performance require separate runtime evidence. | | Native up build batch: authored dispatch, bounded concurrency, stop and drain | [native-build-batch](../../tests/models/tla/native-build-batch/COVERAGE.md) | `runPendingBuilds` captures the first failure and drains every started invocation. Controlled runtime and source CLI SIGINT regressions cover cancellation and caller exit. | Four distinct keys and a cap of three. Per-key leases and receipts are covered by native-build-retention; actual VM settlement remains host evidence. | | Native image builds: unleased build versus engine stop, crash mid-build, storage recreation, foreign or forged images, reclamation versus retained graph references | native-build-retention | `provider::image_build` (shared build fence, per-key lock, incarnation/boot/engine recheck and label check at adoption, dead-attempt recording) and `image_build::reclaim` (owned labels, current receipts, retained graph state scan, engine non-force removal); `image_build` regressions | One key and namespace. Since key version 2 (HACK-2533) every edited build context makes a new key with its own receipt; reclamation keeps, per build declaration, the current and one previous key's image, plus every image retained state (except its diagnostic restore history, HACK-2554) or a container references and every receipt without a declaration, and an `up` that built runs it best-effort after readiness (`image_build::tests::ten_edits_of_one_build_leave_its_current_and_previous_images`); the model's retained-reference safety is unchanged, and which receipt is current is regression-tested, not modeled. Snapshots of a dead owner are removed at the next build in the namespace, only after the owner is proven gone and under that key's lock (`snapshots_of_dead_owners_are_removed_at_the_next_build_of_any_key`). Which inputs a key covers (context walk, ignore rules, hard-link groups, stat cache) and restore's per-up build decision are regression-tested in `image_build::context` and `image_build` and in `tests/native-project-builds.test.ts`, not modeled. A build client orphaned by a killed `hack-native` is not modeled (the client inherits the build fence and per-key lock, so both stay held until it exits: `image_build::tests::a_killed_coordinator_leaves_its_client_fenced`); real BuildKit, engine removal semantics and guest storage are host evidence. | -| Native build-base scheduling | native-build-base-scheduling | `reuse_receipt` uses local proof and read-only engine observation. `run_with_bases` sends cold pins to BuildKit. `retain::run` checks the image fence and provider lease before retaining pinned inputs. | One base, one build receipt, and one background worker. A foreground request may arrive while the worker holds the provider lease. The model covers admitted work, not provider wait budgets, transfer, or guest-side cancellation. | +| Native build-base scheduling | native-build-base-scheduling | `reuse_receipt` uses local proof and read-only engine observation. `run_with_bases` sends cold pins to BuildKit. `retain::run` checks the image fence and provider lease before retaining pinned inputs. | One base, one build receipt, and one background worker. The model covers admitted import and tagging. Download staging yields when it observes foreground work and runs without the provider lease. The model omits provider wait budgets, transport and guest-side cancellation. | | Native build-base alias lifetime | native-build-alias | `image_build::aliases` journals before publishing, keeps a cache reference, and sweeps only while holding the attempt key lock; tests exercise the live lock and stranded journal. | One base and one attempt. The verified pin and per-attempt name are enforced in Rust. The model abstracts registry transport and Docker's image deletion behavior. | | Runtime service per native home (HACK-2460, design): start race, crash at any step, version skew and drain, lost replies, resends on new connections, one-shot fallback, inspection of started but unfinished work | runtime-service | Process half implemented as a library; nothing starts or calls it yet. `TakeLock`, `LoseRace` and `Bind` map to `service::start` (a lock on the private `run/service/` directory, then `service.lock`, each checked against its path and held for the process's whole life, drain included; an existing socket is probed and kept if anything answers). `IdleExit`, `Retire`, `RefuseDraining` and `ExitDrained` map to `run`, `refuse_queued` and `shut_down`, with `settle` releasing ownership only after a complete drain. The tests in `packages/runtime-core/src/service/tests.rs` walk each action (concurrent starts, lock replacement while serving and while draining, stale and live sockets, idle exit with a held session, retire, connections queued at shutdown, drain timeout). `Crash` gets its real-process SIGKILL test in the next slice. Intent records, admission of mutations, skew, fallback and inspection are not implemented; each later slice adds the regression that walks its actions, behind `HACK_RUNTIME_SERVICE` (default `off`) | Not modelled, covered by regression tests instead: a lock held for a moment after its owner let go, because a forked child shares the open file description until it runs `exec` (the starter's bounded retry window, `service/tests.rs`); the time bound on that window; a drain that runs out of time ending the process at once with exit code 3; a signal (TERM, INT, HUP) draining like retire; and a starter that never reads the notify line (`tests/runtime_service_contract.rs`, `tests/runtime_service_hooks.rs`). The model treats a release as immediate and every drain as finishing. Implemented slice assumes the `run/service/` directory itself is not replaced (replacing `service.lock` is covered) and that the process exits after a drain that ran out of its 10 s bound; it refuses, never serves, connections queued at stop. Assumption each mutation slice must meet: its inspector distinguishes proven absence from missing evidence (for example work a provider accepted but has not yet made visible), and missing evidence yields "unknown", never "not done"; the model makes dispatched work visible at once. Liveness, several leases, cancellation of joined attempts, event cursors, dashboard authentication, the idle-exit queue race and intent-write durability are not modelled. | | MCP cold start, cancellation and duplicate launches | mcp-startup, mcp-startup-cancellation | Shared MCP bundle identity, startup deduplication and cancellation regressions | Fresh supported client sessions, full workflow coverage and measured overhead (WU16/WU20/WU28). | diff --git a/docs/versions/v5/native/existing-compose-project.md b/docs/versions/v5/native/existing-compose-project.md index 47542aa99..a3cca9955 100644 --- a/docs/versions/v5/native/existing-compose-project.md +++ b/docs/versions/v5/native/existing-compose-project.md @@ -93,7 +93,9 @@ For a cold build, BuildKit fetches any missing base by digest during the solve. readiness, native tries to retain the exact bases from current and previous builds, one at a time. It tags a matching local engine image when available and otherwise downloads and imports the base. It defers when startup, stop, build, or reclamation -already holds the required locks. Retention has a 30-minute budget and logs failures +already holds the required locks. Downloads stage outside the provider lease and +stop when they observe a foreground operation. An admitted import keeps the provider +lease until verification settles. Retention has a 30-minute budget and logs failures without changing the startup result. `hack up --offline` can reuse an unchanged build. An edited build also needs its verified base loaded in the guest. After an `up` that built, native removes superseded build images while keeping the current diff --git a/packages/runtime-core/src/provider/image_build.rs b/packages/runtime-core/src/provider/image_build.rs index 9d39c2914..2068bccf6 100644 --- a/packages/runtime-core/src/provider/image_build.rs +++ b/packages/runtime-core/src/provider/image_build.rs @@ -773,6 +773,15 @@ pub(super) fn image_fence( } /// Take the shared fence before asking for the provider lease. +/// A staged background download yields to an admitted foreground operation. +pub(super) fn check_retention_idle(state_root: &Path) -> Result<(), CandidateError> { + let _provider = state::Lock::acquire_existing(&state_root.join("run/smolvm"))?; + let fence = Flock::open(&state_root.join("run/image-builds/active.lock"))?; + Flock::try_lock(fence, libc::LOCK_EX)? + .ok_or_else(|| refusal("provider_busy", "Background image retention deferred."))?; + Ok(()) +} + fn idle_retention_fence(candidate: &Candidate) -> Result { let root = builds_root(candidate); state::private_directory(&root)?; @@ -871,7 +880,7 @@ fn owned_image( fn reuse_verified( candidate: &Candidate, inputs: &Inputs, - path: &Path, + path: Option<&Path>, previous: &Receipt, observe: impl FnOnce(&str) -> Result<(PoolIdentity, Option), CandidateError>, ) -> Result, CandidateError> { @@ -891,11 +900,13 @@ fn reuse_verified( { return Ok(None); } - let mut current = previous.clone(); - current.provider_boot_id = identity.boot_id.clone(); - current.declaration = Some(inputs.declaration.clone()); - current.sequence = path.parent().map(next_sequence); - state::write(path, ¤t)?; + if let Some(path) = path { + let mut current = previous.clone(); + current.provider_boot_id = identity.boot_id.clone(); + current.declaration = Some(inputs.declaration.clone()); + current.sequence = path.parent().map(next_sequence); + state::write(path, ¤t)?; + } return Ok(Some(reused(inputs, id, &previous.base_pins))); } Ok(None) @@ -915,14 +926,32 @@ fn reuse_receipt( if !path.try_exists().map_err(state::io)? { return Ok(None); } - let _fence = image_fence(candidate, libc::LOCK_SH)?; - let lock = Flock::open(&directory.join(format!("{}.lock", inputs.key)))?; - let Some(_lock) = Flock::try_lock(lock, libc::LOCK_EX)? else { - return Ok(None); + let fence = match image_fence(candidate, libc::LOCK_SH) { + Ok(fence) => Some(fence), + Err(error) if error.code == "provider_busy" => None, + Err(error) => return Err(error), + }; + let _key = if fence.is_some() { + let lock = Flock::open(&directory.join(format!("{}.lock", inputs.key)))?; + let Some(lock) = Flock::try_lock(lock, libc::LOCK_EX)? else { + return Ok(None); + }; + Some(lock) + } else { + None }; let Some(previous) = read_receipt(&path)? else { return Ok(None); }; + // Exclusive reclaim cannot remove its current or previous build images. + // Observe those read-only and leave receipt order unchanged. + if fence.is_none() + && !previous.image_id.as_ref().is_some_and(|id| { + reclaim::current_images(candidate).is_ok_and(|current| current.builds.contains_key(id)) + }) + { + return Ok(None); + } if let Some(expected) = expected && (expected.len() != previous.base_pins.len() || expected @@ -941,9 +970,13 @@ fn reuse_receipt( { return Ok(None); } - reuse_verified(candidate, inputs, &path, &previous, |id| { - pool.observe_build(id) - }) + reuse_verified( + candidate, + inputs, + fence.is_some().then_some(path.as_path()), + &previous, + |id| pool.observe_build(id), + ) } fn reuse_legacy( @@ -1043,9 +1076,11 @@ fn run_with_bases( "A build receipt does not match its path; no image was adopted or replaced.", )); } - if let Some(outcome) = reuse_verified(candidate, inputs, &receipt_path, previous, |id| { - Ok((identity.clone(), pool.inspect(&lease, id)?)) - })? { + if let Some(outcome) = + reuse_verified(candidate, inputs, Some(&receipt_path), previous, |id| { + Ok((identity.clone(), pool.inspect(&lease, id)?)) + })? + { // Recovery cannot invalidate the verified reuse decision. let _ = aliases::sweep(pool, &lease, &identity, &alias_path); return Ok(outcome); @@ -2188,29 +2223,48 @@ pub fn build_image(candidate: &Candidate, request: &Path) -> Result Result, CandidateError> { + if inputs.policy == Policy::Missing && tag_mode != ImageTagMode::Refresh { + let mut local = policy.clone(); + local.tag_mode = ImageTagMode::Offline; + if let Ok(bases) = acquire_bases( + &inputs, + &prior_pins, + local, + |reference, policy| select_build_base(candidate, reference, policy, None), + deadline, + ) { + let key = key_with_bases(&inputs.key, &bases.selected)?; + let original = std::mem::replace(&mut inputs.key, key); + let reuse = reuse_receipt(candidate, &pool, &inputs, Some(&bases.selected))?; + inputs.key = original; + if let Some(mut outcome) = reuse { + outcome.base_selections = bases.selections; + return Ok(Some(outcome)); + } + } else if let Some(outcome) = reuse_legacy(candidate, &pool, &inputs)? { + return Ok(Some(outcome)); } - } else if let Some(outcome) = reuse_legacy(candidate, &pool, &inputs)? { - return Ok(outcome); } + Ok(None) + }; + if let Some(outcome) = reuse()? { + return Ok(outcome); } - let _acquisition_fence = wait_for_image_fence(candidate, &policy)?; + let acquisition_fence = match image_fence(candidate, libc::LOCK_SH) { + Ok(fence) => Some(fence), + Err(error) if error.code == "provider_busy" => None, + Err(error) => return Err(error), + }; + let _waited_fence = if acquisition_fence.is_none() { + let fence = wait_for_image_fence(candidate, &policy)?; + if let Some(outcome) = reuse()? { + return Ok(outcome); + } + Some(fence) + } else { + None + }; let observer = super::engine::Observer::connect(candidate)?; let BaseSelections { selected, diff --git a/packages/runtime-core/src/provider/image_build/reclaim.rs b/packages/runtime-core/src/provider/image_build/reclaim.rs index 49cf2ddb4..44b677b2a 100644 --- a/packages/runtime-core/src/provider/image_build/reclaim.rs +++ b/packages/runtime-core/src/provider/image_build/reclaim.rs @@ -197,7 +197,7 @@ fn scan_directory( /// most recent and the previous verified key (see the module documentation). #[derive(Default)] pub(super) struct CurrentImages { - builds: BTreeMap, + pub(super) builds: BTreeMap, bases: BTreeSet, pub(super) inputs: BTreeSet<(String, String)>, } diff --git a/packages/runtime-core/src/provider/image_build/retain.rs b/packages/runtime-core/src/provider/image_build/retain.rs index 3ac166d8f..dfef32972 100644 --- a/packages/runtime-core/src/provider/image_build/retain.rs +++ b/packages/runtime-core/src/provider/image_build/retain.rs @@ -2,6 +2,7 @@ //! current and previous build inputs. Each visit takes a nonwaiting provider //! lease and checks the exclusive fence before admitting idle work. Its shared //! fence allows read-only receipt reuse while excluding reclaim and pool stop. +//! Archive staging and registry resolution hold neither provider lease nor fence. use super::{ BuildPool, LivePool, aliases, idle_retention_fence, image_fence, reclaim, select_build_base, }; @@ -38,22 +39,77 @@ pub(super) fn retain_verified( import: impl FnOnce() -> Result<(), CandidateError>, ) -> Result<(), CandidateError> { let keeper = aliases::keeper(&base.image_id).expect("verified base content ID"); - let present = pool.inspect(lease, &base.image_id)?.is_some_and(|image| { - image["Id"] == base.image_id && image["Os"] == "linux" && image["Architecture"] == "arm64" - }); + let present = loaded(pool, lease, base)?; if !present { import()?; } aliases::tag(pool, lease, &base.image_id, &keeper) } +fn loaded( + pool: &P, + lease: &P::Lease, + base: &super::BuildBase, +) -> Result { + Ok(pool.inspect(lease, &base.image_id)?.is_some_and(|image| { + image["Id"] == base.image_id && image["Os"] == "linux" && image["Architecture"] == "arm64" + })) +} + +fn retain_pin( + pool: &LivePool<'_>, + policy: &ImagePolicy, + base: &super::BuildBase, + still_needed: impl Fn() -> Result, +) -> Result<(), CandidateError> { + let candidate = pool.candidate; + let identity = { + let (lease, identity) = pool.try_lease()?; + let _idle = idle_retention_fence(candidate)?; + if !still_needed()? { + return Err(super::refusal( + "provider_busy", + "Background image retention deferred.", + )); + } + if loaded(pool, &lease, base)? { + return retain_verified(pool, &lease, base, || { + unreachable!("image checked under lease") + }); + } + identity + }; + + // Network and host archive work do not reserve the engine. A foreground + // operation arriving during staging can take the provider lease. + image_ensure::cache( + candidate, + &base.pinned_reference, + policy, + PlatformPolicy::Native, + )?; + + let (lease, current) = pool.try_lease()?; + let _idle = idle_retention_fence(candidate)?; + if current != identity || !still_needed()? { + return Err(super::refusal( + "provider_busy", + "Background image retention deferred.", + )); + } + retain_verified(pool, &lease, base, || { + image_ensure::retain_build_image(candidate, &base.pinned_reference, policy, &lease) + .map(|_| ()) + }) +} + pub fn run( candidate: &Candidate, mut policy: ImagePolicy, ) -> Result { policy.local_registries.clear(); policy.tag_mode = ImageTagMode::Normal; - policy.opportunistic_locks = true; + policy.retention_root = Some(candidate.state_root.clone()); let deadline = Instant::now() + BUDGET; policy.build_deadline = Some(deadline); let mut report = RetentionReport::default(); @@ -89,20 +145,21 @@ pub fn run( break; } let result = (|| { - let (lease, _) = pool.try_lease()?; - let _fence = idle_retention_fence(candidate)?; - // An intervening solve can retire a queued input between visits. - if !reclaim::current_images(candidate)? - .inputs - .contains(&(reference.clone(), pin.clone())) { + let (_lease, _) = pool.try_lease()?; + let _idle = idle_retention_fence(candidate)?; + } + let needed = || { + Ok(reclaim::current_images(candidate)? + .inputs + .contains(&(reference.clone(), pin.clone()))) + }; + if !needed()? { return Ok(()); } if !pins.contains(&pin) { let (base, _) = select_build_base(candidate, &pin, &policy, None)?; - retain_verified(&pool, &lease, &base, || { - image_ensure::retain_build_image(candidate, &pin, &policy, &lease).map(|_| ()) - })?; + retain_pin(&pool, &policy, &base, needed)?; pins.insert(pin.clone()); report.retained += 1; } @@ -126,17 +183,9 @@ pub fn run( "The refreshed build base proof differs from its selection.", )); } - // Keep the previous selection usable offline until the + // Keep the previous selection usable offline until its // replacement has both a verified image and its keeper. - retain_verified(&pool, &lease, &base, || { - image_ensure::retain_build_image( - candidate, - &tag.pinned_reference, - &policy, - &lease, - ) - .map(|_| ()) - })?; + retain_pin(&pool, &policy, &base, needed)?; pins.insert(tag.pinned_reference.clone()); report.retained += 1; Ok(()) diff --git a/packages/runtime-core/src/provider/image_build/tests.rs b/packages/runtime-core/src/provider/image_build/tests.rs index 791ad6edc..19e715764 100644 --- a/packages/runtime-core/src/provider/image_build/tests.rs +++ b/packages/runtime-core/src/provider/image_build/tests.rs @@ -2088,6 +2088,26 @@ fn a_dead_build_alias_is_swept_only_after_the_worker_releases_its_key() { assert!(!path.exists()); } +#[test] +fn protected_receipt_reuses_read_only_while_reclaim_holds_the_fence() { + let fixture = Fixture::new(); + let inputs = fixture.inputs(Policy::Missing); + let pool = FakePool::new("pool-1"); + fixture.client(&inputs, "ok"); + pool.built(&inputs, "pool-1", serde_json::json!({})); + run(&fixture.candidate, &pool, &inputs, &never).unwrap(); + let before = fixture.receipt(&inputs).sequence; + let _reclaim = image_fence(&fixture.candidate, libc::LOCK_EX).unwrap(); + assert!( + reuse_receipt(&fixture.candidate, &pool, &inputs, None) + .unwrap() + .unwrap() + .reused + ); + assert_eq!(fixture.receipt(&inputs).sequence, before); + assert_eq!(fixture.calls(&inputs), 1); +} + #[test] fn idle_retention_reuses_loaded_base_and_imports_an_absent_base_once() { let fixture = Fixture::new(); @@ -2097,9 +2117,14 @@ fn idle_retention_reuses_loaded_base_and_imports_an_absent_base_once() { source_digest: PIN.into(), image_id: PIN.into(), }; + let provider = state::Lock::acquire(&fixture.candidate.state_root.join("run/smolvm")).unwrap(); + assert!(check_retention_idle(&fixture.candidate.state_root).is_err()); + drop(provider); let build = image_fence(&fixture.candidate, libc::LOCK_SH).unwrap(); + assert!(check_retention_idle(&fixture.candidate.state_root).is_err()); assert!(idle_retention_fence(&fixture.candidate).is_err()); drop(build); + check_retention_idle(&fixture.candidate.state_root).unwrap(); let _idle = idle_retention_fence(&fixture.candidate).unwrap(); let _observer = image_fence(&fixture.candidate, libc::LOCK_SH).unwrap(); assert!(image_fence(&fixture.candidate, libc::LOCK_EX).is_err()); diff --git a/packages/runtime-core/src/provider/image_ensure.rs b/packages/runtime-core/src/provider/image_ensure.rs index 97e0a9b0e..fa08aabc1 100644 --- a/packages/runtime-core/src/provider/image_ensure.rs +++ b/packages/runtime-core/src/provider/image_ensure.rs @@ -70,7 +70,7 @@ impl ImageCache { if let Some(lease) = &cache.lease { lease.verify_path(root)?; } else { - let lease = if policy.opportunistic_locks { + let lease = if policy.retention_root.is_some() { state::Lock::acquire(root)? } else { state::wait_for_image_lock( @@ -886,13 +886,13 @@ fn confirm_selection( policy, platform, |reference, platform| { - if offline { + if offline || existing_engine.is_some() { return Err(no_archive()); } registry_image::pinned_platform(reference, policy, platform) }, |reference, path, platform, limit| { - if offline { + if offline || existing_engine.is_some() { return Err(no_archive()); } let mut acquired = registry_image::acquire_with_disk_admission( @@ -912,7 +912,7 @@ fn confirm_selection( check_registry_config(receipt, *selected, config)?; return Ok(config.clone()); } - if offline { + if offline || existing_engine.is_some() { return Err(no_archive()); } let proof = match acquired_proof.borrow_mut().take() { diff --git a/packages/runtime-core/src/provider/image_policy.rs b/packages/runtime-core/src/provider/image_policy.rs index f5ae1b1d3..e8783ec0d 100644 --- a/packages/runtime-core/src/provider/image_policy.rs +++ b/packages/runtime-core/src/provider/image_policy.rs @@ -68,7 +68,7 @@ pub struct ImagePolicy { pub tag_mode: ImageTagMode, pub(crate) short_tag_refresh: bool, pub(crate) build_deadline: Option, - pub(super) opportunistic_locks: bool, + pub(super) retention_root: Option, pub(crate) command_image_pin: Option, /// Registries that are refused as local unless named here. pub local_registries: Vec, @@ -92,7 +92,7 @@ impl Default for ImagePolicy { tag_mode: ImageTagMode::Normal, short_tag_refresh: false, build_deadline: None, - opportunistic_locks: false, + retention_root: None, command_image_pin: None, local_registries: Vec::new(), docker_config: None, diff --git a/packages/runtime-core/src/provider/image_tag_store.rs b/packages/runtime-core/src/provider/image_tag_store.rs index 0791a7709..53e333914 100644 --- a/packages/runtime-core/src/provider/image_tag_store.rs +++ b/packages/runtime-core/src/provider/image_tag_store.rs @@ -490,7 +490,7 @@ fn resolve_pending( // Recheck under the writer lock so an automatic refresh can reuse a // resolution another process just published. let lock = match state::Lock::acquire(&root) { - Err(error) if error.code == "provider_busy" && !policy.opportunistic_locks => { + Err(error) if error.code == "provider_busy" && policy.retention_root.is_none() => { let lock = policy .image_wait(std::time::Duration::from_secs(590)) .and_then(|wait| { diff --git a/packages/runtime-core/src/provider/registry_image.rs b/packages/runtime-core/src/provider/registry_image.rs index bdcd1333d..042bb45aa 100644 --- a/packages/runtime-core/src/provider/registry_image.rs +++ b/packages/runtime-core/src/provider/registry_image.rs @@ -863,6 +863,7 @@ struct Fetch<'a> { stage: Stage, deadline: Instant, request_timeout: Duration, + next_idle_check: Instant, } impl<'a> Fetch<'a> { @@ -906,9 +907,20 @@ impl<'a> Fetch<'a> { stage: Stage::Anonymous, deadline: Instant::now() + wait, request_timeout: REQUEST_TIMEOUT, + next_idle_check: Instant::now(), }) } + fn check_retention_idle(&mut self) -> Result<(), CandidateError> { + if let Some(root) = &self.policy.retention_root + && Instant::now() >= self.next_idle_check + { + super::image_build::check_retention_idle(root)?; + self.next_idle_check = Instant::now() + Duration::from_millis(250); + } + Ok(()) + } + fn remaining(&self) -> Result { self.deadline .checked_duration_since(Instant::now()) @@ -1094,6 +1106,7 @@ impl<'a> Fetch<'a> { timeout: Duration, retry: bool, ) -> Result { + self.check_retention_idle()?; loop { let response = self.send(url.clone(), timeout, retry)?; let status = response.status(); @@ -1424,6 +1437,7 @@ impl<'a> Fetch<'a> { let mut total = 0_u64; let mut buffer = vec![0_u8; 64 * 1024]; loop { + self.check_retention_idle().map_err(LayerAttempt::Refused)?; let n = match response.read(&mut buffer) { Ok(0) => break, Ok(n) => n, diff --git a/src/backends/native-project-start.ts b/src/backends/native-project-start.ts index b5af4a4e2..da62e164a 100644 --- a/src/backends/native-project-start.ts +++ b/src/backends/native-project-start.ts @@ -218,6 +218,7 @@ import { } from "./native-restart-policy-notices.ts"; import { invokeNativeRuntime, + NATIVE_BUILD_RETENTION_TIMEOUT_MS, NATIVE_IDLE_POOL_NOTE, NativeRuntimeRequestError, type NativeRuntimeSelection, @@ -3290,9 +3291,9 @@ async function startNativeProjectAttempt( let code = 1; let serveFailure: unknown; let retentionTimer: ReturnType | undefined; - let retentionStopped = false; + const retention = new AbortController(); const scheduleRetention = (attempt: number) => { - if (retentionStopped || controller.signal.aborted) { + if (retention.signal.aborted || controller.signal.aborted) { return; } retentionTimer = setTimeout( @@ -3303,6 +3304,10 @@ async function startNativeProjectAttempt( run, runtime: opts.runtime, invoke: deps.invoke, + signal: AbortSignal.any([ + controller.signal, + retention.signal, + ]), }).then((deferred) => { if (deferred && attempt < 3) { scheduleRetention(attempt + 1); @@ -3544,7 +3549,7 @@ async function startNativeProjectAttempt( } catch (error) { serveFailure = error; } finally { - retentionStopped = true; + retention.abort(); clearTimeout(retentionTimer); await startupStatus.stop(); delivery.payload?.fill(0); @@ -3706,6 +3711,7 @@ async function startNativeProjectAttempt( async function retainReadyBuildBases(opts: { readonly scope: NativeProjectRunScope; readonly run: string; + readonly signal: AbortSignal; readonly runtime: NativeRuntimeSelection; readonly invoke: typeof invokeNativeRuntime; }): Promise { @@ -3719,7 +3725,8 @@ async function retainReadyBuildBases(opts: { "--json", ...nativeImagePolicyArgs(), ], - timeoutMs: 30 * 60_000 + 5000, + timeoutMs: NATIVE_BUILD_RETENTION_TIMEOUT_MS, + signal: opts.signal, }); if ( isRecord(result) && @@ -3731,6 +3738,9 @@ async function retainReadyBuildBases(opts: { } catch { // Maintenance failures are private lifecycle notes. } + if (opts.signal.aborted) { + return false; + } await appendLifecycleLogRecord({ projectDir: opts.scope.projectDir, composeProject: opts.run, diff --git a/src/backends/native-runtime-client.ts b/src/backends/native-runtime-client.ts index bfe6c1eff..613913faa 100644 --- a/src/backends/native-runtime-client.ts +++ b/src/backends/native-runtime-client.ts @@ -39,6 +39,8 @@ import { readNativeStopFailures, } from "./native-stop-diagnostics.ts"; +export const NATIVE_BUILD_RETENTION_TIMEOUT_MS = 30 * 60_000 + 5000; + const ERROR_CODE = /^[a-z][a-z0-9_]{0,63}$/; const NATIVE_SERVICE = /^[A-Za-z0-9_.-]{1,128}$/; const NATIVE_TAIL = /^[1-9][0-9]{0,3}$/; @@ -842,12 +844,18 @@ export async function invokeNativeRuntime(opts: { // Internal invariant: callers build these argv shapes; no user input selects them. throw new Error(REQUEST_BUDGET_REFUSAL); } - const imageBatch = - opts.args[0] === "runtime" && opts.args[1] === "ensure-images"; + const runtimeCommand = opts.args[0] === "runtime" ? opts.args[1] : undefined; + const imageBatch = runtimeCommand === "ensure-images"; + let maxTimeoutMs = 600_000; + if (imageBatch) { + maxTimeoutMs = 3_600_000; + } else if (runtimeCommand === "retain-build-bases") { + maxTimeoutMs = NATIVE_BUILD_RETENTION_TIMEOUT_MS; + } if ( !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || - timeoutMs > (imageBatch ? 3_600_000 : 600_000) || + timeoutMs > maxTimeoutMs || (opts.privateInput?.byteLength ?? 0) > MAX_PRIVATE_INPUT_BYTES ) { // A selected startup timeout or the managed environment size can exceed these bounds. diff --git a/tests/native-runtime-client.test.ts b/tests/native-runtime-client.test.ts index 406ea9ac4..1ebc2be32 100644 --- a/tests/native-runtime-client.test.ts +++ b/tests/native-runtime-client.test.ts @@ -5,6 +5,7 @@ import { join } from "node:path"; import { invokeNativeRuntime, isNativeRuntimeNotRunning, + NATIVE_BUILD_RETENTION_TIMEOUT_MS, NATIVE_EXIT_DRAIN_BOUND_MS, NativeRuntimeRequestError, nativeCodesReportRuntimeNotRunning, @@ -1032,6 +1033,25 @@ await Bun.sleep(60_000); CASE_TIMEOUT_MS ); +test("build retention admits its full budget through the native client", async () => { + const runtime = await fixture(); + const args = ["runtime", "retain-build-bases", "--json"]; + const request = { runtime, cwd: runtime.home, args }; + const result = await invokeNativeRuntime({ + ...request, + timeoutMs: NATIVE_BUILD_RETENTION_TIMEOUT_MS, + }); + expect(result).toHaveProperty("args", expect.arrayContaining(args)); + await expectCodedRefusal( + invokeNativeRuntime({ + ...request, + timeoutMs: NATIVE_BUILD_RETENTION_TIMEOUT_MS + 1, + }), + "E_CONFIG_INVALID", + "input or time budget" + ); +}); + test("private-input and response bounds reject instead of truncating", async () => { const runtime = await fixture(); // A managed environment or a selected timeout can exceed the bounds: a From aaf4699b89d4711a1e8700f6eb2b0e13c4feb7af Mon Sep 17 00:00:00 2001 From: Kit <344842+roodboi@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:13:38 +0000 Subject: [PATCH 33/33] feat: allow opting out of native build base retention --- docs/reference/disk-footprint.md | 15 +++++++++++++++ src/backends/native-project-start.ts | 6 +++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/docs/reference/disk-footprint.md b/docs/reference/disk-footprint.md index 7451a6b62..745b7338c 100644 --- a/docs/reference/disk-footprint.md +++ b/docs/reference/disk-footprint.md @@ -29,8 +29,23 @@ objects as attribution within those disks when measuring host space. | Native images and BuildKit cache | [Image import](../../packages/runtime-core/src/provider/image_load.rs), [build](../../packages/runtime-core/src/provider/image_build.rs) and [reclaim](../../packages/runtime-core/src/provider/image_build/reclaim.rs) in the guest engine. | Best-effort post-build cache target of 8 GiB. No aggregate image bound found. | Image reclamation uses retained references. Failed or interrupted pruning can leave extra engine data. | | Native graph containers, persistent volumes, networks and graph receipts | [Graph runtime](../../packages/runtime-core/src/provider/graph/mod.rs), with host journals and guest resources. | No aggregate graph or retained-volume bound. | Down and recovery retain data by default. A crash can leave resources attached to prior receipts. | +### Native build base retention + +After a native `hack up` reaches readiness, Hack can retain exact build bases +as guest engine images and stage missing images in the host image archive cache. +The guest cost is the retained layers that the engine cannot share with other +images. In one 11-service project, retaining two bases added 1.06 GiB of engine +image data. Reclaim checks the current and previous verified build generations +and protects images still referenced by services or tag records. + +Set `HACK_NATIVE_BUILD_RETENTION=0` in the environment that launches `hack up` +to disable automatic retention. This also disables background build-base tag +refresh for that invocation. Existing images and archives remain on disk until +their normal cleanup runs. + ## Temporary paths + | Location | Owner | Growth bound | Cleanup and interrupted operations | | --- | --- | --- | --- | | `hkgf-*` | Foreground graph [transport](../../packages/runtime-core/src/provider/graph/foreground/transport.rs), one root per run. | No aggregate bound. | Retirement preserves evidence used by recovery. A dead publisher can leave its directories and lock records. | diff --git a/src/backends/native-project-start.ts b/src/backends/native-project-start.ts index da62e164a..4fe2ba7ac 100644 --- a/src/backends/native-project-start.ts +++ b/src/backends/native-project-start.ts @@ -3533,7 +3533,11 @@ async function startNativeProjectAttempt( httpsPort, }) ); - if (built.size > 0 && opts.imageTagMode !== "offline") { + if ( + built.size > 0 && + opts.imageTagMode !== "offline" && + process.env.HACK_NATIVE_BUILD_RETENTION !== "0" + ) { scheduleRetention(0); } // Superseded build images go once the new ones run; this never