From 02ee5f0fba9cc154a8d70cecab2524f668d4a94c Mon Sep 17 00:00:00 2001 From: uiharuayako <2451602772@qq.com> Date: Tue, 17 Nov 2026 16:37:12 +0800 Subject: [PATCH 1/3] fix(search): release cache lock before recovering unhealthy sessions Clone the cached session before probing daemon health so stale-session recovery can acquire the write lock. Add a real-daemon regression covering reopening and subsequent shutdown. --- .../src/workspace_search/service.rs | 53 ++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/src/crates/services/services-integrations/src/workspace_search/service.rs b/src/crates/services/services-integrations/src/workspace_search/service.rs index 52593dc9e3..d6ec26efcd 100644 --- a/src/crates/services/services-integrations/src/workspace_search/service.rs +++ b/src/crates/services/services-integrations/src/workspace_search/service.rs @@ -706,7 +706,9 @@ impl WorkspaceSearchService { }; let _repo_guard = repo_guard.lock().await; - if let Some(existing) = self.sessions.read().await.get(&repo_root).cloned() { + // Release the cache lock before checking daemon health or evicting a stale session. + let existing = self.sessions.read().await.get(&repo_root).cloned(); + if let Some(existing) = existing { existing.activity_epoch.fetch_add(1, Ordering::Relaxed); if existing.session.status().await.is_ok() { return Ok(existing.session); @@ -1463,6 +1465,55 @@ mod tests { use crate::workspace_search::flashgrep::SearchResults; use crate::workspace_search::{ContentSearchOutputMode, WorkspaceSearchRepoStatus}; + #[tokio::test] + #[ignore = "spawns the flashgrep daemon against a temporary repository"] + async fn unhealthy_cached_session_reopens_and_allows_shutdown() { + let directory = tempfile::tempdir().unwrap(); + let repo_root = directory.path(); + for args in [ + vec!["init", "--quiet"], + vec![ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.invalid", + "-c", + "commit.gpgsign=false", + "commit", + "--quiet", + "--allow-empty", + "-m", + "fixture", + ], + ] { + let output = openbitfun_services_core::process_manager::create_command("git") + .current_dir(repo_root) + .args(args) + .output() + .expect("git should be available"); + assert!(output.status.success(), "{output:?}"); + } + + let service = WorkspaceSearchService::new(); + let original = service.get_or_open_session(repo_root).await.unwrap(); + // Close only the backend session so the cache retains an unhealthy entry. + original.close().await.unwrap(); + + let reopened = tokio::time::timeout( + Duration::from_secs(5), + service.get_or_open_session(repo_root), + ) + .await + .expect("an unhealthy cached session must reopen without deadlocking") + .expect("the backend session should reopen"); + reopened.status().await.unwrap(); + + tokio::time::timeout(Duration::from_secs(5), service.shutdown_all_daemons()) + .await + .expect("shutdown must not be blocked by an unhealthy cached session"); + assert!(service.sessions.read().await.is_empty()); + } + fn empty_search_results() -> SearchResults { serde_json::from_value(serde_json::json!({ "candidate_docs": 0, From 170dc7fa81b5a145ed61c0a48948b164fa25880e Mon Sep 17 00:00:00 2001 From: uiharuayako <2451602772@qq.com> Date: Tue, 17 Nov 2026 16:37:24 +0800 Subject: [PATCH 2/3] fix(installer): preserve payload paths and underlying IO errors Attach file and directory context to extraction and copy failures and retain the full error chain at the command boundary. Cover real filesystem conflicts, legacy ZIP payloads, and Windows file sharing violations. --- .../src-tauri/src/installer/commands.rs | 8 +- .../src-tauri/src/installer/extract.rs | 164 ++++++++++++++++-- 2 files changed, 156 insertions(+), 16 deletions(-) diff --git a/OpenBitFun-Installer/src-tauri/src/installer/commands.rs b/OpenBitFun-Installer/src-tauri/src/installer/commands.rs index d1560d4573..2923482d75 100644 --- a/OpenBitFun-Installer/src-tauri/src/installer/commands.rs +++ b/OpenBitFun-Installer/src-tauri/src/installer/commands.rs @@ -995,7 +995,7 @@ async fn install_impl( // Step 1: Create target directory emit_progress(window.as_ref(), "prepare", 5, "Creating installation directory..."); std::fs::create_dir_all(&install_path) - .map_err(|e| format!("Failed to create directory: {}", e))?; + .map_err(|e| format!("Failed to create directory {}: {e}", install_path.display()))?; // Step 2: Extract / copy application files emit_progress(window.as_ref(), "extract", 15, "Extracting application files..."); @@ -1017,7 +1017,7 @@ async fn install_impl( &staging_path, should_install_payload_path, ) - .map_err(|e| format!("Embedded payload extraction failed: {}", e))?; + .map_err(|e| format!("Embedded payload extraction failed: {e:#}"))?; extracted = true; log::info!("Extracted payload from embedded installer archive"); } @@ -1046,7 +1046,7 @@ async fn install_impl( &staging_path, should_install_payload_path, ) - .map_err(|e| format!("Extraction failed from {}: {}", candidate.label, e))?; + .map_err(|e| format!("Extraction failed from {}: {e:#}", candidate.label))?; extracted = true; log::info!("Extracted payload from {}", candidate.label); break; @@ -1066,7 +1066,7 @@ async fn install_impl( &staging_path, should_install_payload_path, ) - .map_err(|e| format!("File copy failed from {}: {}", candidate.label, e))?; + .map_err(|e| format!("File copy failed from {}: {e:#}", candidate.label))?; extracted = true; log::info!("Copied payload from {}", candidate.label); break; diff --git a/OpenBitFun-Installer/src-tauri/src/installer/extract.rs b/OpenBitFun-Installer/src-tauri/src/installer/extract.rs index fd7e706e63..63b90ca578 100644 --- a/OpenBitFun-Installer/src-tauri/src/installer/extract.rs +++ b/OpenBitFun-Installer/src-tauri/src/installer/extract.rs @@ -47,13 +47,30 @@ fn extract_zip_archive( let out_path = target_dir.join(&rel_path); if file.is_dir() { - fs::create_dir_all(&out_path)?; + fs::create_dir_all(&out_path).with_context(|| { + format!( + "Failed to create installation directory: {}", + out_path.display() + ) + })?; } else { if let Some(parent) = out_path.parent() { - fs::create_dir_all(parent)?; + fs::create_dir_all(parent).with_context(|| { + format!( + "Failed to create installation directory: {}", + parent.display() + ) + })?; } - let mut outfile = fs::File::create(&out_path)?; - io::copy(&mut file, &mut outfile)?; + let mut outfile = fs::File::create(&out_path).with_context(|| { + format!("Failed to create installation file: {}", out_path.display()) + })?; + io::copy(&mut file, &mut outfile).with_context(|| { + format!( + "Failed to extract installation file: {}", + out_path.display() + ) + })?; } } @@ -78,12 +95,29 @@ fn copy_directory_internal( let mut bytes_copied: u64 = 0; if !target.exists() { - fs::create_dir_all(target)?; + fs::create_dir_all(target).with_context(|| { + format!( + "Failed to create installation directory: {}", + target.display() + ) + })?; } - for entry in fs::read_dir(source)? { - let entry = entry?; - let file_type = entry.file_type()?; + for entry in fs::read_dir(source) + .with_context(|| format!("Failed to read payload directory: {}", source.display()))? + { + let entry = entry.with_context(|| { + format!( + "Failed to read payload directory entry: {}", + source.display() + ) + })?; + let file_type = entry.file_type().with_context(|| { + format!( + "Failed to inspect payload entry: {}", + entry.path().display() + ) + })?; let name = entry.file_name(); let rel = relative_prefix.join(&name); let dest = target.join(&name); @@ -100,8 +134,19 @@ fn copy_directory_internal( if !should_copy_file(&rel) { continue; } - let size = entry.metadata()?.len(); - fs::copy(entry.path(), &dest)?; + let size = entry + .metadata() + .with_context(|| { + format!("Failed to inspect payload file: {}", entry.path().display()) + })? + .len(); + fs::copy(entry.path(), &dest).with_context(|| { + format!( + "Failed to copy payload file from {} to {}", + entry.path().display(), + dest.display() + ) + })?; bytes_copied += size; } } @@ -111,8 +156,103 @@ fn copy_directory_internal( #[cfg(test)] mod tests { - use super::{extract_zip_bytes_with_filter, extract_zip_with_filter}; - use std::{fs, path::Path}; + use super::{ + copy_directory_with_filter, extract_zip_bytes_with_filter, extract_zip_with_filter, + }; + use std::{fs, io, path::Path}; + + fn assert_io_diagnostic(error: anyhow::Error, path: &Path) { + let cause = error.downcast_ref::().unwrap(); + let os_error = cause.raw_os_error().unwrap(); + let message = format!("{error:#}"); + assert!(message.contains(&path.display().to_string()), "{message}"); + assert!(message.contains(&cause.to_string()), "{message}"); + assert!( + message.contains(&format!("os error {os_error}")), + "{message}" + ); + } + + #[test] + fn extraction_failure_preserves_target_path_and_os_error() { + let root = tempfile::tempdir().unwrap(); + let target = root.path().join("installed"); + let blocked_file = target.join("resources/readme.txt"); + fs::create_dir_all(&blocked_file).unwrap(); + + let error = extract_zip_bytes_with_filter( + include_bytes!("fixtures/legacy-payload-zip-0.6.6.zip"), + &target, + |path| path == Path::new("resources/readme.txt"), + ) + .unwrap_err(); + + assert_io_diagnostic(error, &blocked_file); + } + + #[test] + fn extraction_directory_failure_preserves_path_and_os_error() { + let root = tempfile::tempdir().unwrap(); + let target = root.path().join("installed"); + fs::create_dir(&target).unwrap(); + let blocked_directory = target.join("resources"); + fs::write(&blocked_directory, b"not a directory").unwrap(); + + let error = extract_zip_bytes_with_filter( + include_bytes!("fixtures/legacy-payload-zip-0.6.6.zip"), + &target, + |path| path == Path::new("resources/readme.txt"), + ) + .unwrap_err(); + + assert_io_diagnostic(error, &blocked_directory); + } + + #[test] + fn copy_failure_preserves_source_target_and_os_error() { + let root = tempfile::tempdir().unwrap(); + let source = root.path().join("payload"); + fs::create_dir(&source).unwrap(); + let source_file = source.join("application.exe"); + fs::write(&source_file, b"new application").unwrap(); + let target = root.path().join("installed"); + let blocked_file = target.join("application.exe"); + fs::create_dir_all(&blocked_file).unwrap(); + + let error = copy_directory_with_filter(&source, &target, |_| true).unwrap_err(); + assert!(format!("{error:#}").contains(&source_file.display().to_string())); + assert_io_diagnostic(error, &blocked_file); + } + + #[cfg(windows)] + #[test] + fn locked_installation_file_preserves_windows_error_code() { + use std::os::windows::fs::OpenOptionsExt; + + let root = tempfile::tempdir().unwrap(); + let target = root.path().join("installed"); + fs::create_dir_all(target.join("resources")).unwrap(); + let locked_file = target.join("resources/readme.txt"); + fs::write(&locked_file, b"old resource").unwrap(); + let _locked = fs::OpenOptions::new() + .read(true) + .share_mode(0) + .open(&locked_file) + .unwrap(); + + let error = extract_zip_bytes_with_filter( + include_bytes!("fixtures/legacy-payload-zip-0.6.6.zip"), + &target, + |path| path == Path::new("resources/readme.txt"), + ) + .unwrap_err(); + + assert_eq!( + error.downcast_ref::().unwrap().raw_os_error(), + Some(32) + ); + assert_io_diagnostic(error, &locked_file); + } #[test] fn reads_legacy_payload_from_file_and_embedded_bytes() { From 1fdf1a28b451edb0f86a7ee44ac135d049f78a68 Mon Sep 17 00:00:00 2001 From: kev1n77 Date: Thu, 19 Nov 2026 16:27:43 +0800 Subject: [PATCH 3/3] fix(search): mark cached sessions active before idle release Update the activity epoch while the cache read lock is held, and release the lock before daemon IO. Add a real-daemon regression for a pending idle release. AI-assisted. Verified on Windows with 30 workspace search unit tests and 6 contract tests, including ignored real-daemon cases. --- .../src/workspace_search/service.rs | 51 ++++++++++++++++--- 1 file changed, 45 insertions(+), 6 deletions(-) diff --git a/src/crates/services/services-integrations/src/workspace_search/service.rs b/src/crates/services/services-integrations/src/workspace_search/service.rs index d6ec26efcd..3e6978a269 100644 --- a/src/crates/services/services-integrations/src/workspace_search/service.rs +++ b/src/crates/services/services-integrations/src/workspace_search/service.rs @@ -692,6 +692,15 @@ impl WorkspaceSearchService { } } + async fn claim_cached_session(&self, repo_root: &Path) -> Option { + // Idle release checks the epoch under the write lock, so mark the entry + // active before releasing the read lock. + self.sessions.read().await.get(repo_root).map(|entry| { + entry.activity_epoch.fetch_add(1, Ordering::Relaxed); + entry.clone() + }) + } + async fn get_or_open_session( &self, repo_root: &Path, @@ -707,9 +716,7 @@ impl WorkspaceSearchService { let _repo_guard = repo_guard.lock().await; // Release the cache lock before checking daemon health or evicting a stale session. - let existing = self.sessions.read().await.get(&repo_root).cloned(); - if let Some(existing) = existing { - existing.activity_epoch.fetch_add(1, Ordering::Relaxed); + if let Some(existing) = self.claim_cached_session(&repo_root).await { if existing.session.status().await.is_ok() { return Ok(existing.session); } @@ -1465,9 +1472,7 @@ mod tests { use crate::workspace_search::flashgrep::SearchResults; use crate::workspace_search::{ContentSearchOutputMode, WorkspaceSearchRepoStatus}; - #[tokio::test] - #[ignore = "spawns the flashgrep daemon against a temporary repository"] - async fn unhealthy_cached_session_reopens_and_allows_shutdown() { + fn init_search_test_repo() -> tempfile::TempDir { let directory = tempfile::tempdir().unwrap(); let repo_root = directory.path(); for args in [ @@ -1494,6 +1499,14 @@ mod tests { assert!(output.status.success(), "{output:?}"); } + directory + } + + #[tokio::test] + #[ignore = "spawns the flashgrep daemon against a temporary repository"] + async fn unhealthy_cached_session_reopens_and_allows_shutdown() { + let directory = init_search_test_repo(); + let repo_root = directory.path(); let service = WorkspaceSearchService::new(); let original = service.get_or_open_session(repo_root).await.unwrap(); // Close only the backend session so the cache retains an unhealthy entry. @@ -1514,6 +1527,32 @@ mod tests { assert!(service.sessions.read().await.is_empty()); } + #[tokio::test] + #[ignore = "spawns the flashgrep daemon against a temporary repository"] + async fn claiming_cached_session_prevents_pending_idle_release() { + let directory = init_search_test_repo(); + let repo_root = normalize_repo_root(directory.path()).unwrap(); + let service = Arc::new(WorkspaceSearchService::new()); + + tokio::time::timeout(Duration::from_secs(10), async { + let original = service.get_or_open_session(&repo_root).await.unwrap(); + let idle_epoch = service.sessions.read().await[&repo_root] + .activity_epoch + .load(Ordering::Relaxed); + + let claimed = service.claim_cached_session(&repo_root).await.unwrap(); + // A pending idle release can acquire the write lock as soon as the claim returns. + service.release_repo_if_idle(repo_root, idle_epoch).await; + let status = claimed.session.status().await; + service.shutdown_all_daemons().await; + + assert!(Arc::ptr_eq(&original, &claimed.session)); + status.expect("a pending idle release must leave the claimed session open"); + }) + .await + .expect("claiming and releasing a cached session must complete"); + } + fn empty_search_results() -> SearchResults { serde_json::from_value(serde_json::json!({ "candidate_docs": 0,