Skip to content

Commit 34750ff

Browse files
committed
fix(mounts): preserve shared directories across branch changes
Flush shared mounts before changing revisions, supervise GeeseFS startup and preserve other mounted directories when switching the selected desktop. Handle shutdown during restore and verify readiness after restarting the daemon.
1 parent 2c56872 commit 34750ff

8 files changed

Lines changed: 131 additions & 41 deletions

File tree

‎apps/agentdrived/src/main.rs‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,11 @@ async fn serve(
108108
runtime: tokio::runtime::Handle::current(),
109109
}))?;
110110
let cancellation = CancellationToken::new();
111+
let shutdown = cancellation.clone();
112+
let signal = tokio::spawn(async move {
113+
shutdown_signal().await;
114+
shutdown.cancel();
115+
});
111116
let listener = tokio::net::TcpListener::bind(config.listen).await?;
112117
let address = listener.local_addr()?;
113118
let services = engine.services.clone();
@@ -277,11 +282,6 @@ async fn serve(
277282
}
278283
});
279284
}
280-
let shutdown = cancellation.clone();
281-
let signal = tokio::spawn(async move {
282-
shutdown_signal().await;
283-
shutdown.cancel();
284-
});
285285
let server_result = tokio::select! {
286286
result = axum::serve(listener, app)
287287
.with_graceful_shutdown(cancellation.clone().cancelled_owned())
@@ -311,6 +311,19 @@ async fn serve(
311311
}
312312
}
313313
}
314+
#[cfg(windows)]
315+
loop {
316+
match engine.suspend_native_mounts().await {
317+
Err(error) if error.code == ErrorCode::MountBusy => {
318+
tokio::time::sleep(Duration::from_secs(1)).await
319+
}
320+
result => {
321+
result?;
322+
break;
323+
}
324+
}
325+
}
326+
#[cfg(not(windows))]
314327
engine.suspend_native_mounts().await?;
315328
engine.flush_local().await?;
316329
drop(s3_guard);

