Skip to content

Commit 34e196f

Browse files
authored
Merge pull request #3974 from uiharuayako/codex/fix-workspace-search-recovery
fix: unblock search session recovery and preserve installer IO errors
2 parents 5a9ca6f + 1fdf1a2 commit 34e196f

3 files changed

Lines changed: 248 additions & 18 deletions

File tree

‎OpenBitFun-Installer/src-tauri/src/installer/commands.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -995,7 +995,7 @@ async fn install_impl(
995995
// Step 1: Create target directory
996996
emit_progress(window.as_ref(), "prepare", 5, "Creating installation directory...");
997997
std::fs::create_dir_all(&install_path)
998-
.map_err(|e| format!("Failed to create directory: {}", e))?;
998+
.map_err(|e| format!("Failed to create directory {}: {e}", install_path.display()))?;
999999

10001000
// Step 2: Extract / copy application files
10011001
emit_progress(window.as_ref(), "extract", 15, "Extracting application files...");
@@ -1017,7 +1017,7 @@ async fn install_impl(
10171017
&staging_path,
10181018
should_install_payload_path,
10191019
)
1020-
.map_err(|e| format!("Embedded payload extraction failed: {}", e))?;
1020+
.map_err(|e| format!("Embedded payload extraction failed: {e:#}"))?;
10211021
extracted = true;
10221022
log::info!("Extracted payload from embedded installer archive");
10231023
}
@@ -1046,7 +1046,7 @@ async fn install_impl(
10461046
&staging_path,
10471047
should_install_payload_path,
10481048
)
1049-
.map_err(|e| format!("Extraction failed from {}: {}", candidate.label, e))?;
1049+
.map_err(|e| format!("Extraction failed from {}: {e:#}", candidate.label))?;
10501050
extracted = true;
10511051
log::info!("Extracted payload from {}", candidate.label);
10521052
break;
@@ -1066,7 +1066,7 @@ async fn install_impl(
10661066
&staging_path,
10671067
should_install_payload_path,
10681068
)
1069-
.map_err(|e| format!("File copy failed from {}: {}", candidate.label, e))?;
1069+
.map_err(|e| format!("File copy failed from {}: {e:#}", candidate.label))?;
10701070
extracted = true;
10711071
log::info!("Copied payload from {}", candidate.label);
10721072
break;

‎OpenBitFun-Installer/src-tauri/src/installer/extract.rs‎

Lines changed: 152 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -47,13 +47,30 @@ fn extract_zip_archive<R: io::Read + io::Seek>(
4747
let out_path = target_dir.join(&rel_path);
4848

4949
if file.is_dir() {
50-
fs::create_dir_all(&out_path)?;
50+
fs::create_dir_all(&out_path).with_context(|| {
51+
format!(
52+
"Failed to create installation directory: {}",
53+
out_path.display()
54+
)
55+
})?;
5156
} else {
5257
if let Some(parent) = out_path.parent() {
53-
fs::create_dir_all(parent)?;
58+
fs::create_dir_all(parent).with_context(|| {
59+
format!(
60+
"Failed to create installation directory: {}",
61+
parent.display()
62+
)
63+
})?;
5464
}
55-
let mut outfile = fs::File::create(&out_path)?;
56-
io::copy(&mut file, &mut outfile)?;
65+
let mut outfile = fs::File::create(&out_path).with_context(|| {
66+
format!("Failed to create installation file: {}", out_path.display())
67+
})?;
68+
io::copy(&mut file, &mut outfile).with_context(|| {
69+
format!(
70+
"Failed to extract installation file: {}",
71+
out_path.display()
72+
)
73+
})?;
5774
}
5875
}
5976

