diff --git a/crates/griffr-cli/src/commands/install/run.rs b/crates/griffr-cli/src/commands/install/run.rs index d78002f..94dc745 100644 --- a/crates/griffr-cli/src/commands/install/run.rs +++ b/crates/griffr-cli/src/commands/install/run.rs @@ -176,6 +176,9 @@ pub(super) async fn install_hypergryph( .context("Failed to build the install content plan")?; let change_start = start_install_change(&install_path, &change_state)?; + content_plan + .reclaim_payload_temps(change_state.sync_vfs, false) + .await?; match change_start { InstallChangeStart::New => {} InstallChangeStart::Resume => { @@ -245,6 +248,9 @@ pub(super) async fn install_hypergryph( sync_launcher_metadata(&api_client, &install_path, content_plan.snapshot()) .await .context("Failed to sync launcher metadata after resumed install verification")?; + content_plan + .reclaim_payload_temps(change_state.sync_vfs, true) + .await?; finish_install_change(&install_path, &change_state) .context("Failed to remove the install change marker")?; ui::print_success("Install resume finished"); @@ -474,6 +480,9 @@ pub(super) async fn install_hypergryph( sync_launcher_metadata(&api_client, &install_path, content_plan.snapshot()) .await .context("Failed to sync launcher metadata after final install verification")?; + content_plan + .reclaim_payload_temps(change_state.sync_vfs, true) + .await?; finish_install_change(&install_path, &change_state) .context("Failed to remove the install change marker")?; diff --git a/crates/griffr-cli/src/commands/update/run.rs b/crates/griffr-cli/src/commands/update/run.rs index 0859b0e..a1c5572 100644 --- a/crates/griffr-cli/src/commands/update/run.rs +++ b/crates/griffr-cli/src/commands/update/run.rs @@ -292,6 +292,9 @@ pub(super) async fn update_internal( let mut content_plan = ContentPlan::from_snapshot(&local.install_path, manifest_snapshot, &vfs_plan.claims) .context("Failed to build the update content plan")?; + content_plan + .reclaim_payload_temps(state.sync_vfs, false) + .await?; let post_update = verify_updated_install( api_client, &install_target.api, @@ -307,6 +310,9 @@ pub(super) async fn update_internal( ) .await?; debug_assert_eq!(post_update, PostUpdateResult::Verified); + content_plan + .reclaim_payload_temps(state.sync_vfs, true) + .await?; finish_install_change(&local.install_path, state) .context("Failed to remove the install change marker")?; ui::print_success(format!("Unfinished {} target verified", state.kind)); @@ -607,6 +613,10 @@ pub(super) async fn update_internal( )), } + content_plan + .reclaim_payload_temps(change_state.sync_vfs, false) + .await?; + // Delete intent belongs to the compatible official patch even when its // payload loses the delivery comparison. The patch apply route itself // retains ownership of deletes and releases bases after their consumers. @@ -744,6 +754,9 @@ pub(super) async fn update_internal( ) .await?; if post_update == PostUpdateResult::Verified { + content_plan + .reclaim_payload_temps(change_state.sync_vfs, true) + .await?; finish_install_change(&local.install_path, &change_state) .context("Failed to remove the install change marker")?; ui::print_success("Update finished"); diff --git a/crates/griffr-cli/src/commands/verify.rs b/crates/griffr-cli/src/commands/verify.rs index b378573..6178bce 100644 --- a/crates/griffr-cli/src/commands/verify.rs +++ b/crates/griffr-cli/src/commands/verify.rs @@ -168,6 +168,9 @@ impl RepairTransaction { sync_launcher_metadata(api_client, install_path, content_plan.snapshot()) .await .context("Failed to sync launcher metadata after repair")?; + content_plan + .reclaim_payload_temps(self.scope != crate::VerifyScopeArg::Core, true) + .await?; if let Some(state) = self.change.as_ref() { finish_install_change(install_path, state) .context("Failed to remove the install change marker")?; @@ -559,6 +562,11 @@ async fn verify_one( &vfs_plan, text_output, )?; + if execute_repairs && effective_scope != crate::VerifyScopeArg::Resources { + content_plan + .reclaim_payload_temps(effective_scope != crate::VerifyScopeArg::Core, false) + .await?; + } let summary = run_integrity_pool( &content_plan, match (effective_scope, execute_repairs) { diff --git a/crates/griffr-cli/src/progress.rs b/crates/griffr-cli/src/progress.rs index 6a6bc48..44989f5 100644 --- a/crates/griffr-cli/src/progress.rs +++ b/crates/griffr-cli/src/progress.rs @@ -22,6 +22,7 @@ pub struct StepProgress { label: String, verbose: bool, started: Arc, + terminal: Arc, plain: bool, last_plain: Arc, multi: Option>, @@ -64,6 +65,7 @@ impl StepProgress { label: label.into(), verbose, started: Arc::new(AtomicBool::new(false)), + terminal: Arc::new(AtomicBool::new(false)), plain: !std::io::stderr().is_terminal(), last_plain: Arc::new(AtomicU64::new(u64::MAX)), multi, @@ -175,17 +177,30 @@ impl StepProgress { } pub fn finish(&self) { - if crate::ui::is_quiet() || !self.started.load(Ordering::Acquire) { + self.finish_with_status(None); + } + + fn finish_with_status(&self, failure: Option<&str>) { + if crate::ui::is_quiet() + || !self.started.load(Ordering::Acquire) + || self.terminal.swap(true, Ordering::AcqRel) + { return; } let done = self.bar.position(); let total = self.bar.length().unwrap_or(done); + let status = if failure.is_some() { "failed" } else { "done" }; + let message = format!("{} {} ({}/{})", self.label, status, done, total); if self.plain { - eprintln!("{}: done ({}/{})", self.label, done, total); - return; + eprintln!("{message}"); + } + // Abandon preserves the observed position; finish_with_message forces + // the position to the target even when work failed. + if failure.is_some() { + self.bar.abandon_with_message(message); + } else { + self.bar.finish_with_message(message); } - self.bar - .finish_with_message(format!("{} done ({}/{})", self.label, done, total)); } fn ensure_started(&self, total: u64) { @@ -322,7 +337,7 @@ fn apply_update(route: &ProgressRoute, update: ProgressUpdate) { } } ProgressUpdate::Finished { .. } => route.bar.finish(), - ProgressUpdate::Failed { .. } => route.bar.finish(), + ProgressUpdate::Failed { reason, .. } => route.bar.finish_with_status(Some(&reason)), ProgressUpdate::Started { .. } => {} } } diff --git a/crates/griffr-cli/src/progress/tests.rs b/crates/griffr-cli/src/progress/tests.rs index 714bc59..a77913b 100644 --- a/crates/griffr-cli/src/progress/tests.rs +++ b/crates/griffr-cli/src/progress/tests.rs @@ -105,3 +105,29 @@ fn rendered_prefix_never_rounds_an_incomplete_count_to_100() { progress.update_count(13_315, 13_315, ""); assert_eq!(progress.bar.prefix(), "100%"); } + +#[test] +fn failed_progress_is_terminal_and_keeps_observed_position() { + let progress = CountAndByteProgress::new("verify", "repair.download", false); + hide_group(&progress.bytes); + let lane = ProgressLane::INTEGRITY_DOWNLOAD; + let session = progress.start(ProgressLane::INTEGRITY_VERIFY, lane); + let sender = session.sender(); + sender.emit(ProgressUpdate::Advanced { + lane, + finished: 32, + total: Some(128), + item: None, + }); + sender.emit(ProgressUpdate::Failed { + lane, + item: None, + reason: "download failed after retries".to_owned(), + }); + drop(sender); + session.finish(); + progress.finish(); + assert_eq!(progress.bytes.bar.position(), 32); + assert!(progress.bytes.bar.message().contains("failed")); + assert!(!progress.bytes.bar.message().contains("done")); +} diff --git a/crates/griffr-runtime/src/content_plan.rs b/crates/griffr-runtime/src/content_plan.rs index 5fae441..e4df83e 100644 --- a/crates/griffr-runtime/src/content_plan.rs +++ b/crates/griffr-runtime/src/content_plan.rs @@ -293,6 +293,30 @@ impl ContentPlan { .collect() } + /// Retire obsolete ordinary payload temporaries at a quiescent install + /// transaction boundary. The manifest protects all still-planned targets. + pub async fn reclaim_payload_temps( + &self, + include_resources: bool, + completed: bool, + ) -> Result { + let root = self.install_root.clone(); + let targets = self + .files + .values() + .map(|file| file.physical_path.clone()) + .collect::>(); + crate::compat_fs::run_blocking("reclaim payload temporaries", move || { + crate::install_change::temps::reclaim_payload_temps( + &root, + &targets, + include_resources, + completed, + ) + }) + .await + } + pub fn planned_files(&self) -> impl Iterator { self.files.values() } diff --git a/crates/griffr-runtime/src/download/extractor/range.rs b/crates/griffr-runtime/src/download/extractor/range.rs index 7d6abeb..7ea2ff6 100644 --- a/crates/griffr-runtime/src/download/extractor/range.rs +++ b/crates/griffr-runtime/src/download/extractor/range.rs @@ -5,7 +5,6 @@ use std::time::Duration; use compio::time::timeout; use crate::error::{Error, Result}; -use crate::preallocate_file; use griffr_hypergryph_api::protocol::{RANGE_HEADER, USER_AGENT_HEADER}; const ARCHIVE_RANGE_SEND_TIMEOUT: Duration = Duration::from_secs(60); @@ -129,7 +128,12 @@ pub(crate) async fn fetch_archive_range_to_cache( path: part_path.clone(), source, })?; - preallocate_file(&file, &part_path, expected)?; + // Do not retain unwritten KEEP_SIZE allocation on Linux after interruption. + #[cfg(windows)] + if let Err(error) = crate::preallocate_file(&file, &part_path, expected) { + return crate::task_pool::download_write::close_http_output(file, &part_path, Err(error)) + .await; + } let flush_threshold = progress_buffer_bytes.max(64 * 1024) as u64; let mut last_reported = resume_offset; @@ -150,6 +154,17 @@ pub(crate) async fn fetch_archive_range_to_cache( ) .await?; + crate::task_pool::download_write::close_http_output(file, &part_path, Ok(())).await?; + + if current_offset > expected { + compio::fs::remove_file(&part_path) + .await + .map_err(|source| Error::IoAt { + action: "remove file or directory", + path: part_path.clone(), + source, + })?; + } if current_offset != expected { return Err(Error::Message { context: "Download error: ", @@ -160,12 +175,6 @@ pub(crate) async fn fetch_archive_range_to_cache( }); } - file.close().await.map_err(|source| Error::IoAt { - action: "write to file", - path: part_path.clone(), - source, - })?; - save_archive_range_file(&part_path, &request.cache_path).await?; Ok(expected) } diff --git a/crates/griffr-runtime/src/http_download.rs b/crates/griffr-runtime/src/http_download.rs index 5539a85..a59e9eb 100644 --- a/crates/griffr-runtime/src/http_download.rs +++ b/crates/griffr-runtime/src/http_download.rs @@ -158,11 +158,12 @@ pub async fn download_file( |_| {}, ) .await?; - output.sync_data().await.map_err(|source| Error::IoAt { + let synced = output.sync_data().await.map_err(|source| Error::IoAt { action: "write to file", path: output_path.to_path_buf(), source, - })?; + }); + crate::task_pool::download_write::close_http_output(output, output_path, synced).await?; Ok(griffr_core::to_hex(&hasher.finalize())) } diff --git a/crates/griffr-runtime/src/install_change/mod.rs b/crates/griffr-runtime/src/install_change/mod.rs index e0b9452..a7b9c45 100644 --- a/crates/griffr-runtime/src/install_change/mod.rs +++ b/crates/griffr-runtime/src/install_change/mod.rs @@ -1,3 +1,5 @@ +pub(crate) mod temps; + use std::io::ErrorKind; use std::path::{Path, PathBuf}; diff --git a/crates/griffr-runtime/src/install_change/temps.rs b/crates/griffr-runtime/src/install_change/temps.rs new file mode 100644 index 0000000..624ea58 --- /dev/null +++ b/crates/griffr-runtime/src/install_change/temps.rs @@ -0,0 +1,336 @@ +use std::collections::HashSet; +use std::io::ErrorKind; +use std::path::{Path, PathBuf}; + +use crate::error::{Error, Result}; + +/// A transaction may reclaim ordinary payload temporaries after its previous +/// writers have stopped. Private archive/patch/predownload caches and linked +/// directories have independent lifecycles and are not traversed. +pub(crate) fn reclaim_payload_temps( + root: &Path, + targets: &[PathBuf], + include_resources: bool, + completed: bool, +) -> Result { + let targets = targets + .iter() + .filter_map(|path| { + path.strip_prefix(root) + .ok() + .map(|relative| crate::normalize_logical_path(&relative.to_string_lossy())) + }) + .collect::>(); + let mut dirs = vec![root.to_path_buf()]; + let mut removed = 0; + while let Some(dir) = dirs.pop() { + // A user-selected predownload directory can live inside the install + // without using the default private namespace. + if dir != root + && dir + .join(crate::patch_apply::PREDOWNLOAD_STAGE_METADATA_NAME) + .exists() + { + continue; + } + let entries = match std::fs::read_dir(&dir) { + Ok(entries) => entries, + Err(error) if error.kind() == ErrorKind::NotFound => continue, + Err(source) => { + return Err(Error::IoAt { + action: "read directory", + path: dir, + source, + }) + } + }; + for entry in entries { + let entry = entry.map_err(|source| Error::IoAt { + action: "read directory", + path: dir.clone(), + source, + })?; + let file_type = match entry.file_type() { + Ok(file_type) => file_type, + Err(error) if error.kind() == ErrorKind::NotFound => continue, + Err(source) => { + return Err(Error::IoAt { + action: "query file metadata/stat for", + path: entry.path(), + source, + }) + } + }; + if file_type.is_symlink() { + continue; + } + let name = entry.file_name(); + // Avoid a separate stat and path normalization for every ordinary + // payload file in a large install. + if !file_type.is_dir() + && !name.to_str().is_some_and(|name| { + name.starts_with('.') + && (name.ends_with(".griffr.part") || name.contains(".griffr.tmp.")) + }) + { + continue; + } + let path = entry.path(); + let relative = path.strip_prefix(root).expect("entry below install root"); + let key = crate::normalize_logical_path(&relative.to_string_lossy()); + let first = key.split('/').next().unwrap_or_default(); + if matches!(first, ".griffr" | "vfs_files" | "vfs_patch") { + continue; + } + if key.split('/').any(|component| component == "persistent") { + continue; + } + if !include_resources + && crate::is_resource_baseline_path(relative.to_string_lossy().as_ref()) + { + continue; + } + let metadata = match std::fs::symlink_metadata(&path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == ErrorKind::NotFound => continue, + Err(source) => { + return Err(Error::IoAt { + action: "query file metadata/stat for", + path, + source, + }) + } + }; + if metadata.file_type().is_symlink() { + continue; + } + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + if metadata.file_attributes() & 0x400 != 0 { + continue; + } + } + if metadata.is_dir() { + dirs.push(path); + continue; + } + if !metadata.is_file() || targets.contains(&key) { + continue; + } + let Some(name) = name.to_str() else { continue }; + let Some(name) = name.strip_prefix('.') else { + continue; + }; + let remove = if let Some(target) = name.strip_suffix(".griffr.part") { + if target.is_empty() { + continue; + } + let dest = relative.with_file_name(target); + if is_archive_volume_name(target) + && !targets.contains(&crate::normalize_logical_path(&dest.to_string_lossy())) + { + continue; + } + if !include_resources && crate::is_resource_baseline_path(&dest.to_string_lossy()) { + continue; + } + completed + || !targets.contains(&crate::normalize_logical_path(&dest.to_string_lossy())) + } else if let Some((target, id)) = name.rsplit_once(".griffr.tmp.") { + let Some((pid, counter)) = id.split_once('.') else { + continue; + }; + if target.is_empty() || counter.parse::().is_err() { + continue; + } + let Ok(pid) = pid.parse::() else { + continue; + }; + let dest = relative.with_file_name(target); + if is_archive_volume_name(target) + && !targets.contains(&crate::normalize_logical_path(&dest.to_string_lossy())) + { + continue; + } + if !include_resources && crate::is_resource_baseline_path(&dest.to_string_lossy()) { + continue; + } + !other_process_may_be_alive(pid) + } else { + false + }; + if remove { + match std::fs::remove_file(&path) { + Ok(()) => removed += 1, + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => { + tracing::warn!(path = %path.display(), %error, "failed to reclaim obsolete payload temporary") + } + } + } + } + } + Ok(removed) +} + +// The transaction's own writers are quiescent at these call sites. A tmp +// bearing a different live PID is conservatively retained (including PID reuse). +fn is_archive_volume_name(name: &str) -> bool { + let name = name.to_ascii_lowercase(); + if name.ends_with(".zip") { + return true; + } + name.rsplit_once(".zip.").is_some_and(|(_, sequence)| { + !sequence.is_empty() && sequence.bytes().all(|byte| byte.is_ascii_digit()) + }) +} + +fn other_process_may_be_alive(pid: u32) -> bool { + if pid == std::process::id() { + return false; + } + #[cfg(unix)] + { + if pid == 0 || pid > i32::MAX as u32 { + return true; + } + let result = unsafe { libc::kill(pid as i32, 0) }; + result == 0 || std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH) + } + #[cfg(windows)] + { + use windows_sys::Win32::Foundation::{CloseHandle, ERROR_INVALID_PARAMETER, WAIT_OBJECT_0}; + use windows_sys::Win32::System::Threading::{OpenProcess, WaitForSingleObject}; + const SYNCHRONIZE: u32 = 0x00100000; + let process = unsafe { OpenProcess(SYNCHRONIZE, 0, pid) }; + if process.is_null() { + return std::io::Error::last_os_error().raw_os_error() + != Some(ERROR_INVALID_PARAMETER as i32); + } + let alive = unsafe { WaitForSingleObject(process, 0) } != WAIT_OBJECT_0; + unsafe { CloseHandle(process) }; + alive + } + #[cfg(not(any(unix, windows)))] + true +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fixture(root: &Path, relative: &str) -> PathBuf { + let path = root.join(relative); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"test").unwrap(); + path + } + + #[test] + fn transaction_reclaims_only_owned_payload_temporaries() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let keep = fixture(root, "data/.current.bin.griffr.part"); + let obsolete = fixture(root, "data/.obsolete.bin.griffr.part"); + let stale = fixture( + root, + &format!("data/.current.bin.griffr.tmp.{}.0", std::process::id()), + ); + let normal = fixture(root, "data/ordinary.tmp"); + let malformed = fixture(root, "data/.fake.griffr.tmp.text.1"); + let planned = fixture(root, "data/.official.griffr.part"); + let private = fixture(root, ".griffr/patch/.base.griffr.part"); + let archive = fixture(root, ".griffr/archives/.bundle.griffr.part"); + let custom_stage = fixture(root, "custom-stage/.bundle.zip.001.griffr.part"); + let marked_stage = fixture(root, "marked-stage/.payload.griffr.part"); + fixture( + root, + &format!( + "marked-stage/{}", + crate::patch_apply::PREDOWNLOAD_STAGE_METADATA_NAME + ), + ); + let stage = fixture(root, "vfs_files/.payload.griffr.part"); + let persistent = fixture(root, "Game_Data/Persistent/VFS/.file.griffr.part"); + let resources = fixture(root, "Game_Data/StreamingAssets/VFS/.old.griffr.part"); + let index = fixture( + root, + "Game_Data/StreamingAssets/.index_main.json.griffr.part", + ); + let targets = vec![root.join("data/current.bin"), planned.clone()]; + assert_eq!( + reclaim_payload_temps(root, &targets, false, false).unwrap(), + 2 + ); + assert!(!obsolete.exists()); + assert!(!stale.exists()); + for path in [ + &keep, + &normal, + &malformed, + &planned, + &private, + &archive, + &custom_stage, + &marked_stage, + &stage, + &persistent, + &resources, + &index, + ] { + assert!(path.exists(), "removed {}", path.display()); + } + assert_eq!( + reclaim_payload_temps(root, &targets, false, true).unwrap(), + 1 + ); + assert!(!keep.exists()); + assert!(resources.exists()); + assert!(index.exists()); + assert_eq!( + reclaim_payload_temps(root, &targets, true, true).unwrap(), + 2 + ); + for path in [ + &normal, + &malformed, + &planned, + &private, + &archive, + &custom_stage, + &marked_stage, + &stage, + &persistent, + ] { + assert!(path.exists(), "removed {}", path.display()); + } + assert_eq!( + reclaim_payload_temps(root, &targets, true, true).unwrap(), + 0 + ); + } + + #[test] + fn cleanup_does_not_follow_linked_directories() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("install"); + let outside = temp.path().join("outside"); + std::fs::create_dir_all(&root).unwrap(); + let file = fixture(&outside, ".keep.griffr.part"); + #[cfg(unix)] + std::os::unix::fs::symlink(&outside, root.join("linked")).unwrap(); + #[cfg(windows)] + { + let result = std::process::Command::new("cmd") + .args(["/C", "mklink", "/J"]) + .arg(root.join("linked")) + .arg(&outside) + .output() + .unwrap(); + assert!(result.status.success(), "{:?}", result); + } + assert_eq!(reclaim_payload_temps(&root, &[], true, true).unwrap(), 0); + assert!(file.exists()); + } +} diff --git a/crates/griffr-runtime/src/task_pool/download.rs b/crates/griffr-runtime/src/task_pool/download.rs index be6a757..7925d65 100644 --- a/crates/griffr-runtime/src/task_pool/download.rs +++ b/crates/griffr-runtime/src/task_pool/download.rs @@ -4,10 +4,7 @@ use std::sync::OnceLock; use std::time::{Duration, Instant}; use crate::error::{Error, Result}; -use crate::{ - preallocate_file, ArtifactDigest, ArtifactExpectation, ArtifactProof, ArtifactSource, - ContentHash, -}; +use crate::{ArtifactDigest, ArtifactExpectation, ArtifactProof, ArtifactSource, ContentHash}; use griffr_hypergryph_api::protocol::{byte_range_from, RANGE_HEADER, USER_AGENT_HEADER}; use tracing::debug; @@ -278,8 +275,18 @@ pub(crate) async fn do_prepared_download( source: e, })?; + // Windows releases unused allocation on handle close. Linux KEEP_SIZE + // survives close, so resumable files grow as written on that platform. + #[cfg(windows)] if let Some(expected_size) = expected_size { - preallocate_file(&out, &part_path_for_write, expected_size)?; + if let Err(error) = crate::preallocate_file(&out, &part_path_for_write, expected_size) { + return super::download_write::close_http_output( + out, + &part_path_for_write, + Err(error), + ) + .await; + } } let mut hasher = if resume_effective { @@ -321,13 +328,22 @@ pub(crate) async fn do_prepared_download( } } - out.sync_data().await.map_err(|e| Error::IoAt { + let synced = out.sync_data().await.map_err(|e| Error::IoAt { action: "write to file", path: part_path_for_write.clone(), source: e, - })?; - + }); + super::download_write::close_http_output(out, &part_path_for_write, synced).await?; if let Some(expected) = expected_size { + if total_written > expected { + compio::fs::remove_file(&part_path_for_write) + .await + .map_err(|source| Error::IoAt { + action: "remove file or directory", + path: part_path_for_write.clone(), + source, + })?; + } if total_written != expected { return Err(Error::Message { context: "Download error: ", @@ -344,6 +360,13 @@ pub(crate) async fn do_prepared_download( }?; if actual_hash != *expected_hash { + compio::fs::remove_file(&part_path) + .await + .map_err(|source| Error::IoAt { + action: "remove file or directory", + path: part_path.clone(), + source, + })?; return Err(Error::Message { context: "Download error: ", detail: format!( diff --git a/crates/griffr-runtime/src/task_pool/download_write.rs b/crates/griffr-runtime/src/task_pool/download_write.rs index 71c0226..f5b3caa 100644 --- a/crates/griffr-runtime/src/task_pool/download_write.rs +++ b/crates/griffr-runtime/src/task_pool/download_write.rs @@ -18,7 +18,7 @@ const WRITE_QUEUE_DEPTH: usize = 2; #[allow(clippy::too_many_arguments)] pub(crate) async fn write_http_body( stream: S, - file: compio::fs::File, + mut file: compio::fs::File, path: &Path, item: &str, start_offset: u64, @@ -93,8 +93,7 @@ where Ok::(write_offset) }; - let writer = async move { - let mut file = file; + let writer = async { while let Ok((chunk, write_offset)) = write_rx.recv_async().await { let chunk_len = chunk.len() as u64; let BufResult(write_result, _) = file.write_all_at(chunk, write_offset).await; @@ -105,11 +104,37 @@ where })?; on_written(write_offset.saturating_add(chunk_len)); } - Ok::(file) + Ok::<(), Error>(()) }; - let (total_written, file) = futures_util::try_join!(producer, writer)?; - Ok((file, total_written)) + // The producer may fail while a write is in flight. Keep ownership of the + // handle outside both futures so the retry cannot race a deferred close. + match futures_util::try_join!(producer, writer) { + Ok((total_written, ())) => Ok((file, total_written)), + Err(error) => close_http_output(file, path, Err(error)).await, + } +} + +/// Close the output on both paths while preserving the original transfer error. +pub(crate) async fn close_http_output( + file: compio::fs::File, + path: &Path, + result: Result, +) -> Result { + let close_result = file.close().await.map_err(|source| Error::IoAt { + action: "close file", + path: path.to_path_buf(), + source, + }); + match result { + Ok(value) => close_result.map(|()| value), + Err(error) => { + if let Err(close_error) = close_result { + tracing::warn!(path = %path.display(), %close_error, "failed to close interrupted HTTP output"); + } + Err(error) + } + } } fn writer_stopped(item: &str) -> Error { diff --git a/crates/griffr-runtime/src/task_pool/fs_ops/mod.rs b/crates/griffr-runtime/src/task_pool/fs_ops/mod.rs index f8e65b7..7db32ec 100644 --- a/crates/griffr-runtime/src/task_pool/fs_ops/mod.rs +++ b/crates/griffr-runtime/src/task_pool/fs_ops/mod.rs @@ -23,7 +23,7 @@ pub(crate) use patch_manifest::{ pub(crate) use reuse::{ classify_reuse_mode, commit_partial_download, copy_verified_file_async, create_hardlink, hash_file_prefix_into_hasher, make_partial_download_path, make_temp_write_path, - storage_volume_group_key, storage_volume_id, ReuseMode, + retire_download_partial, storage_volume_group_key, storage_volume_id, ReuseMode, }; #[cfg(test)] diff --git a/crates/griffr-runtime/src/task_pool/fs_ops/reuse.rs b/crates/griffr-runtime/src/task_pool/fs_ops/reuse.rs index 39a305a..508a185 100644 --- a/crates/griffr-runtime/src/task_pool/fs_ops/reuse.rs +++ b/crates/griffr-runtime/src/task_pool/fs_ops/reuse.rs @@ -28,6 +28,32 @@ pub(crate) fn make_partial_download_path(path: &Path) -> Result { Ok(parent.join(format!(".{}.griffr.part", file_name))) } +/// Retire the direct-download partial once the same destination has been +/// verified or materialized by a different provider. Never follow a link. +pub(crate) fn retire_download_partial(dest: &Path) { + let Ok(part) = make_partial_download_path(dest) else { + return; + }; + let Ok(metadata) = std::fs::symlink_metadata(&part) else { + return; + }; + if !metadata.is_file() || metadata.file_type().is_symlink() { + return; + } + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + if metadata.file_attributes() & 0x400 != 0 { + return; + } + } + if let Err(error) = std::fs::remove_file(&part) { + if error.kind() != ErrorKind::NotFound { + tracing::warn!(path = %part.display(), %error, "failed to retire completed download partial"); + } + } +} + pub(crate) fn hash_file_prefix_into_hasher( path: &Path, prefix_len: u64, diff --git a/crates/griffr-runtime/src/task_pool/runner/archive/repair.rs b/crates/griffr-runtime/src/task_pool/runner/archive/repair.rs index b6657d5..b51ae49 100644 --- a/crates/griffr-runtime/src/task_pool/runner/archive/repair.rs +++ b/crates/griffr-runtime/src/task_pool/runner/archive/repair.rs @@ -232,17 +232,7 @@ pub(crate) fn run_extract_archive_repair_file( ); }; - if let Ok(part_path) = crate::task_pool::fs_ops::make_partial_download_path(&repair.dest) { - if let Err(error) = std::fs::remove_file(&part_path) { - if error.kind() != std::io::ErrorKind::NotFound { - tracing::warn!( - path = %part_path.display(), - %error, - "failed to remove stale individual-repair partial after archive repair" - ); - } - } - } + crate::task_pool::fs_ops::retire_download_partial(&repair.dest); let _ = event_tx.send(WorkerEvent::downloaded( repair.logical_path.clone(), diff --git a/crates/griffr-runtime/src/task_pool/runner/transfer.rs b/crates/griffr-runtime/src/task_pool/runner/transfer.rs index 9109057..27f649d 100644 --- a/crates/griffr-runtime/src/task_pool/runner/transfer.rs +++ b/crates/griffr-runtime/src/task_pool/runner/transfer.rs @@ -435,6 +435,7 @@ fn finish_reuse_file( }; match result { Ok(proof) => { + super::super::fs_ops::retire_download_partial(&dest); let _ = event_tx.send(WorkerEvent::committed(proof)); TaskRun::succeeded() } diff --git a/crates/griffr-runtime/src/task_pool/scheduler.rs b/crates/griffr-runtime/src/task_pool/scheduler.rs index 08e4fa7..74b2ac0 100644 --- a/crates/griffr-runtime/src/task_pool/scheduler.rs +++ b/crates/griffr-runtime/src/task_pool/scheduler.rs @@ -584,8 +584,13 @@ impl TaskPoolRunner { while let Ok(event) = event_rx.try_recv() { record_worker_event(&mut progress, &mut outcomes, event); } - progress.finish(); let graph_summary = graph.summary(); + let unsuccessful = graph_summary.failed_nodes + graph_summary.cancelled_nodes; + progress.finish( + (unsuccessful != 0) + .then(|| format!("{unsuccessful} failed or cancelled task node(s)")) + .as_deref(), + ); let mut metrics = metrics.snapshot(); metrics.graph = graph_summary.clone(); metrics.initial_graph_time = initial_graph_time; diff --git a/crates/griffr-runtime/src/task_pool/scheduler/progress.rs b/crates/griffr-runtime/src/task_pool/scheduler/progress.rs index d10886d..7fe8e18 100644 --- a/crates/griffr-runtime/src/task_pool/scheduler/progress.rs +++ b/crates/griffr-runtime/src/task_pool/scheduler/progress.rs @@ -226,10 +226,18 @@ impl TaskProgressReducer { } } - pub(super) fn finish(&self) { + pub(super) fn finish(&self, failure: Option<&str>) { + let terminal = |lane| match failure { + Some(reason) => ProgressUpdate::Failed { + lane, + item: None, + reason: reason.to_owned(), + }, + None => ProgressUpdate::Finished { lane }, + }; if let Some((lane, total)) = self.config.verify { if total > 0 { - self.config.sender.emit(ProgressUpdate::Finished { lane }); + self.config.sender.emit(terminal(lane)); } } for (started, lane) in [ @@ -241,7 +249,7 @@ impl TaskProgressReducer { ] { if started { if let Some(lane) = lane { - self.config.sender.emit(ProgressUpdate::Finished { lane }); + self.config.sender.emit(terminal(lane)); } } } diff --git a/crates/griffr-runtime/src/task_pool/scheduler/progress_tests.rs b/crates/griffr-runtime/src/task_pool/scheduler/progress_tests.rs index ae305f9..6250f43 100644 --- a/crates/griffr-runtime/src/task_pool/scheduler/progress_tests.rs +++ b/crates/griffr-runtime/src/task_pool/scheduler/progress_tests.rs @@ -80,7 +80,7 @@ fn reducer_emits_scoped_updates_without_regressing_retry_bytes() { false, )); reducer.handle(&WorkerEvent::verified("a.bin".to_string(), true, None)); - reducer.finish(); + reducer.finish(None); drop(reducer); let mut updates = Vec::new(); diff --git a/crates/griffr-runtime/src/task_pool/scheduler/routing.rs b/crates/griffr-runtime/src/task_pool/scheduler/routing.rs index 54ceb7d..24afa8c 100644 --- a/crates/griffr-runtime/src/task_pool/scheduler/routing.rs +++ b/crates/griffr-runtime/src/task_pool/scheduler/routing.rs @@ -171,11 +171,25 @@ pub(super) fn task_resources_cached(task: &Task, volumes: &mut VolumeKeyCache) - reserve_storage(&mut request, &repair.dest, repair.expected_size, volumes); } request.mutation_paths.push(path_key(&repair.dest)); + // A successful archive repair retires the direct-download partial. + if let Ok(part_path) = + crate::task_pool::fs_ops::make_partial_download_path(&repair.dest) + { + request.mutation_paths.push(path_key(&part_path)); + } request.extract = true; } - Task::Verify { path, .. } => request.read_volumes.push(volumes.resolve_verify_file(path)), - Task::VerifyMetadata { path, .. } => { + Task::Verify { path, on_fail, .. } => { + request.read_volumes.push(volumes.resolve_verify_file(path)); + if on_fail.is_some() { + route_partial_retirement(&mut request, path); + } + } + Task::VerifyMetadata { path, on_fail, .. } => { request.metadata_volumes.push(volume_key(volumes, path)); + if on_fail.is_some() { + route_partial_retirement(&mut request, path); + } } Task::Download { dest, @@ -204,10 +218,9 @@ pub(super) fn task_resources_cached(task: &Task, volumes: &mut VolumeKeyCache) - request.metadata_volumes.push(volume); } request.mutation_paths.push(path_key(dest)); - if resume.is_some() { - if let Ok(part_path) = crate::task_pool::fs_ops::make_partial_download_path(dest) { - request.mutation_paths.push(path_key(&part_path)); - } + // Preparation may discard or promote a partial before transfer. + if let Ok(part_path) = crate::task_pool::fs_ops::make_partial_download_path(dest) { + request.mutation_paths.push(path_key(&part_path)); } } Task::VerifyReuseVolume { candidates, .. } => { @@ -223,6 +236,7 @@ pub(super) fn task_resources_cached(task: &Task, volumes: &mut VolumeKeyCache) - expected_size, .. } => { + route_partial_retirement(&mut request, dest); if *copy_only { request.read_volumes.push(volume_key(volumes, source)); request.write_volumes.push(volume_key(volumes, dest)); @@ -664,6 +678,12 @@ pub(super) fn task_resources_cached(task: &Task, volumes: &mut VolumeKeyCache) - request } +fn route_partial_retirement(request: &mut ResourceRequest, dest: &Path) { + if let Ok(part_path) = crate::task_pool::fs_ops::make_partial_download_path(dest) { + request.mutation_paths.push(path_key(&part_path)); + } +} + fn route_archive_range_write( request: &mut ResourceRequest, range: &crate::download::extractor::ArchiveRangeRequest, diff --git a/crates/griffr-runtime/src/task_pool/test/download.rs b/crates/griffr-runtime/src/task_pool/test/download.rs index b9f0053..7358201 100644 --- a/crates/griffr-runtime/src/task_pool/test/download.rs +++ b/crates/griffr-runtime/src/task_pool/test/download.rs @@ -36,6 +36,8 @@ fn ensure_file_can_relink_verified_target_when_prefer_reuse_enabled() { let target = tmp.path().join("target.bin"); std::fs::write(&source, b"same-bytes").unwrap(); std::fs::write(&target, b"same-bytes").unwrap(); + let partial = make_partial_download_path(&target).unwrap(); + std::fs::write(&partial, b"stale").unwrap(); let expected_md5 = griffr_core::to_hex(&Md5::digest(b"same-bytes")); let tasks = vec![Task::ensure_file(FileEnsureTask { @@ -63,6 +65,7 @@ fn ensure_file_can_relink_verified_target_when_prefer_reuse_enabled() { )), "expected committed artifact proof after relink" ); + assert!(!partial.exists()); } #[test] @@ -269,3 +272,5 @@ fn bounded_download_writer_preserves_resumed_prefix() { assert_eq!(std::fs::read(&dest).unwrap(), expected); assert_eq!(progress.last().copied(), Some(written)); } + +mod tests; diff --git a/crates/griffr-runtime/src/task_pool/test/download/tests.rs b/crates/griffr-runtime/src/task_pool/test/download/tests.rs new file mode 100644 index 0000000..e95da27 --- /dev/null +++ b/crates/griffr-runtime/src/task_pool/test/download/tests.rs @@ -0,0 +1,538 @@ +use super::*; + +/// Single loopback connection per response, with bounded accept/read/write. +fn download_test_server( + responses: Vec<(String, Vec)>, +) -> (String, std::thread::JoinHandle>) { + use std::io::Read; + use std::time::{Duration, Instant}; + + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let addr = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + let mut requests = Vec::new(); + for (headers, body) in responses { + let deadline = Instant::now() + Duration::from_secs(15); + let mut socket = loop { + match listener.accept() { + Ok((socket, _)) => break socket, + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + assert!(Instant::now() < deadline, "no download request"); + std::thread::sleep(Duration::from_millis(5)); + } + Err(e) => panic!("{e}"), + } + }; + socket.set_nonblocking(false).unwrap(); + socket + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + socket + .set_write_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut request = Vec::new(); + while !request.ends_with(b"\r\n\r\n") && request.len() < 8192 { + let mut byte = [0]; + socket.read_exact(&mut byte).unwrap(); + request.push(byte[0]); + } + requests.push(String::from_utf8(request).unwrap().to_ascii_lowercase()); + socket.write_all(headers.as_bytes()).unwrap(); + socket.write_all(&body).unwrap(); + } + requests + }); + (format!("http://{addr}/payload"), server) +} + +#[cfg(windows)] +fn allocated_bytes(path: &std::path::Path) -> u64 { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Storage::FileSystem::{ + FileStandardInfo, GetFileInformationByHandleEx, FILE_STANDARD_INFO, + }; + let file = std::fs::File::open(path).unwrap(); + let mut info = std::mem::MaybeUninit::::uninit(); + let ok = unsafe { + GetFileInformationByHandleEx( + file.as_raw_handle() as _, + FileStandardInfo, + info.as_mut_ptr().cast(), + std::mem::size_of::() as u32, + ) + }; + assert_ne!(ok, 0, "{}", std::io::Error::last_os_error()); + unsafe { info.assume_init().AllocationSize as u64 } +} + +#[cfg(target_os = "linux")] +fn allocated_bytes(path: &std::path::Path) -> u64 { + use std::os::unix::fs::MetadataExt; + std::fs::metadata(path).unwrap().blocks() * 512 +} + +#[test] +fn exhausted_download_retries_keep_only_written_prefix_and_resume() { + let tmp = tempdir().unwrap(); + let dest = tmp.path().join("payload.bin"); + let part = make_partial_download_path(&dest).unwrap(); + let payload = (0..(32 * 1024 * 1024)) + .map(|i| (i % 251) as u8) + .collect::>(); + let size = payload.len() as u64; + let expected_md5 = griffr_core::to_hex(&Md5::digest(&payload)); + let (url, server) = download_test_server(vec![ + ( + format!("HTTP/1.1 200 OK\r\nContent-Length: {size}\r\nConnection: close\r\n\r\n"), + payload[..3 * 1024 * 1024].to_vec(), + ), + ( + "HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + .to_owned(), + Vec::new(), + ), + ]); + let (sender, receiver) = crate::ProgressSender::channel(); + let lane = crate::ProgressLane::INTEGRITY_DOWNLOAD; + let result = run_tasks_with_progress( + vec![Task::Download { + url, + dest: dest.clone(), + logical_path: "payload.bin".to_owned(), + expected_hash: expected_md5.clone().into(), + expected_size: Some(size), + retry_count: 0, + transfer_class: TransferClass::General, + archive_repair: None, + resume: None, + }], + TaskPoolConfig { + max_retries: 1, + ..TaskPoolConfig::default() + }, + TaskProgress::new(sender).with_download(lane), + ) + .unwrap(); + let requests = server.join().unwrap(); + assert_eq!(result.metrics.graph.failed_nodes, 1); + assert!(!dest.exists()); + let prefix = std::fs::read(&part).unwrap(); + assert!(!prefix.is_empty()); + assert!(prefix.len() < payload.len()); + assert_eq!(prefix, payload[..prefix.len()]); + assert!(requests[1].contains(&format!("range: bytes={}-", prefix.len()))); + #[cfg(any(windows, target_os = "linux"))] + { + let allocated = allocated_bytes(&part); + eprintln!( + "expected={size} prefix={} allocated={allocated}", + prefix.len() + ); + assert!( + allocated <= prefix.len() as u64 + 1024 * 1024, + "partial retains excess allocation: {allocated}" + ); + } + let updates = std::iter::from_fn(|| receiver.try_recv()).collect::>(); + assert!(updates + .iter() + .any(|u| matches!(u, crate::ProgressUpdate::Failed { lane: l, .. } if *l == lane))); + assert!(!updates + .iter() + .any(|u| matches!(u, crate::ProgressUpdate::Finished { lane: l } if *l == lane))); + + let offset = prefix.len(); + let (url, server) = download_test_server(vec![( + format!("HTTP/1.1 206 Partial Content\r\nContent-Length: {}\r\nContent-Range: bytes {}-{}/{}\r\nConnection: close\r\n\r\n", payload.len()-offset, offset, size-1, size), + payload[offset..].to_vec(), + )]); + assert_eq!( + do_download( + "Griffr test", + &url, + &dest, + &expected_md5, + Some(size), + DEFAULT_PROGRESS_BUFFER_BYTES, + None:: + ) + .unwrap(), + size + ); + assert!(server.join().unwrap()[0].contains(&format!("range: bytes={offset}-"))); + assert_eq!(std::fs::read(&dest).unwrap(), payload); + assert!(!part.exists()); +} + +#[test] +fn checksum_mismatch_discards_partial_without_another_attempt() { + let tmp = tempdir().unwrap(); + let dest = tmp.path().join("bad.bin"); + let part = make_partial_download_path(&dest).unwrap(); + let (url, server) = download_test_server(vec![( + "HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\n".to_owned(), + b"evil".to_vec(), + )]); + let md5 = griffr_core::to_hex(&Md5::digest(b"good")); + let err = do_download( + "Griffr test", + &url, + &dest, + &md5, + Some(4), + DEFAULT_PROGRESS_BUFFER_BYTES, + None::, + ) + .unwrap_err(); + server.join().unwrap(); + assert!(err.to_string().contains("mismatch"), "{err}"); + assert!(!part.exists()); + assert!(!dest.exists()); +} + +#[test] +fn interrupted_archive_range_releases_unused_allocation_and_resumes() { + use crate::download::extractor::{fetch_archive_range_to_cache, ArchiveRangeRequest}; + let tmp = tempdir().unwrap(); + let cache = tmp.path().join("v0000-7-33554439.range"); + let part = cache.with_extension("range.part"); + let payload = (0..(32 * 1024 * 1024)) + .map(|i| (i % 239) as u8) + .collect::>(); + let size = payload.len() as u64; + let start = 7u64; + let end = start + size; + let (url, server) = download_test_server(vec![( + format!("HTTP/1.1 206 Partial Content\r\nContent-Length: {size}\r\nContent-Range: bytes {start}-{}/{end}\r\nConnection: close\r\n\r\n", end-1), + payload[..3 * 1024 * 1024].to_vec(), + )]); + let mut request = ArchiveRangeRequest { + volume_index: 0, + local_range: start..end, + global_range: start..end, + url, + cache_path: cache.clone(), + }; + let runtime = compio::runtime::Runtime::new().unwrap(); + let result = runtime.block_on(fetch_archive_range_to_cache( + &request, + "Griffr test", + DEFAULT_PROGRESS_BUFFER_BYTES, + |_| {}, + )); + assert!(result.is_err()); + assert!(server.join().unwrap()[0].contains(&format!("range: bytes={start}-{}", end - 1))); + assert!(!cache.exists()); + let prefix = std::fs::read(&part).unwrap(); + assert!(!prefix.is_empty()); + assert!(prefix.len() < payload.len()); + assert_eq!(prefix, payload[..prefix.len()]); + #[cfg(any(windows, target_os = "linux"))] + { + let allocated = allocated_bytes(&part); + eprintln!( + "archive expected={size} prefix={} allocated={allocated}", + prefix.len() + ); + assert!(allocated <= prefix.len() as u64 + 1024 * 1024); + } + let offset = prefix.len(); + let (url, server) = download_test_server(vec![( + format!("HTTP/1.1 206 Partial Content\r\nContent-Length: {}\r\nContent-Range: bytes {}-{}/{end}\r\nConnection: close\r\n\r\n", size-offset as u64, start+offset as u64, end-1), + payload[offset..].to_vec(), + )]); + request.url = url; + assert_eq!( + runtime + .block_on(fetch_archive_range_to_cache( + &request, + "Griffr test", + DEFAULT_PROGRESS_BUFFER_BYTES, + |_| {} + )) + .unwrap(), + size + ); + assert!(server.join().unwrap()[0].contains(&format!( + "range: bytes={}-{}", + start + offset as u64, + end - 1 + ))); + assert_eq!(std::fs::read(&cache).unwrap(), payload); + assert!(!part.exists()); +} + +#[test] +fn interrupted_download_child_process() { + let Some(dest) = std::env::var_os("GRIFFR_TEST_INTERRUPTED_DEST") else { + return; + }; + let url = std::env::var("GRIFFR_TEST_INTERRUPTED_URL").unwrap(); + let payload = vec![42u8; 16 * 1024 * 1024]; + let _ = do_download( + "Griffr test", + &url, + std::path::Path::new(&dest), + &griffr_core::to_hex(&Md5::digest(&payload)), + Some(payload.len() as u64), + DEFAULT_PROGRESS_BUFFER_BYTES, + None::, + ); +} + +#[test] +fn killed_download_process_keeps_resumable_prefix() { + use std::io::Read; + use std::time::{Duration, Instant}; + let tmp = tempdir().unwrap(); + let dest = tmp.path().join("payload.bin"); + let part = make_partial_download_path(&dest).unwrap(); + let payload = vec![42u8; 16 * 1024 * 1024]; + let size = payload.len() as u64; + let hash = griffr_core::to_hex(&Md5::digest(&payload)); + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let address = listener.local_addr().unwrap(); + let (done_tx, done_rx) = flume::bounded::<()>(1); + let server = std::thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(15); + let mut socket = loop { + match listener.accept() { + Ok((socket, _)) => break socket, + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + assert!(Instant::now() < deadline, "no child request"); + std::thread::sleep(Duration::from_millis(10)); + } + Err(e) => panic!("{e}"), + } + }; + socket.set_nonblocking(false).unwrap(); + socket + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + socket + .set_write_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut request = Vec::new(); + while !request.ends_with(b"\r\n\r\n") && request.len() < 8192 { + let mut byte = [0]; + socket.read_exact(&mut byte).unwrap(); + request.push(byte[0]); + } + socket + .write_all( + format!("HTTP/1.1 200 OK\r\nContent-Length: {size}\r\nConnection: close\r\n\r\n") + .as_bytes(), + ) + .unwrap(); + socket.write_all(&vec![42u8; 3 * 1024 * 1024]).unwrap(); + let _ = done_rx.recv_timeout(Duration::from_secs(20)); + }); + let mut child = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "task_pool::test::download::tests::interrupted_download_child_process", + ]) + .env("GRIFFR_TEST_INTERRUPTED_DEST", &dest) + .env( + "GRIFFR_TEST_INTERRUPTED_URL", + format!("http://{address}/payload"), + ) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(15); + let prefix_written = loop { + if std::fs::metadata(&part).is_ok_and(|m| m.len() >= 1024 * 1024) { + break true; + } + if Instant::now() >= deadline || child.try_wait().unwrap().is_some() { + break false; + } + std::thread::sleep(Duration::from_millis(10)); + }; + let kill = child.kill(); + let status = child.wait().unwrap(); + let _ = done_tx.send(()); + server.join().unwrap(); + assert!(prefix_written, "child never wrote prefix: {status}"); + kill.unwrap(); + assert!(!status.success()); + assert!(!dest.exists()); + let prefix = std::fs::read(&part).unwrap(); + assert!(prefix.len() >= 1024 * 1024); + assert!(prefix.len() < payload.len()); + assert_eq!(prefix, payload[..prefix.len()]); + #[cfg(any(windows, target_os = "linux"))] + { + let allocated = allocated_bytes(&part); + eprintln!( + "killed expected={size} prefix={} allocated={allocated}", + prefix.len() + ); + assert!(allocated <= prefix.len() as u64 + 1024 * 1024); + } + let offset = prefix.len(); + let (url, server) = download_test_server(vec![( + format!("HTTP/1.1 206 Partial Content\r\nContent-Length: {}\r\nContent-Range: bytes {offset}-{}/{size}\r\nConnection: close\r\n\r\n", payload.len()-offset, size-1), + payload[offset..].to_vec(), + )]); + assert_eq!( + do_download( + "Griffr test", + &url, + &dest, + &hash, + Some(size), + DEFAULT_PROGRESS_BUFFER_BYTES, + None:: + ) + .unwrap(), + size + ); + assert!(server.join().unwrap()[0].contains(&format!("range: bytes={offset}-"))); + assert_eq!(std::fs::read(&dest).unwrap(), payload); + assert!(!part.exists()); +} + +#[test] +fn interrupted_download_batch_keeps_written_prefix_under_shared_capacity() { + let tmp = tempdir().unwrap(); + let count = 8; + let expected_size = 64 * 1024 * 1024; + let mut batches = [Vec::new(), Vec::new()]; + let mut servers = Vec::new(); + let mut destinations = Vec::new(); + for i in 0..count { + let dest = tmp.path().join(format!("payload-{i}.bin")); + let (url, server) = download_test_server(vec![( + format!( + "HTTP/1.1 200 OK\r\nContent-Length: {expected_size}\r\nConnection: close\r\n\r\n" + ), + vec![42u8; 3 * 1024 * 1024], + )]); + batches[i % 2].push(Task::Download { + url, + dest: dest.clone(), + logical_path: format!("payload-{i}.bin"), + expected_hash: "00".repeat(16).into(), + expected_size: Some(expected_size), + retry_count: 0, + transfer_class: TransferClass::General, + archive_repair: None, + resume: None, + }); + destinations.push(dest); + servers.push(server); + } + let mut config = TaskPoolConfig { + network_slots: 2, + max_retries: 0, + ..TaskPoolConfig::default() + }; + config.fit_blocking_pool_for_runners(2); + let group = TaskPoolRunnerGroup::new(config.clone()).unwrap(); + let mut left = group.runner(config.clone()).unwrap(); + let mut right = group.runner(config).unwrap(); + let [first, second] = batches; + let (a, b) = std::thread::scope(|scope| { + let a = scope.spawn(move || left.run_batch(first, TaskProgress::disabled()).unwrap()); + let b = scope.spawn(move || right.run_batch(second, TaskProgress::disabled()).unwrap()); + (a.join().unwrap(), b.join().unwrap()) + }); + for server in servers { + server.join().unwrap(); + } + assert_eq!( + a.metrics.graph.failed_nodes + b.metrics.graph.failed_nodes, + count + ); + let peak = a + .metrics + .global_capacity + .global_network_peak + .max(b.metrics.global_capacity.global_network_peak); + assert!((1..=2).contains(&peak)); + let mut prefix_bytes = 0; + #[cfg(any(windows, target_os = "linux"))] + let mut allocated = 0; + for dest in destinations { + assert!(!dest.exists()); + let part = make_partial_download_path(&dest).unwrap(); + let prefix = std::fs::read(&part).unwrap(); + assert!(!prefix.is_empty()); + assert!(prefix.iter().all(|&byte| byte == 42)); + assert!(prefix.len() <= 3 * 1024 * 1024); + prefix_bytes += prefix.len() as u64; + #[cfg(any(windows, target_os = "linux"))] + { + allocated += allocated_bytes(&part); + } + } + #[cfg(any(windows, target_os = "linux"))] + { + eprintln!("batch target_bytes={} prefix_bytes={prefix_bytes} allocated_bytes={allocated} shared_network_peak={peak}", expected_size * count as u64); + assert!(allocated <= prefix_bytes + count as u64 * 1024 * 1024); + } + assert!(prefix_bytes > 0); +} + +#[test] +fn repair_verification_retires_partial_but_read_only_verification_does_not() { + let tmp = tempdir().unwrap(); + let mut readonly = Vec::new(); + let mut repairs = Vec::new(); + let mut parts = Vec::new(); + for i in 0..4 { + let dest = tmp.path().join(format!("valid-{i}.bin")); + let part = make_partial_download_path(&dest).unwrap(); + std::fs::write(&dest, b"valid").unwrap(); + std::fs::write(&part, b"stale").unwrap(); + let expected_hash = crate::ContentHash::from(griffr_core::to_hex(&Md5::digest(b"valid"))); + readonly.push(Task::Verify { + path: dest.clone(), + logical_path: format!("valid-{i}.bin"), + expected_hash: expected_hash.clone(), + expected_size: Some(5), + on_fail: None, + }); + let spec = FileEnsureTask { + dest, + logical_path: format!("valid-{i}.bin"), + expected_hash, + expected_size: 5, + source_candidates: Vec::new(), + download_url: Some("http://127.0.0.1:1/not-needed".to_string()), + allow_copy_fallback: false, + copy_only: false, + prefer_reuse: false, + retry_count: 0, + transfer_class: TransferClass::General, + archive_repair: None, + }; + repairs.push(if i == 3 { + Task::ensure_file_metadata(spec) + } else { + Task::ensure_file(spec) + }); + parts.push(part); + } + assert_eq!( + run_tasks(readonly, TaskPoolConfig::default()) + .unwrap() + .metrics + .graph + .failed_nodes, + 0 + ); + assert!(parts.iter().all(|part| part.exists())); + assert_eq!( + run_tasks(repairs, TaskPoolConfig::default()) + .unwrap() + .metrics + .graph + .failed_nodes, + 0 + ); + assert!(parts.iter().all(|part| !part.exists())); +} diff --git a/crates/griffr-runtime/src/task_pool/verify.rs b/crates/griffr-runtime/src/task_pool/verify.rs index d41260f..8ad7f75 100644 --- a/crates/griffr-runtime/src/task_pool/verify.rs +++ b/crates/griffr-runtime/src/task_pool/verify.rs @@ -63,6 +63,9 @@ pub(crate) fn run_verify( expected_size, &mut read_bytes, ); + if issue.is_none() && on_fail.is_some() { + super::fs_ops::retire_download_partial(path); + } ( finish_verify(logical_path, issue, on_fail, event_tx), read_bytes, @@ -103,6 +106,7 @@ fn finish_verify( } struct Md5VerifyEntry { + repair_target: Option, file: Option, read_bytes: u64, logical_path: String, @@ -128,6 +132,7 @@ impl Md5VerifyEntry { debug_assert!(matches!(expected_hash, ContentHash::Md5(_))); let mut entry = Self { + repair_target: on_fail.as_ref().map(|_| path.clone()), file: None, read_bytes: 0, logical_path: logical_path.clone(), @@ -262,6 +267,11 @@ pub(crate) fn run_md5_verify_batch( entry.issue = Some(entry.hash_failure(Some(actual_hash))); } } + if entry.issue.is_none() { + if let Some(path) = &entry.repair_target { + super::fs_ops::retire_download_partial(path); + } + } let run = finish_verify(&entry.logical_path, entry.issue, entry.on_fail, event_tx); Md5VerifyBatchResult { run, @@ -280,6 +290,9 @@ pub(crate) fn run_metadata_verify( event_tx: &flume::Sender, ) -> super::graph::TaskRun { let issue = build_metadata_issue(path, logical_path, expected_hash, expected_size); + if issue.is_none() && on_fail.is_some() { + super::fs_ops::retire_download_partial(path); + } match issue { None => { let _ = event_tx.send(super::types::WorkerEvent::verified( diff --git a/crates/griffr-runtime/src/yostar_files.rs b/crates/griffr-runtime/src/yostar_files.rs index c142a50..06343c1 100644 --- a/crates/griffr-runtime/src/yostar_files.rs +++ b/crates/griffr-runtime/src/yostar_files.rs @@ -117,6 +117,18 @@ pub async fn ensure_yostar_files_with_pool( return Ok(summary); } + let root = install_path.to_path_buf(); + let targets = planned + .iter() + .map(|(_, relative)| root.join(relative)) + .collect::>(); + let scan_root = root.clone(); + let scan_targets = targets.clone(); + crate::compat_fs::run_blocking("reclaim obsolete YoStar temporaries", move || { + crate::install_change::temps::reclaim_payload_temps(&scan_root, &scan_targets, true, false) + }) + .await?; + let roots = provider_attempt_roots(cdn_roots); let mut last_error = None; for (index, cdn_root) in roots.iter().enumerate() { @@ -152,7 +164,20 @@ pub async fn ensure_yostar_files_with_pool( .with_download(ProgressLane::FILE_ENSURE_DOWNLOAD); match runner.run_batch(tasks, task_progress) { Ok(result) => match summarize_result(result.outcomes, &result.metrics.graph, true) { - Ok(summary) => return Ok(summary), + Ok(summary) => { + if summary.issues.is_empty() { + crate::compat_fs::run_blocking( + "reclaim completed YoStar temporaries", + move || { + crate::install_change::temps::reclaim_payload_temps( + &root, &targets, true, true, + ) + }, + ) + .await?; + } + return Ok(summary); + } Err(error) => last_error = Some(error), }, Err(error) => { diff --git a/docs/DESIGN_optimizations.md b/docs/DESIGN_optimizations.md index 75adae4..329ea70 100644 --- a/docs/DESIGN_optimizations.md +++ b/docs/DESIGN_optimizations.md @@ -40,15 +40,17 @@ This design uses six code stages followed by packaging metadata. - Scheduler CPU ordering uses the same estimated cost that formed the shards. - For shard run details, see [`DESIGN_task_pool.md#7-lazy-range-archive-dag`](DESIGN_task_pool.md#7-lazy-range-archive-dag). -## 6. Windows Allocation and Scheduler Reservation +## 6. File Allocation and Scheduler Reservation -- Download partials, archive ranges, ZIP entry outputs, cross-volume commits, and reuse copies reserve storage with `FILE_ALLOCATION_INFO` before streaming. +- On Windows, download partials, archive ranges, ZIP entry outputs, cross-volume commits, and reuse copies reserve storage with `FILE_ALLOCATION_INFO` before streaming. - The task scheduler tracks peak additional allocation per physical volume for each active writer, admitting new writers only when live free space covers active reservations. -- First writers use physical preallocation as the authoritative error point, allowing resume tasks to run on nearly full volumes. +- First writers use their allocation or write operation as the authoritative space check, allowing resume tasks to run on nearly full volumes. On Linux, resumable HTTP output grows with received bytes instead of retaining unwritten KEEP_SIZE allocation across interruptions. - Read-only, verify, delete, base-release, hardlink, and metadata-only tasks do not consume byte reservations. -- Failed copy paths remove partial temporary outputs immediately. +- Interrupted HTTP writes close the file handle before retrying; the logical EOF of the retained partial remains the resume boundary. Completed downloads with invalid content hash or an oversized payload remove their partial immediately. Failed copy paths remove partial temporary outputs immediately. +Ordinary install payload temporaries use the existing .griffr.part and .griffr.tmp.. naming contract. At a quiescent transaction boundary, the target manifest preserves still-planned download partials; a completed transaction can retire the remaining payload temporaries. Repair verification and successful reuse retire their own partials under scheduler path permits. Read-only verification does not mutate files. The scan skips private archive/patch/predownload state, unclaimed package archive volumes, linked directories, and the separate Persistent resource working set. A core-only operation also preserves the resource baseline. Atomic-write temporaries from another live PID are retained. These boundaries assume one mutating command per install; the install-change marker is recovery state, not a cross-process lock. + ## 7. Bounded Transfer and Scheduler Hot Paths - HTTP response chunks are coalesced into 1 MiB write batches and passed through a bounded two-entry queue. Receiving and digesting the next batch can overlap the previous `write_all_at` without allowing unbounded body buffering. diff --git a/docs/DESIGN_task_pool.md b/docs/DESIGN_task_pool.md index 729a74e..2825e59 100644 --- a/docs/DESIGN_task_pool.md +++ b/docs/DESIGN_task_pool.md @@ -158,7 +158,7 @@ Reads, writes, and metadata steps are keyed by stable physical-volume identity. Install-root mutation additionally uses path permits, so commit, patch, delete, hardlink, and cleanup tasks cannot mutate the same target concurrently. -Known-size writers also declare their peak additional allocation per physical volume. The first writer on a volume is always admitted: its own `FILE_ALLOCATION_INFO` preallocation remains the authoritative space check, so the scheduler never recreates an install-wide size estimate. While that writer is active, later writers are admitted only when the current free space can cover the active reservation plus the new task's declared peak. If the platform cannot provide a live free-space value, admission fails open and the writer's normal allocation/write error remains authoritative. This prevents several large outputs from starting against the same free bytes while allowing verify, delete, base release, and metadata-only work to proceed. +Known-size writers also declare their peak additional allocation per physical volume. The first writer on a volume is always admitted: its own allocation or write operation is authoritative, including `FILE_ALLOCATION_INFO` preallocation on Windows. The scheduler never recreates an install-wide size estimate. While that writer is active, later writers are admitted only when the current free space can cover the active reservation plus the new task's declared peak. If the platform cannot provide a live free-space value, admission fails open and the writer's normal allocation/write error remains authoritative. This prevents several large outputs from starting against the same free bytes while allowing verify, delete, base release, and metadata-only work to proceed. Reservations cover download remainders, range-cache files, reuse copies, extraction outputs, retained archive parts, patch preparation relocation, cross-volume commits, and local/HDiff patch outputs. Composite tasks declare the total output that can coexist during that task. Reservations are released when the task finishes; persistent output usage is observed through the next live free-space query. The queue takes one free-space snapshot per relevant volume for each scheduling pass, rather than querying once per candidate task.