‎crates/agentdrive-engine/src/mounts.rs‎

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,7 @@ impl MountService {
312312
"old mount generation changed",
313313
));
314314
}
315-
if self.files.open_handles(old.id) != 0 {
315+
if !self.supports_shared_writable_mounts() && self.files.open_handles(old.id) != 0 {
316316
return Err(Error::new(
317317
ErrorCode::MountBusy,
318318
"close open file handles before releasing the mount",
@@ -684,7 +684,9 @@ impl MountService {
684684
) -> Result<OperationRecord> {
685685
let _gate = self.runtime.lock_branch(target.branch).await;
686686
self.runtime.check_mutation(target.branch)?;
687-
self.runtime.check_sandbox(target.branch)?;
687+
if !self.supports_shared_writable_mounts() {
688+
self.runtime.check_sandbox(target.branch)?;
689+
}
688690
let _protection = self.runtime.objects.read().await;
689691
let branch = self.runtime.branch(target.branch).await?;
690692
check_guard(&branch, &target)?;
@@ -1467,10 +1469,31 @@ impl RevisionTransition for MountService {
14671469
{
14681470
return Ok(current);
14691471
}
1472+
let mounts = self.runtime.state.mounts().await?;
1473+
let live: Vec<_> = mounts
1474+
.into_iter()
1475+
.filter(|m| {
1476+
m.branch == target.branch
1477+
&& m.access == AccessMode::ReadWrite
1478+
&& m.state != MountState::Released
1479+
})
1480+
.collect();
1481+
// Shared clients keep their branch alias through a restore or merge. Flush
1482+
// before taking the branch lock because GeeseFS writes through the gateway.
1483+
let mount = if self.supports_shared_writable_mounts() {
1484+
for binding in live.iter().filter(|m| m.state == MountState::Ready) {
1485+
self.driver.flush(binding).await?;
1486+
}
1487+
None
1488+
} else {
1489+
live.into_iter().next()
1490+
};
14701491
let record = {
14711492
let _gate = self.runtime.lock_branch(target.branch).await;
14721493
self.runtime.check_mutation(target.branch)?;
1473-
self.runtime.check_sandbox(target.branch)?;
1494+
if !self.supports_shared_writable_mounts() {
1495+
self.runtime.check_sandbox(target.branch)?;
1496+
}
14741497
let branch = self.runtime.branch(target.branch).await?;
14751498
check_guard(&branch, &target)?;
14761499
self.revisions
@@ -1480,17 +1503,6 @@ impl RevisionTransition for MountService {
14801503
if merge.is_none() {
14811504
branch.check_write(self.runtime.location, target.authority_epoch)?;
14821505
}
1483-
let mount = self
1484-
.runtime
1485-
.state
1486-
.mounts()
1487-
.await?
1488-
.into_iter()
1489-
.find(|mount| {
1490-
mount.branch == target.branch
1491-
&& mount.access == AccessMode::ReadWrite
1492-
&& mount.state != MountState::Released
1493-
});
14941506
let mut record = current;
14951507
record.error = None;
14961508
record.pending = Some(PendingAction::ApplyRevision {

‎crates/agentdrive-engine/src/revisions.rs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,7 +299,30 @@ impl RevisionService {
299299
.publisher
300300
.build_job(&branch, revision.as_ref(), &operation)
301301
.await?;
302+
let mounts = if replacing {
303+
self.runtime
304+
.state
305+
.mounts()
306+
.await?
307+
.into_iter()
308+
.filter_map(|mut mount| {
309+
if mount.branch == branch.id
310+
&& mount.revision.is_none()
311+
&& mount.access == AccessMode::ReadWrite
312+
&& mount.state != MountState::Released
313+
{
314+
mount.branch_generation = Some(branch.generation);
315+
Some(mount)
316+
} else {
317+
None
318+
}
319+
})
320+
.collect()
321+
} else {
322+
Vec::new()
323+
};
302324
let commit = LocalCommit {
325+
mounts,
303326
guards: vec![request.guard],
304327
branches: vec![branch.clone()],
305328
revisions: revision.into_iter().collect(),

‎crates/agentdrive-engine/tests/workflows.rs‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2224,9 +2224,7 @@ async fn concurrent_mounts_reuse_location_branch_and_mount() {
22242224
)
22252225
.await
22262226
.unwrap();
2227-
let second = mounted(other_path);
2228-
assert_ne!(second.id, binding.id);
2229-
assert!(!second.follows_selection);
2227+
assert_eq!(other_path.error.unwrap().code, ErrorCode::MountBusy);
22302228
success(
22312229
harness
22322230
.engine

‎crates/agentdrive-mcp/src/sandbox_tests.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -869,6 +869,9 @@ async fn sandbox_reconciliation_does_not_release_a_restarting_branch() {
869869
#[tokio::test]
870870
async fn desktop_switch_preserves_running_guest_branch_and_mount() {
871871
let f = fixture().await;
872+
f.mounts
873+
.shared_mounts
874+
.store(true, std::sync::atomic::Ordering::SeqCst);
872875
let server = crate::McpServer::new(f.engine.services.clone(), f.owner.clone());
873876
let desktop = f._directory.path().join("desktop");
874877
let prepared = server

‎crates/agentdrive-platform/src/geesefs.rs‎

Lines changed: 56 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,16 @@ struct Gateway {
1414
client: reqwest::Client,
1515
}
1616

17+
/// Until the kernel reports a mount, cancellation must also stop helper processes.
18+
struct MountStartup(Option<rustix::process::Pid>);
19+
impl Drop for MountStartup {
20+
fn drop(&mut self) {
21+
if let Some(pid) = self.0 {
22+
let _ = rustix::process::kill_process_group(pid, rustix::process::Signal::KILL);
23+
}
24+
}
25+
}
26+
1727
fn alias(binding: &MountBinding) -> String {
1828
format!("drive-{}-{:x}", binding.id, binding.generation)
1929
}
@@ -97,24 +107,52 @@ impl Driver {
97107
if binding.access == AccessMode::ReadOnly {
98108
command.args(["-o", "ro"]);
99109
}
100-
// GeeseFS's parent exits after the child has mounted the directory.
101-
let output = command
110+
// Keep the helper and its mounting subprocess in a private process group.
111+
// A denied macFUSE activation can leave both processes waiting indefinitely.
112+
let mut child = command
113+
.arg("-f")
102114
.arg(&bucket)
103115
.arg(&binding.path)
104116
.stdin(Stdio::null())
105-
.output()
106-
.await
117+
.process_group(0)
118+
.spawn()
107119
.map_err(|e| Error::new(ErrorCode::Io, format!("start geesefs: {e}")))?;
108-
if !output.status.success() {
109-
return Err(Error::new(
110-
ErrorCode::Io,
111-
format!(
112-
"GeeseFS mount failed ({}): {}",
113-
output.status,
114-
String::from_utf8_lossy(&output.stderr).trim()
115-
),
116-
));
120+
let mut group = MountStartup(
121+
child
122+
.id()
123+
.and_then(|id| rustix::process::Pid::from_raw(id as i32)),
124+
);
125+
let startup = tokio::time::timeout(Duration::from_secs(20), async {
126+
loop {
127+
if let Some(status) = child.try_wait()? {
128+
return Err(Error::new(ErrorCode::Io, format!("GeeseFS exited before mounting (status {status}); check the FUSE driver and daemon log")));
129+
}
130+
if mount_source(&binding.path)?.as_deref() == Some(bucket.as_str()) {
131+
return Ok(());
132+
}
133+
tokio::time::sleep(Duration::from_millis(50)).await;
134+
}
135+
}).await.unwrap_or_else(|_| Err(Error::new(ErrorCode::Unavailable,
136+
"GeeseFS mount timed out; check the system FUSE driver, mount permissions and daemon log")));
137+
if let Err(error) = startup {
138+
if child.id().is_none() {
139+
group.0 = None;
140+
}
141+
drop(group);
142+
let _ = child.wait().await;
143+
if mount_source(&binding.path)?.as_deref() == Some(bucket.as_str()) {
144+
detach(&binding.path).await?;
145+
}
146+
return Err(error);
117147
}
148+
group.0 = None;
149+
tokio::spawn(async move {
150+
if let Ok(status) = child.wait().await
151+
&& !status.success()
152+
{
153+
tracing::warn!(%bucket, %status, "GeeseFS stopped");
154+
}
155+
});
118156
Ok(())
119157
}
120158

@@ -143,9 +181,11 @@ impl Driver {
143181
));
144182
}
145183
let path = binding.path.clone();
146-
tokio::task::spawn_blocking(move || std::fs::File::open(path)?.sync_all())
147-
.await
148-
.map_err(|e| Error::new(ErrorCode::Io, e.to_string()))??;
184+
tokio::task::spawn_blocking(move || -> std::io::Result<()> {
185+
Ok(rustix::fs::fsync(std::fs::File::open(path)?)?)
186+
})
187+
.await
188+
.map_err(|e| Error::new(ErrorCode::Io, e.to_string()))??;
149189
Ok(())
150190
}
151191

‎crates/agentdrive-test-support/src/lib.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,7 @@ impl RemoteRefStore for MemoryRemote {
223223

224224
#[derive(Debug, Default)]
225225
pub struct MemoryMountDriver {
226+
pub shared_mounts: AtomicBool,
226227
mounts: Mutex<BTreeMap<MountId, MountBinding>>,
227228
pub fail_mount: AtomicBool,
228229
pub unmount_error: Mutex<Option<Error>>,
@@ -252,7 +253,7 @@ impl MemoryMountDriver {
252253
#[async_trait]
253254
impl MountDriver for MemoryMountDriver {
254255
fn supports_shared_writable_mounts(&self) -> bool {
255-
true
256+
self.shared_mounts.load(Ordering::SeqCst)
256257
}
257258

258259
fn supports_automatic_collaboration(&self) -> bool {

‎tests/drive_s3_smoke.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ def start(directory):
130130
if process.poll() is not None:
131131
raise RuntimeError(f"server exited with {process.returncode}")
132132
try:
133-
with socket.create_connection(("127.0.0.1", admin_port), timeout=.3):
133+
with urllib.request.urlopen(ui + "/api/workspaces", timeout=1):
134134
return process
135135
except OSError:
136136
time.sleep(.05)
@@ -142,7 +142,7 @@ def start(directory):
142142

143143
def stop(process):
144144
process.terminate()
145-
process.wait(timeout=10)
145+
assert process.wait(timeout=30) == 0
146146

147147
def post(path, **fields):
148148
req = urllib.request.Request(ui + path, json.dumps(fields).encode(), {"Content-Type": "application/json"})

0 commit comments

Comments
 (0)