@@ -78,12 +95,29 @@ fn copy_directory_internal(
7895
let mut bytes_copied: u64 = 0;
7996

8097
if !target.exists() {
81-
fs::create_dir_all(target)?;
98+
fs::create_dir_all(target).with_context(|| {
99+
format!(
100+
"Failed to create installation directory: {}",
101+
target.display()
102+
)
103+
})?;
82104
}
83105

84-
for entry in fs::read_dir(source)? {
85-
let entry = entry?;
86-
let file_type = entry.file_type()?;
106+
for entry in fs::read_dir(source)
107+
.with_context(|| format!("Failed to read payload directory: {}", source.display()))?
108+
{
109+
let entry = entry.with_context(|| {
110+
format!(
111+
"Failed to read payload directory entry: {}",
112+
source.display()
113+
)
114+
})?;
115+
let file_type = entry.file_type().with_context(|| {
116+
format!(
117+
"Failed to inspect payload entry: {}",
118+
entry.path().display()
119+
)
120+
})?;
87121
let name = entry.file_name();
88122
let rel = relative_prefix.join(&name);
89123
let dest = target.join(&name);
@@ -100,8 +134,19 @@ fn copy_directory_internal(
100134
if !should_copy_file(&rel) {
101135
continue;
102136
}
103-
let size = entry.metadata()?.len();
104-
fs::copy(entry.path(), &dest)?;
137+
let size = entry
138+
.metadata()
139+
.with_context(|| {
140+
format!("Failed to inspect payload file: {}", entry.path().display())
141+
})?
142+
.len();
143+
fs::copy(entry.path(), &dest).with_context(|| {
144+
format!(
145+
"Failed to copy payload file from {} to {}",
146+
entry.path().display(),
147+
dest.display()
148+
)
149+
})?;
105150
bytes_copied += size;
106151
}
107152
}
@@ -111,8 +156,103 @@ fn copy_directory_internal(
111156

112157
#[cfg(test)]
113158
mod tests {
114-
use super::{extract_zip_bytes_with_filter, extract_zip_with_filter};
115-
use std::{fs, path::Path};
159+
use super::{
160+
copy_directory_with_filter, extract_zip_bytes_with_filter, extract_zip_with_filter,
161+
};
162+
use std::{fs, io, path::Path};
163+
164+
fn assert_io_diagnostic(error: anyhow::Error, path: &Path) {
165+
let cause = error.downcast_ref::<io::Error>().unwrap();
166+
let os_error = cause.raw_os_error().unwrap();
167+
let message = format!("{error:#}");
168+
assert!(message.contains(&path.display().to_string()), "{message}");
169+
assert!(message.contains(&cause.to_string()), "{message}");
170+
assert!(
171+
message.contains(&format!("os error {os_error}")),
172+
"{message}"
173+
);
174+
}
175+
176+
#[test]
177+
fn extraction_failure_preserves_target_path_and_os_error() {
178+
let root = tempfile::tempdir().unwrap();
179+
let target = root.path().join("installed");
180+
let blocked_file = target.join("resources/readme.txt");
181+
fs::create_dir_all(&blocked_file).unwrap();
182+
183+
let error = extract_zip_bytes_with_filter(
184+
include_bytes!("fixtures/legacy-payload-zip-0.6.6.zip"),
185+
&target,
186+
|path| path == Path::new("resources/readme.txt"),
187+
)
188+
.unwrap_err();
189+
190+
assert_io_diagnostic(error, &blocked_file);
191+
}
192+
193+
#[test]
194+
fn extraction_directory_failure_preserves_path_and_os_error() {
195+
let root = tempfile::tempdir().unwrap();
196+
let target = root.path().join("installed");
197+
fs::create_dir(&target).unwrap();
198+
let blocked_directory = target.join("resources");
199+
fs::write(&blocked_directory, b"not a directory").unwrap();
200+
201+
let error = extract_zip_bytes_with_filter(
202+
include_bytes!("fixtures/legacy-payload-zip-0.6.6.zip"),
203+
&target,
204+
|path| path == Path::new("resources/readme.txt"),
205+
)
206+
.unwrap_err();
207+
208+
assert_io_diagnostic(error, &blocked_directory);
209+
}
210+
211+
#[test]
212+
fn copy_failure_preserves_source_target_and_os_error() {
213+
let root = tempfile::tempdir().unwrap();
214+
let source = root.path().join("payload");
215+
fs::create_dir(&source).unwrap();
216+
let source_file = source.join("application.exe");
217+
fs::write(&source_file, b"new application").unwrap();
218+
let target = root.path().join("installed");
219+
let blocked_file = target.join("application.exe");
220+
fs::create_dir_all(&blocked_file).unwrap();
221+
222+
let error = copy_directory_with_filter(&source, &target, |_| true).unwrap_err();
223+
assert!(format!("{error:#}").contains(&source_file.display().to_string()));
224+
assert_io_diagnostic(error, &blocked_file);
225+
}
226+
227+
#[cfg(windows)]
228+
#[test]
229+
fn locked_installation_file_preserves_windows_error_code() {
230+
use std::os::windows::fs::OpenOptionsExt;
231+
232+
let root = tempfile::tempdir().unwrap();
233+
let target = root.path().join("installed");
234+
fs::create_dir_all(target.join("resources")).unwrap();
235+
let locked_file = target.join("resources/readme.txt");
236+
fs::write(&locked_file, b"old resource").unwrap();
237+
let _locked = fs::OpenOptions::new()
238+
.read(true)
239+
.share_mode(0)
240+
.open(&locked_file)
241+
.unwrap();
242+
243+
let error = extract_zip_bytes_with_filter(
244+
include_bytes!("fixtures/legacy-payload-zip-0.6.6.zip"),
245+
&target,
246+
|path| path == Path::new("resources/readme.txt"),
247+
)
248+
.unwrap_err();
249+
250+
assert_eq!(
251+
error.downcast_ref::<io::Error>().unwrap().raw_os_error(),
252+
Some(32)
253+
);
254+
assert_io_diagnostic(error, &locked_file);
255+
}
116256

117257
#[test]
118258
fn reads_legacy_payload_from_file_and_embedded_bytes() {

‎src/crates/services/services-integrations/src/workspace_search/service.rs‎

Lines changed: 92 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -692,6 +692,15 @@ impl WorkspaceSearchService {
692692
}
693693
}
694694

695+
async fn claim_cached_session(&self, repo_root: &Path) -> Option<SessionEntry> {
696+
// Idle release checks the epoch under the write lock, so mark the entry
697+
// active before releasing the read lock.
698+
self.sessions.read().await.get(repo_root).map(|entry| {
699+
entry.activity_epoch.fetch_add(1, Ordering::Relaxed);
700+
entry.clone()
701+
})
702+
}
703+
695704
async fn get_or_open_session(
696705
&self,
697706
repo_root: &Path,
@@ -706,8 +715,8 @@ impl WorkspaceSearchService {
706715
};
707716
let _repo_guard = repo_guard.lock().await;
708717

709-
if let Some(existing) = self.sessions.read().await.get(&repo_root).cloned() {
710-
existing.activity_epoch.fetch_add(1, Ordering::Relaxed);
718+
// Release the cache lock before checking daemon health or evicting a stale session.
719+
if let Some(existing) = self.claim_cached_session(&repo_root).await {
711720
if existing.session.status().await.is_ok() {
712721
return Ok(existing.session);
713722
}
@@ -1463,6 +1472,87 @@ mod tests {
14631472
use crate::workspace_search::flashgrep::SearchResults;
14641473
use crate::workspace_search::{ContentSearchOutputMode, WorkspaceSearchRepoStatus};
14651474

1475+
fn init_search_test_repo() -> tempfile::TempDir {
1476+
let directory = tempfile::tempdir().unwrap();
1477+
let repo_root = directory.path();
1478+
for args in [
1479+
vec!["init", "--quiet"],
1480+
vec![
1481+
"-c",
1482+
"user.name=Test",
1483+
"-c",
1484+
"user.email=test@example.invalid",
1485+
"-c",
1486+
"commit.gpgsign=false",
1487+
"commit",
1488+
"--quiet",
1489+
"--allow-empty",
1490+
"-m",
1491+
"fixture",
1492+
],
1493+
] {
1494+
let output = openbitfun_services_core::process_manager::create_command("git")
1495+
.current_dir(repo_root)
1496+
.args(args)
1497+
.output()
1498+
.expect("git should be available");
1499+
assert!(output.status.success(), "{output:?}");
1500+
}
1501+
1502+
directory
1503+
}
1504+
1505+
#[tokio::test]
1506+
#[ignore = "spawns the flashgrep daemon against a temporary repository"]
1507+
async fn unhealthy_cached_session_reopens_and_allows_shutdown() {
1508+
let directory = init_search_test_repo();
1509+
let repo_root = directory.path();
1510+
let service = WorkspaceSearchService::new();
1511+
let original = service.get_or_open_session(repo_root).await.unwrap();
1512+
// Close only the backend session so the cache retains an unhealthy entry.
1513+
original.close().await.unwrap();
1514+
1515+
let reopened = tokio::time::timeout(
1516+
Duration::from_secs(5),
1517+
service.get_or_open_session(repo_root),
1518+
)
1519+
.await
1520+
.expect("an unhealthy cached session must reopen without deadlocking")
1521+
.expect("the backend session should reopen");
1522+
reopened.status().await.unwrap();
1523+
1524+
tokio::time::timeout(Duration::from_secs(5), service.shutdown_all_daemons())
1525+
.await
1526+
.expect("shutdown must not be blocked by an unhealthy cached session");
1527+
assert!(service.sessions.read().await.is_empty());
1528+
}
1529+
1530+
#[tokio::test]
1531+
#[ignore = "spawns the flashgrep daemon against a temporary repository"]
1532+
async fn claiming_cached_session_prevents_pending_idle_release() {
1533+
let directory = init_search_test_repo();
1534+
let repo_root = normalize_repo_root(directory.path()).unwrap();
1535+
let service = Arc::new(WorkspaceSearchService::new());
1536+
1537+
tokio::time::timeout(Duration::from_secs(10), async {
1538+
let original = service.get_or_open_session(&repo_root).await.unwrap();
1539+
let idle_epoch = service.sessions.read().await[&repo_root]
1540+
.activity_epoch
1541+
.load(Ordering::Relaxed);
1542+
1543+
let claimed = service.claim_cached_session(&repo_root).await.unwrap();
1544+
// A pending idle release can acquire the write lock as soon as the claim returns.
1545+
service.release_repo_if_idle(repo_root, idle_epoch).await;
1546+
let status = claimed.session.status().await;
1547+
service.shutdown_all_daemons().await;
1548+
1549+
assert!(Arc::ptr_eq(&original, &claimed.session));
1550+
status.expect("a pending idle release must leave the claimed session open");
1551+
})
1552+
.await
1553+
.expect("claiming and releasing a cached session must complete");
1554+
}
1555+
14661556
fn empty_search_results() -> SearchResults {
14671557
serde_json::from_value(serde_json::json!({
14681558
"candidate_docs": 0,

0 commit comments

Comments
 (0)