Skip to content

A full-featured download manager.

fix(finalize): bound rename retries and report durable completion (#2265)

Dr_rOot221a983c9fe9
diff --git a/packages/finalize-fs/README.md b/packages/finalize-fs/README.md
index 11e7f76a..8da29947 100644
--- a/packages/finalize-fs/README.md
+++ b/packages/finalize-fs/README.md
@@ -210,3 +210,31 @@ NTFS. The Linux recovery suite also covers a lost isolation response followed
by restart with 0755 permissions, and preservation of both hard links when
0777 permissions make cleanup unsafe. Windows uses its existing handle-based
removal and SMB flush policy; these Unix permission checks do not apply there.
+
+## Rename completion and retries
+
+Rename responses add `stage`, `mutation`, and `directory_sync_mode`. On success,
+`mutation` is `applied` and both changed parent directories have been synced.
+Parents with the same held filesystem identity are synced once. The host skips
+its duplicate directory syncs only when the sidecar returns a sync mode; older
+sidecars retain the caller-owned fallback. File-content sync and journal
+checkpoints remain separate requirements.
+
+Failures before the syscall use `not_attempted`, syscall failures use the
+conservative `unknown`, and post-rename verification or sync failures use
+`applied`. A lost process response is also `unknown`. These fields are diagnostic:
+recovery must still inspect both names and their identities before deciding
+what to do. They do not authorize replaying an operation or skipping recovery.
+`remote_acknowledged` retains the weaker SMB acknowledgement contract and must
+not be described as a completed directory flush.
+
+On Windows, rename-only admission and rename share four possible waits of
+50, 100, 200, and 400 milliseconds. Only errors 5, 32, and 33 retry. Error 5
+is ambiguous and can be a permanent ACL denial; bounded retries never alter
+permissions or relax handle sharing. Exhaustion reports the failing stage,
+attempt count for that stage, OS code, and original NTSTATUS. The wait budget
+does not bound time spent inside a blocking filesystem call.
+
+Directory case-sensitivity queries fall back only on recognized unsupported
+information-class errors. Permission, sharing, transport, and I/O failures are
+propagated instead of silently switching to case-insensitive lookup.
diff --git a/packages/finalize-fs/src/error.rs b/packages/finalize-fs/src/error.rs
index 8738f004..b4fe346a 100644
--- a/packages/finalize-fs/src/error.rs
+++ b/packages/finalize-fs/src/error.rs
@@ -1,6 +1,7 @@
use std::io;
pub(crate) fn classify_error(error: &io::Error) -> &'static str {
+ let error = underlying(error);
if let Some(code) = error
.get_ref()
.and_then(|e| e.downcast_ref::<NativeError>())
@@ -72,6 +73,7 @@ pub(crate) fn native_error(
}
pub(crate) fn os_code(error: &io::Error) -> Option<i32> {
+ let error = underlying(error);
error.raw_os_error().or_else(|| {
error
.get_ref()?
@@ -82,6 +84,7 @@ pub(crate) fn os_code(error: &io::Error) -> Option<i32> {
}
pub(crate) fn nt_status(error: &io::Error) -> Option<String> {
+ let error = underlying(error);
error
.get_ref()?
.downcast_ref::<NativeError>()?
@@ -137,3 +140,51 @@ mod rename_tests {
);
}
}
+
+#[derive(Debug)]
+pub(crate) struct OperationError {
+ pub(crate) stage: &'static str,
+ // "unknown" includes syscall errors whose remote outcome cannot be inferred.
+ pub(crate) mutation: &'static str,
+ pub(crate) attempts: Option<usize>,
+ source: io::Error,
+}
+
+impl std::fmt::Display for OperationError {
+ fn fmt(&self, output: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(output, "{}: {}", self.stage, self.source)
+ }
+}
+impl std::error::Error for OperationError {
+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
+ Some(&self.source)
+ }
+}
+
+pub(crate) fn operation_error(
+ source: io::Error,
+ stage: &'static str,
+ mutation: &'static str,
+ attempts: Option<usize>,
+) -> io::Error {
+ io::Error::new(
+ source.kind(),
+ OperationError {
+ stage,
+ mutation,
+ attempts,
+ source,
+ },
+ )
+}
+
+pub(crate) fn operation_context(error: &io::Error) -> Option<&OperationError> {
+ error.get_ref()?.downcast_ref::<OperationError>()
+}
+
+fn underlying(mut error: &io::Error) -> &io::Error {
+ while let Some(context) = operation_context(error) {
+ error = &context.source;
+ }
+ error
+}
diff --git a/packages/finalize-fs/src/main.rs b/packages/finalize-fs/src/main.rs
index 6356b1de..51b09714 100644
--- a/packages/finalize-fs/src/main.rs
+++ b/packages/finalize-fs/src/main.rs
@@ -4,6 +4,7 @@ mod error;
mod path;
mod platform;
mod protocol;
+mod rename;
mod sanitize;
mod state;
diff --git a/packages/finalize-fs/src/platform/unix/rename.rs b/packages/finalize-fs/src/platform/unix/rename.rs
index 8a18deed..3a354cef 100644
--- a/packages/finalize-fs/src/platform/unix/rename.rs
+++ b/packages/finalize-fs/src/platform/unix/rename.rs
@@ -1,5 +1,7 @@
use super::{ArtifactHandle, RootHandle, assert_opened_artifact, open_parent};
+use crate::error::operation_error;
use crate::path::validate_relative;
+use crate::rename::{RenameOutcome, sync_parents};
use std::ffi::CString;
use std::io;
use std::os::fd::AsRawFd;
@@ -9,21 +11,27 @@ pub(crate) fn rename_opened_no_replace(
artifact: &ArtifactHandle,
target: &RootHandle,
target_relative: &str,
-) -> io::Result<()> {
- let target_parts = validate_relative(target_relative)?;
- let target_parent = open_parent(target.0.as_raw_fd(), &target_parts)?;
- let target_name =
- CString::new(*target_parts.last().expect("nonempty")).expect("validated component");
- assert_opened_artifact(artifact, artifact.parent.as_raw_fd(), &artifact.name)?;
- if super::metadata::artifact_stamp(&super::metadata::stat_opened(
- artifact.artifact.as_raw_fd(),
- )?) != artifact.opened_stamp
- {
- return Err(io::Error::new(
- io::ErrorKind::InvalidData,
- "opened artifact changed before rename",
- ));
- }
+) -> io::Result<RenameOutcome> {
+ let (target_parent, target_name, same_parent) = (|| {
+ let target_parts = validate_relative(target_relative)?;
+ let target_parent = open_parent(target.0.as_raw_fd(), &target_parts)?;
+ let target_name =
+ CString::new(*target_parts.last().expect("nonempty")).expect("validated component");
+ assert_opened_artifact(artifact, artifact.parent.as_raw_fd(), &artifact.name)?;
+ if super::metadata::artifact_stamp(&super::metadata::stat_opened(
+ artifact.artifact.as_raw_fd(),
+ )?) != artifact.opened_stamp
+ {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "opened artifact changed before rename",
+ ));
+ }
+
+ let same_parent = same_directory(&artifact.parent, &target_parent)?;
+ Ok((target_parent, target_name, same_parent))
+ })()
+ .map_err(|e| operation_error(e, "validate_source", "not_attempted", None))?;
rustix::fs::renameat_with(
&artifact.parent,
@@ -38,13 +46,11 @@ pub(crate) fn rename_opened_no_replace(
super::metadata::stat_opened(artifact.artifact.as_raw_fd())
.is_ok_and(|stat| stat.st_mode & libc::S_IFMT == libc::S_IFREG),
)
- })?;
- assert_opened_artifact(artifact, target_parent.as_raw_fd(), &target_name)?;
- rustix::fs::fsync(&target_parent)
- .map_err(|e| crate::error::native_error(e.into(), "fsync(rename_target_parent)", None))?;
- rustix::fs::fsync(&artifact.parent)
- .map_err(|e| crate::error::native_error(e.into(), "fsync(rename_source_parent)", None))?;
- Ok(())
+ })
+ .map_err(|e| operation_error(e, "rename", "unknown", Some(1)))?;
+ assert_opened_artifact(artifact, target_parent.as_raw_fd(), &target_name)
+ .map_err(|e| operation_error(e, "verify_target", "applied", None))?;
+ sync_directories(&artifact.parent, &target_parent, same_parent)
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
@@ -52,7 +58,7 @@ pub(crate) fn rename_opened_no_replace(
_artifact: &ArtifactHandle,
_target: &RootHandle,
target_relative: &str,
-) -> io::Result<()> {
+) -> io::Result<RenameOutcome> {
validate_relative(target_relative)?;
Err(io::Error::new(
io::ErrorKind::Unsupported,
@@ -66,15 +72,27 @@ pub(crate) fn rename_no_replace(
source_relative: &str,
target: &RootHandle,
target_relative: &str,
-) -> io::Result<()> {
- let source_parts = validate_relative(source_relative)?;
- let target_parts = validate_relative(target_relative)?;
- let source_parent = open_parent(source.0.as_raw_fd(), &source_parts)?;
- let target_parent = open_parent(target.0.as_raw_fd(), &target_parts)?;
- let source_name =
- CString::new(*source_parts.last().expect("nonempty")).expect("validated component");
- let target_name =
- CString::new(*target_parts.last().expect("nonempty")).expect("validated component");
+) -> io::Result<RenameOutcome> {
+ let (source_parent, source_name, target_parent, target_name, same_parent) = (|| {
+ let source_parts = validate_relative(source_relative)?;
+ let target_parts = validate_relative(target_relative)?;
+ let source_parent = open_parent(source.0.as_raw_fd(), &source_parts)?;
+ let target_parent = open_parent(target.0.as_raw_fd(), &target_parts)?;
+ let source_name =
+ CString::new(*source_parts.last().expect("nonempty")).expect("validated component");
+ let target_name =
+ CString::new(*target_parts.last().expect("nonempty")).expect("validated component");
+
+ let same_parent = same_directory(&source_parent, &target_parent)?;
+ Ok((
+ source_parent,
+ source_name,
+ target_parent,
+ target_name,
+ same_parent,
+ ))
+ })()
+ .map_err(|e| operation_error(e, "validate_source", "not_attempted", None))?;
rustix::fs::renameat_with(
&source_parent,
@@ -83,14 +101,15 @@ pub(crate) fn rename_no_replace(
&target_name,
rustix::fs::RenameFlags::NOREPLACE,
)
- .map_err(|error| crate::error::native_error(error.into(), "renameat_with(NOREPLACE)", None))?;
- // Keep the held-handle variant's durability contract: both mutated
- // directories are flushed before the operation reports success.
- rustix::fs::fsync(&target_parent)
- .map_err(|e| crate::error::native_error(e.into(), "fsync(rename_target_parent)", None))?;
- rustix::fs::fsync(&source_parent)
- .map_err(|e| crate::error::native_error(e.into(), "fsync(rename_source_parent)", None))?;
- Ok(())
+ .map_err(|error| {
+ operation_error(
+ crate::error::native_error(error.into(), "renameat_with(NOREPLACE)", None),
+ "rename",
+ "unknown",
+ Some(1),
+ )
+ })?;
+ sync_directories(&source_parent, &target_parent, same_parent)
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
@@ -99,7 +118,7 @@ pub(crate) fn rename_no_replace(
source_relative: &str,
_target: &RootHandle,
target_relative: &str,
-) -> io::Result<()> {
+) -> io::Result<RenameOutcome> {
validate_relative(source_relative)?;
validate_relative(target_relative)?;
Err(io::Error::new(
@@ -107,3 +126,26 @@ pub(crate) fn rename_no_replace(
"atomic no-replace rename is not implemented on this platform",
))
}
+
+#[cfg(any(target_os = "macos", target_os = "linux"))]
+fn same_directory(
+ source: &std::os::fd::OwnedFd,
+ target: &std::os::fd::OwnedFd,
+) -> io::Result<bool> {
+ let source = super::metadata::stat_opened(source.as_raw_fd())?;
+ let target = super::metadata::stat_opened(target.as_raw_fd())?;
+ Ok(source.st_dev == target.st_dev && source.st_ino == target.st_ino)
+}
+
+#[cfg(any(target_os = "macos", target_os = "linux"))]
+fn sync_directories(
+ source: &std::os::fd::OwnedFd,
+ target: &std::os::fd::OwnedFd,
+ same: bool,
+) -> io::Result<RenameOutcome> {
+ sync_parents(same, |is_target| {
+ rustix::fs::fsync(if is_target { target } else { source })
+ .map(|()| "directory_flushed")
+ .map_err(|e| crate::error::native_error(e.into(), "fsync(rename_parent)", None))
+ })
+}
diff --git a/packages/finalize-fs/src/platform/unix/tests.rs b/packages/finalize-fs/src/platform/unix/tests.rs
index d4a27484..8ddc162f 100644
--- a/packages/finalize-fs/src/platform/unix/tests.rs
+++ b/packages/finalize-fs/src/platform/unix/tests.rs
@@ -386,3 +386,54 @@ fn check_mounted_link_publication(parent: &str, filesystem_type: u64, isolation_
drop(survivor);
std::fs::remove_dir_all(base).unwrap();
}
+
+#[cfg(any(target_os = "macos", target_os = "linux"))]
+#[test]
+fn competing_target_creation_never_overwrites_either_payload() {
+ use std::io::Write;
+ use std::sync::Barrier;
+ let base =
+ std::env::temp_dir().join(format!("motrix-rename-competition-{}", std::process::id()));
+ std::fs::create_dir_all(&base).unwrap();
+ let base = base.canonicalize().unwrap();
+ let root = open_root(base.to_str().unwrap()).unwrap();
+ for index in 0..16 {
+ let source = format!("source-{index}.motrix");
+ let target = format!("target-{index}");
+ std::fs::write(base.join(&source), b"download").unwrap();
+ let artifact = super::open_artifact_for_rename(&root, &source).unwrap();
+ let barrier = Barrier::new(2);
+ std::thread::scope(|scope| {
+ let creator = scope.spawn(|| {
+ barrier.wait();
+ match std::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(base.join(&target))
+ {
+ Ok(mut file) => {
+ file.write_all(b"competitor").unwrap();
+ true
+ }
+ Err(error) => {
+ assert_eq!(error.kind(), std::io::ErrorKind::AlreadyExists);
+ false
+ }
+ }
+ });
+ barrier.wait();
+ let renamed = super::rename_opened_no_replace(&artifact, &root, &target);
+ if creator.join().unwrap() {
+ let error = renamed.unwrap_err();
+ assert_eq!(crate::error::classify_error(&error), "target_exists");
+ assert_eq!(std::fs::read(base.join(&source)).unwrap(), b"download");
+ assert_eq!(std::fs::read(base.join(&target)).unwrap(), b"competitor");
+ } else {
+ assert_eq!(renamed.unwrap().directory_sync_mode, "directory_flushed");
+ assert!(!base.join(&source).exists());
+ assert_eq!(std::fs::read(base.join(&target)).unwrap(), b"download");
+ }
+ });
+ }
+ std::fs::remove_dir_all(base).unwrap();
+}
diff --git a/packages/finalize-fs/src/platform/unsupported.rs b/packages/finalize-fs/src/platform/unsupported.rs
index d241ec13..d796ea2b 100644
--- a/packages/finalize-fs/src/platform/unsupported.rs
+++ b/packages/finalize-fs/src/platform/unsupported.rs
@@ -25,7 +25,7 @@ pub(crate) fn rename_opened_no_replace(
_artifact: &ArtifactHandle,
_target: &RootHandle,
target_relative: &str,
-) -> io::Result<()> {
+) -> io::Result<crate::rename::RenameOutcome> {
validate_relative(target_relative)?;
Err(io::Error::new(
io::ErrorKind::Unsupported,
@@ -38,7 +38,7 @@ pub(crate) fn rename_no_replace(
source_relative: &str,
_target: &RootHandle,
target_relative: &str,
-) -> io::Result<()> {
+) -> io::Result<crate::rename::RenameOutcome> {
validate_relative(source_relative)?;
validate_relative(target_relative)?;
Err(io::Error::new(
diff --git a/packages/finalize-fs/src/platform/windows/metadata.rs b/packages/finalize-fs/src/platform/windows/metadata.rs
index 41f59441..721e990f 100644
--- a/packages/finalize-fs/src/platform/windows/metadata.rs
+++ b/packages/finalize-fs/src/platform/windows/metadata.rs
@@ -18,7 +18,7 @@ use windows_sys::Win32::Storage::FileSystem::{
};
#[derive(Clone, Debug, Eq, PartialEq)]
-enum FileIdentity {
+pub(super) enum FileIdentity {
Extended([u8; 16]),
Legacy(u64),
}
@@ -77,7 +77,7 @@ pub(super) fn query_stamp(handle: &OwnedHandle) -> io::Result<FileStamp> {
})
}
-fn query_identity(handle: &OwnedHandle) -> io::Result<(u64, FileIdentity)> {
+pub(super) fn query_identity(handle: &OwnedHandle) -> io::Result<(u64, FileIdentity)> {
query_identity_with(handle, query::<FILE_ID_INFO>(handle, FileIdInfo))
}
diff --git a/packages/finalize-fs/src/platform/windows/mod.rs b/packages/finalize-fs/src/platform/windows/mod.rs
index b9440202..e34bc4a6 100644
--- a/packages/finalize-fs/src/platform/windows/mod.rs
+++ b/packages/finalize-fs/src/platform/windows/mod.rs
@@ -21,6 +21,10 @@ use std::path::{Component, Path, PathBuf, Prefix};
pub(crate) use copy::copy_opened;
pub(crate) use remove::remove_opened;
+use super::windows_policy::RenameRetryBudget;
+use crate::error::operation_error;
+use crate::rename::{RenameOutcome, sync_parents};
+
pub(crate) struct RootHandle {
handle: OwnedHandle,
}
@@ -31,6 +35,7 @@ pub(crate) struct ArtifactHandle {
name: Vec<u16>,
snapshot: Option<ArtifactSnapshot>,
stamp: metadata::FileStamp,
+ rename_budget: RenameRetryBudget,
}
pub(crate) fn open_root(path: &str) -> io::Result<RootHandle> {
@@ -79,7 +84,14 @@ fn open_artifact_internal(
) -> io::Result<ArtifactHandle> {
let parts = validate_relative(relative)?;
let (parent, name) = open_parent(&root.handle, &parts)?;
- let handle = nt::open_existing(&parent, &name)?;
+ let rename_budget = RenameRetryBudget::default();
+ let handle = if snapshot {
+ nt::open_existing(&parent, &name)?
+ } else {
+ rename_budget.run("open_source", "not_attempted", || {
+ nt::open_existing(&parent, &name)
+ })?
+ };
let stamp = query_stamp(&handle)?;
let snapshot = if snapshot {
Some(metadata::snapshot_opened(&handle)?)
@@ -93,6 +105,7 @@ fn open_artifact_internal(
name,
snapshot,
stamp,
+ rename_budget,
})
}
@@ -100,28 +113,40 @@ pub(crate) fn rename_opened_no_replace(
artifact: &ArtifactHandle,
target: &RootHandle,
target_relative: &str,
-) -> io::Result<()> {
- if let Some(snapshot) = &artifact.snapshot {
- ensure_snapshot(&artifact.handle, snapshot)?;
- } else if query_stamp(&artifact.handle)? != artifact.stamp {
- return Err(io::Error::new(
- io::ErrorKind::InvalidData,
- "opened Windows artifact changed before rename",
- ));
- }
- ensure_named_entry(&artifact.handle, &artifact.parent, &artifact.name)?;
- let parts = validate_relative(target_relative)?;
- let (target_parent, target_name) = open_parent(&target.handle, &parts)?;
- nt::rename_no_replace_with_retry(&artifact.handle, &target_parent, &target_name)?;
- ensure_named_entry(&artifact.handle, &target_parent, &target_name)?;
- assert_name_absent(&artifact.parent, &artifact.name)?;
- // Match the Unix durability contract: flush both mutated directories
- // before reporting success, instead of depending on the host to flush
- // after the sidecar could have crashed. flush_directory keeps the SMB
- // remote-acknowledgement policy for directory flushes.
- nt::flush_directory(&target_parent).map(|_| ())?;
- nt::flush_directory(&artifact.parent).map(|_| ())?;
- Ok(())
+) -> io::Result<RenameOutcome> {
+ let (target_parent, target_name, same_parent) = (|| {
+ if let Some(snapshot) = &artifact.snapshot {
+ ensure_snapshot(&artifact.handle, snapshot)?;
+ } else if query_stamp(&artifact.handle)? != artifact.stamp {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "opened Windows artifact changed before rename",
+ ));
+ }
+ ensure_named_entry(&artifact.handle, &artifact.parent, &artifact.name)?;
+ let parts = validate_relative(target_relative)?;
+ let (target_parent, target_name) = open_parent(&target.handle, &parts)?;
+ let same_parent = metadata::query_identity(&artifact.parent)?
+ == metadata::query_identity(&target_parent)?;
+ Ok((target_parent, target_name, same_parent))
+ })()
+ .map_err(|e| operation_error(e, "validate_source", "not_attempted", None))?;
+ nt::rename_no_replace_with_retry(
+ &artifact.handle,
+ &target_parent,
+ &target_name,
+ &artifact.rename_budget,
+ )?;
+ ensure_named_entry(&artifact.handle, &target_parent, &target_name)
+ .and_then(|()| assert_name_absent(&artifact.parent, &artifact.name))
+ .map_err(|e| operation_error(e, "verify_target", "applied", None))?;
+ sync_parents(same_parent, |target| {
+ nt::flush_directory(if target {
+ &target_parent
+ } else {
+ &artifact.parent
+ })
+ })
}
pub(crate) fn rename_no_replace(
@@ -129,7 +154,7 @@ pub(crate) fn rename_no_replace(
source_relative: &str,
target: &RootHandle,
target_relative: &str,
-) -> io::Result<()> {
+) -> io::Result<RenameOutcome> {
let artifact = open_artifact(source, source_relative)?;
rename_opened_no_replace(&artifact, target, target_relative)
}
diff --git a/packages/finalize-fs/src/platform/windows/nt.rs b/packages/finalize-fs/src/platform/windows/nt.rs
index c57c83a7..a9565625 100644
--- a/packages/finalize-fs/src/platform/windows/nt.rs
+++ b/packages/finalize-fs/src/platform/windows/nt.rs
@@ -1,8 +1,8 @@
//! Thin, checked wrappers around the Windows native handle APIs we need.
use super::super::windows_policy::{
- is_online_smb2, is_transient_rename_conflict, remote_directory_acknowledged,
- rename_retry_delay_ms, unsupported_information,
+ RenameRetryBudget, case_sensitive_query, is_online_smb2, remote_directory_acknowledged,
+ unsupported_information,
};
use crate::error::{native_error, os_code};
use std::ffi::{OsStr, c_void};
@@ -11,7 +11,6 @@ use std::mem::size_of;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::path::Path;
-use std::time::Duration;
use windows_sys::Wdk::Foundation::OBJECT_ATTRIBUTES;
use windows_sys::Wdk::Storage::FileSystem::{
FILE_CREATE, FILE_DIRECTORY_FILE, FILE_DISPOSITION_DELETE,
@@ -273,7 +272,7 @@ fn nt_create(
Length: u32::try_from(size_of::<OBJECT_ATTRIBUTES>()).expect("OBJECT_ATTRIBUTES size"),
RootDirectory: parent.as_raw_handle(),
ObjectName: &object_name,
- Attributes: object_attributes(parent),
+ Attributes: object_attributes(parent)?,
SecurityDescriptor: std::ptr::null(),
SecurityQualityOfService: std::ptr::null(),
};
@@ -301,7 +300,7 @@ fn nt_create(
Ok(unsafe { OwnedHandle::from_raw_handle(handle) })
}
-fn object_attributes(parent: &OwnedHandle) -> u32 {
+fn object_attributes(parent: &OwnedHandle) -> io::Result<u32> {
const FILE_CS_FLAG_CASE_SENSITIVE_DIR: u32 = 1;
let mut info = FILE_CASE_SENSITIVE_INFO::default();
let result = unsafe {
@@ -313,11 +312,20 @@ fn object_attributes(parent: &OwnedHandle) -> u32 {
.expect("FILE_CASE_SENSITIVE_INFO size"),
)
};
- if result != 0 && info.Flags & FILE_CS_FLAG_CASE_SENSITIVE_DIR != 0 {
+ let sensitive = case_sensitive_query(if result == 0 {
+ Err(native_error(
+ io::Error::last_os_error(),
+ "GetFileInformationByHandleEx(FileCaseSensitiveInfo)",
+ None,
+ ))
+ } else {
+ Ok(info.Flags & FILE_CS_FLAG_CASE_SENSITIVE_DIR != 0)
+ })?;
+ Ok(if sensitive {
OBJ_DONT_REPARSE
} else {
OBJ_CASE_INSENSITIVE | OBJ_DONT_REPARSE
- }
+ })
}
pub(super) fn rename_no_replace(
@@ -357,35 +365,16 @@ pub(super) fn rename_no_replace(
)
}
-/// Rename with surge-style exponential backoff. Antivirus scanners, search
-/// indexers and handles lingering after `Close()` returns can hold the
-/// artifact or target name with a sharing violation for a few milliseconds;
-/// only that error family (`ACCESS_DENIED`, `SHARING_VIOLATION`,
-/// `LOCK_VIOLATION`) is retried, five attempts with a 50 ms doubling base.
-/// Every other error — and exhaustion of the schedule — is reported
-/// immediately, so the host journal recovery path is unchanged.
+/// Retry only failed rename calls, sharing the admission wait budget.
pub(super) fn rename_no_replace_with_retry(
artifact: &OwnedHandle,
target_parent: &OwnedHandle,
target_name: &[u16],
+ budget: &RenameRetryBudget,
) -> io::Result<()> {
- let mut attempt = 0_usize;
- loop {
- let error = match rename_no_replace(artifact, target_parent, target_name) {
- Ok(()) => return Ok(()),
- Err(error) => error,
- };
- let delay = is_transient_rename_conflict(os_code(&error))
- .then(|| rename_retry_delay_ms(attempt))
- .flatten();
- match delay {
- Some(delay) => {
- std::thread::sleep(Duration::from_millis(delay));
- attempt += 1;
- }
- None => return Err(error),
- }
- }
+ budget.run("rename", "unknown", || {
+ rename_no_replace(artifact, target_parent, target_name)
+ })
}
pub(super) fn mark_delete(artifact: &OwnedHandle) -> io::Result<()> {
diff --git a/packages/finalize-fs/src/platform/windows/tests.rs b/packages/finalize-fs/src/platform/windows/tests.rs
index f285d759..866b38c8 100644
--- a/packages/finalize-fs/src/platform/windows/tests.rs
+++ b/packages/finalize-fs/src/platform/windows/tests.rs
@@ -216,3 +216,32 @@ fn smb_share_supports_held_rename_copy_and_removal() {
remove_opened(complete, ".remove-file", false).unwrap();
assert_eq!(fs::read_dir(scratch.path()).unwrap().count(), 0);
}
+
+#[test]
+fn rename_admission_waits_for_a_reader_that_denies_delete_sharing() {
+ use std::os::windows::fs::OpenOptionsExt;
+ use windows_sys::Win32::Storage::FileSystem::{FILE_SHARE_READ, FILE_SHARE_WRITE};
+
+ let scratch = Scratch::new("rename-admission-retry");
+ fs::write(scratch.path().join("source.motrix"), b"complete").unwrap();
+ let root = open_root(scratch.path().to_str().unwrap()).unwrap();
+ let reader = fs::OpenOptions::new()
+ .read(true)
+ .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
+ .open(scratch.path().join("source.motrix"))
+ .unwrap();
+ std::thread::scope(|scope| {
+ scope.spawn(move || {
+ std::thread::sleep(std::time::Duration::from_millis(120));
+ drop(reader);
+ });
+ let artifact = super::open_artifact_for_rename(&root, "source.motrix").unwrap();
+ let outcome = rename_opened_no_replace(&artifact, &root, "complete.bin").unwrap();
+ assert_eq!(outcome.directory_sync_mode, "directory_flushed");
+ });
+ assert_eq!(
+ fs::read(scratch.path().join("complete.bin")).unwrap(),
+ b"complete"
+ );
+ assert!(!scratch.path().join("source.motrix").exists());
+}
diff --git a/packages/finalize-fs/src/platform/windows_policy.rs b/packages/finalize-fs/src/platform/windows_policy.rs
index ff7cb9c7..15ef7dcc 100644
--- a/packages/finalize-fs/src/platform/windows_policy.rs
+++ b/packages/finalize-fs/src/platform/windows_policy.rs
@@ -16,11 +16,9 @@ pub(super) fn is_online_smb2(protocol: u32, major: u16, flags: u32) -> bool {
protocol == 0x0002_0000 && major >= 2 && flags & 0x2 == 0
}
-/// Rename errors that are transient in practice: antivirus scanners, search
-/// indexers and recently closed handles hold the artifact or target name for a
-/// few milliseconds. ACCESS_DENIED (5), SHARING_VIOLATION (32) and
-/// LOCK_VIOLATION (33) only — real permission settings, invalid paths,
-/// missing parents and cross-device moves are reported immediately.
+/// Sharing/lock violations can be transient. ACCESS_DENIED is ambiguous: it
+/// can mean either temporary interference or a permanent ACL denial. All three
+/// receive bounded retries; no retry changes permissions or sharing policy.
pub(super) fn is_transient_rename_conflict(code: Option<i32>) -> bool {
matches!(code, Some(5 | 32 | 33))
}
@@ -39,10 +37,144 @@ pub(super) fn rename_retry_delay_ms(attempt: usize) -> Option<u64> {
}
}
+/// One wait budget follows a rename-only handle from admission through rename.
+/// Successful opens do not reset the budget. Total deliberate waiting is at
+/// most 750 ms; this does not impose a timeout on a blocking filesystem call.
+#[derive(Default)]
+pub(super) struct RenameRetryBudget(std::cell::Cell<usize>);
+
+impl RenameRetryBudget {
+ pub(super) fn run<T>(
+ &self,
+ stage: &'static str,
+ mutation: &'static str,
+ operation: impl FnMut() -> std::io::Result<T>,
+ ) -> std::io::Result<T> {
+ self.run_with_sleep(stage, mutation, operation, |ms| {
+ std::thread::sleep(std::time::Duration::from_millis(ms));
+ })
+ }
+
+ fn run_with_sleep<T>(
+ &self,
+ stage: &'static str,
+ mutation: &'static str,
+ mut operation: impl FnMut() -> std::io::Result<T>,
+ mut sleep: impl FnMut(u64),
+ ) -> std::io::Result<T> {
+ let mut attempts = 0;
+ loop {
+ attempts += 1;
+ let error = match operation() {
+ Ok(value) => return Ok(value),
+ Err(error) => error,
+ };
+ let delay = is_transient_rename_conflict(crate::error::os_code(&error))
+ .then(|| rename_retry_delay_ms(self.0.get()))
+ .flatten();
+ match delay {
+ Some(ms) => {
+ self.0.set(self.0.get() + 1);
+ sleep(ms);
+ }
+ None => {
+ return Err(crate::error::operation_error(
+ error,
+ stage,
+ mutation,
+ Some(attempts),
+ ));
+ }
+ }
+ }
+ }
+}
+
+/// A failed capability query must not turn an operational error into a change
+/// in path lookup semantics. Only known unsupported-information errors fall back.
+pub(super) fn case_sensitive_query(result: std::io::Result<bool>) -> std::io::Result<bool> {
+ match result {
+ Err(error) if unsupported_information(crate::error::os_code(&error)) => Ok(false),
+ result => result,
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn case_query_only_falls_back_for_capability_errors() {
+ assert!(case_sensitive_query(Ok(true)).unwrap());
+ assert!(!case_sensitive_query(Ok(false)).unwrap());
+ for code in [1, 50, 87, 120, 124] {
+ assert!(!case_sensitive_query(Err(std::io::Error::from_raw_os_error(code))).unwrap());
+ }
+ for code in [5, 32, 53, 64, 1117] {
+ assert_eq!(
+ case_sensitive_query(Err(std::io::Error::from_raw_os_error(code)))
+ .unwrap_err()
+ .raw_os_error(),
+ Some(code)
+ );
+ }
+ }
+
+ #[test]
+ fn admission_and_rename_share_one_retry_budget() {
+ let budget = RenameRetryBudget::default();
+ let mut waits = Vec::new();
+ let mut opens = 0;
+ budget
+ .run_with_sleep(
+ "open_source",
+ "not_attempted",
+ || {
+ opens += 1;
+ if opens <= 2 {
+ Err(std::io::Error::from_raw_os_error(32))
+ } else {
+ Ok(())
+ }
+ },
+ |ms| waits.push(ms),
+ )
+ .unwrap();
+ let error = budget
+ .run_with_sleep::<()>(
+ "rename",
+ "unknown",
+ || Err(std::io::Error::from_raw_os_error(5)),
+ |ms| waits.push(ms),
+ )
+ .unwrap_err();
+ assert_eq!(waits, vec![50, 100, 200, 400]);
+ let context = crate::error::operation_context(&error).unwrap();
+ assert_eq!(context.stage, "rename");
+ assert_eq!(context.attempts, Some(3));
+ assert_eq!(crate::error::os_code(&error), Some(5));
+ }
+
+ #[test]
+ fn successful_mutations_and_non_conflict_errors_are_never_replayed() {
+ let budget = RenameRetryBudget::default();
+ budget.run("rename", "unknown", || Ok(())).unwrap();
+ for code in [17, 87, 112, 183, 64] {
+ let error = budget
+ .run_with_sleep::<()>(
+ "rename",
+ "unknown",
+ || Err(std::io::Error::from_raw_os_error(code)),
+ |_| panic!("permanent or ambiguous transport errors must not retry"),
+ )
+ .unwrap_err();
+ assert_eq!(
+ crate::error::operation_context(&error).unwrap().attempts,
+ Some(1)
+ );
+ }
+ }
+
#[test]
fn remote_acknowledgement_requires_online_smb2_or_newer() {
assert!(is_online_smb2(0x0002_0000, 2, 0));
diff --git a/packages/finalize-fs/src/protocol.rs b/packages/finalize-fs/src/protocol.rs
index 705aa93e..398e8095 100644
--- a/packages/finalize-fs/src/protocol.rs
+++ b/packages/finalize-fs/src/protocol.rs
@@ -131,6 +131,12 @@ pub(crate) struct Response<'a> {
pub(crate) os_error: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) nt_status: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub(crate) stage: Option<&'static str>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub(crate) mutation: Option<&'static str>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub(crate) attempts: Option<usize>,
}
impl<'a> Response<'a> {
@@ -151,6 +157,9 @@ impl<'a> Response<'a> {
directory_sync_mode: None,
os_error: None,
nt_status: None,
+ stage: None,
+ mutation: None,
+ attempts: None,
}
}
@@ -162,6 +171,11 @@ impl<'a> Response<'a> {
);
response.os_error = crate::error::os_code(&error);
response.nt_status = crate::error::nt_status(&error);
+ if let Some(context) = crate::error::operation_context(&error) {
+ response.stage = Some(context.stage);
+ response.mutation = Some(context.mutation);
+ response.attempts = context.attempts;
+ }
response
}
@@ -208,6 +222,22 @@ mod tests {
use serde_json::json;
use std::io::Cursor;
+ #[test]
+ fn mutation_context_preserves_original_native_diagnostics() {
+ let native = crate::error::native_error(
+ std::io::Error::from_raw_os_error(5),
+ "NtSetInformationFile",
+ Some(0xc0000022_u32 as i32),
+ );
+ let error = crate::error::operation_error(native, "rename", "unknown", Some(3));
+ let value = serde_json::to_value(Response::filesystem_error(1, error)).unwrap();
+ assert_eq!(value["stage"], "rename");
+ assert_eq!(value["mutation"], "unknown");
+ assert_eq!(value["attempts"], 3);
+ assert_eq!(value["os_error"], 5);
+ assert_eq!(value["nt_status"], "0xc0000022");
+ }
+
#[test]
fn request_wire_remains_tagged_by_operation() {
let request: Request = serde_json::from_value(json!({
diff --git a/packages/finalize-fs/src/rename.rs b/packages/finalize-fs/src/rename.rs
new file mode 100644
index 00000000..1243e52b
--- /dev/null
+++ b/packages/finalize-fs/src/rename.rs
@@ -0,0 +1,89 @@
+//! Rename completion describes namespace mutation separately from durability.
+
+use crate::error::operation_error;
+use std::io;
+
+#[derive(Debug)]
+pub(crate) struct RenameOutcome {
+ pub(crate) directory_sync_mode: &'static str,
+}
+
+/// Compare held directory identities before mutation; never deduplicate by path.
+pub(crate) fn sync_parents(
+ same_parent: bool,
+ mut sync: impl FnMut(bool) -> io::Result<&'static str>,
+) -> io::Result<RenameOutcome> {
+ let target =
+ sync(true).map_err(|e| operation_error(e, "sync_target_parent", "applied", None))?;
+ let source = if same_parent {
+ target
+ } else {
+ sync(false).map_err(|e| operation_error(e, "sync_source_parent", "applied", None))?
+ };
+ Ok(RenameOutcome {
+ directory_sync_mode: if target == "remote_acknowledged" || source == "remote_acknowledged" {
+ "remote_acknowledged"
+ } else {
+ "directory_flushed"
+ },
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn same_directory_flushes_once_and_distinct_directories_flush_target_first() {
+ for same in [true, false] {
+ let mut calls = Vec::new();
+ let outcome = sync_parents(same, |target| {
+ calls.push(target);
+ Ok("directory_flushed")
+ })
+ .unwrap();
+ assert_eq!(calls, if same { vec![true] } else { vec![true, false] });
+ assert_eq!(outcome.directory_sync_mode, "directory_flushed");
+ }
+ }
+
+ #[test]
+ fn sync_failure_preserves_the_applied_mutation_and_native_error() {
+ for fail_target in [true, false] {
+ let error = sync_parents(false, |target| {
+ if target == fail_target {
+ Err(io::Error::from_raw_os_error(5))
+ } else {
+ Ok("directory_flushed")
+ }
+ })
+ .unwrap_err();
+ let context = crate::error::operation_context(&error).unwrap();
+ assert_eq!(context.mutation, "applied");
+ assert_eq!(
+ context.stage,
+ if fail_target {
+ "sync_target_parent"
+ } else {
+ "sync_source_parent"
+ }
+ );
+ assert_eq!(crate::error::os_code(&error), Some(5));
+ }
+ }
+
+ #[test]
+ fn remote_acknowledgement_is_not_reported_as_a_directory_flush() {
+ for remote_target in [true, false] {
+ let outcome = sync_parents(false, |target| {
+ Ok(if target == remote_target {
+ "remote_acknowledged"
+ } else {
+ "directory_flushed"
+ })
+ })
+ .unwrap();
+ assert_eq!(outcome.directory_sync_mode, "remote_acknowledged");
+ }
+ }
+}
diff --git a/packages/finalize-fs/src/state.rs b/packages/finalize-fs/src/state.rs
index f1ca72ff..da760625 100644
--- a/packages/finalize-fs/src/state.rs
+++ b/packages/finalize-fs/src/state.rs
@@ -77,7 +77,20 @@ impl State {
response.handle = Some(handle);
response
}
- Err(error) => Response::filesystem_error(request_id, error),
+ Err(error) => {
+ let error =
+ if rename_only && crate::error::operation_context(&error).is_none() {
+ crate::error::operation_error(
+ error,
+ "open_source",
+ "not_attempted",
+ None,
+ )
+ } else {
+ error
+ };
+ Response::filesystem_error(request_id, error)
+ }
}
}
Request::RenameOpenedNoReplace {
@@ -96,7 +109,7 @@ impl State {
"unknown target root",
);
};
- operation_response(
+ rename_response(
request_id,
rename_opened_no_replace(artifact, target, &target_relative),
)
@@ -172,7 +185,7 @@ impl State {
"unknown target root",
);
};
- operation_response(
+ rename_response(
request_id,
rename_no_replace(source, &source_relative, target, &target_relative),
)
@@ -321,6 +334,22 @@ impl State {
}
}
+fn rename_response(
+ request_id: u64,
+ result: std::io::Result<crate::rename::RenameOutcome>,
+) -> Response<'static> {
+ match result {
+ Ok(outcome) => {
+ let mut response = Response::ok(Some(request_id));
+ response.stage = Some("complete");
+ response.mutation = Some("applied");
+ response.directory_sync_mode = Some(outcome.directory_sync_mode);
+ response
+ }
+ Err(error) => Response::filesystem_error(request_id, error),
+ }
+}
+
fn operation_response(request_id: u64, result: std::io::Result<()>) -> Response<'static> {
match result {
Ok(()) => Response::ok(Some(request_id)),
diff --git a/src/core/plugin/finalize/filesystem-adapter.test.ts b/src/core/plugin/finalize/filesystem-adapter.test.ts
index 8b1965dd..11fcda1a 100644
--- a/src/core/plugin/finalize/filesystem-adapter.test.ts
+++ b/src/core/plugin/finalize/filesystem-adapter.test.ts
@@ -75,7 +75,7 @@ describe.runIf(process.platform !== 'win32')(
if (incoming.length < size + 4) return
const request = JSON.parse(incoming.subarray(4, size + 4).toString())
incoming = incoming.subarray(size + 4)
- if (request.relative === 'crash') process.exit(23)
+ if (request.relative === 'crash' || request.target_relative === 'crash') process.exit(23)
const send = () => {
const payload = Buffer.from(JSON.stringify({
request_id: request.request_id, status: 'ok',
@@ -86,6 +86,17 @@ describe.runIf(process.platform !== 'win32')(
handle: request.op === 'open_root' ? 1 : 2,
platform: 'test', rename_no_replace: true, held_roots: true,
directory_sync: true, held_artifacts: true,
+ ...(request.target_relative === 'synced' ? {
+ stage: 'complete', mutation: 'applied', directory_sync_mode: 'directory_flushed',
+ } : {}),
+ ...(request.target_relative === 'future-mode' ? {
+ directory_sync_mode: 'future-unsupported-mode',
+ } : {}),
+ ...(request.target_relative === 'flush-failed' ? {
+ status: 'error', code: 'io_error', os_error: 5,
+ stage: 'sync_target_parent', mutation: 'applied',
+ message: 'directory flush failed',
+ } : {}),
...(request.relative === 'unsupported' ? {
status: 'error', code: 'unsupported',
operation: request.op, os_error: 1, nt_status: '0xc0000010',
@@ -203,6 +214,55 @@ describe.runIf(process.platform !== 'win32')(
}
})
+ it('reports native durability, keeps legacy responses compatible, and preserves post-rename failures', async () => {
+ const adapter = new NativeFinalizeFilesystemAdapter(await framedSidecar())
+ try {
+ const root = await adapter.openRoot('/tmp')
+ const artifact = await adapter.openArtifact(root, 'source', 'rename')
+ await expect(
+ adapter.renameOpenedNoReplace(artifact, root, 'synced')
+ ).resolves.toEqual({ directorySyncMode: 'directory_flushed' })
+ await expect(
+ adapter.renameOpenedNoReplace(artifact, root, 'legacy')
+ ).resolves.toBeUndefined()
+ await expect(
+ adapter.renameOpenedNoReplace(artifact, root, 'future-mode')
+ ).resolves.toBeUndefined()
+ await expect(
+ adapter.renameOpenedNoReplace(artifact, root, 'flush-failed')
+ ).rejects.toMatchObject({
+ code: 'io_error',
+ details: {
+ stage: 'sync_target_parent',
+ mutation: 'applied',
+ osError: 5,
+ },
+ })
+ } finally {
+ await adapter.dispose()
+ }
+ })
+
+ it('marks a lost rename response as unknown instead of assuming no mutation', async () => {
+ const adapter = new NativeFinalizeFilesystemAdapter(await framedSidecar())
+ try {
+ const root = await adapter.openRoot('/tmp')
+ const artifact = await adapter.openArtifact(root, 'source', 'rename')
+ await expect(
+ adapter.renameOpenedNoReplace(artifact, root, 'crash')
+ ).rejects.toMatchObject({
+ code: 'io_error',
+ details: {
+ operation: 'rename_opened_no_replace',
+ stage: 'transport',
+ mutation: 'unknown',
+ },
+ })
+ } finally {
+ await adapter.dispose()
+ }
+ })
+
async function rejectedError(operation: Promise<unknown>): Promise<Error> {
let caught: unknown
try {
diff --git a/src/core/plugin/finalize/filesystem-adapter.ts b/src/core/plugin/finalize/filesystem-adapter.ts
index 25e8e14b..046e8399 100644
--- a/src/core/plugin/finalize/filesystem-adapter.ts
+++ b/src/core/plugin/finalize/filesystem-adapter.ts
@@ -15,6 +15,10 @@ export type FinalizeFsErrorCode =
| 'symlink_rejected'
| 'io_error'
+export interface FinalizeRenameResult {
+ directorySyncMode: 'directory_flushed' | 'remote_acknowledged'
+}
+
export class FinalizeFsError extends Error {
constructor(
readonly code: FinalizeFsErrorCode,
@@ -23,6 +27,9 @@ export class FinalizeFsError extends Error {
operation?: string
osError?: number
ntStatus?: string
+ stage?: string
+ mutation?: 'not_attempted' | 'applied' | 'unknown'
+ attempts?: number
}
) {
super(message)
@@ -47,6 +54,9 @@ interface WireResponse {
operation?: string
os_error?: number
nt_status?: string
+ stage?: string
+ mutation?: 'not_attempted' | 'applied' | 'unknown'
+ attempts?: number
directory_sync_mode?: 'directory_flushed' | 'remote_acknowledged'
sanitized_name?: string
platform?: string
@@ -91,7 +101,7 @@ export interface FinalizeFilesystemAdapter {
artifact: FinalizeArtifactHandle,
targetRoot: FinalizeRootHandle,
targetRelative: string
- ): Promise<void>
+ ): Promise<FinalizeRenameResult | undefined>
linkOpenedNoReplace(
artifact: FinalizeArtifactHandle,
targetRoot: FinalizeRootHandle,
@@ -113,7 +123,7 @@ export interface FinalizeFilesystemAdapter {
sourceRelative: string,
targetRoot: FinalizeRootHandle,
targetRelative: string
- ): Promise<void>
+ ): Promise<FinalizeRenameResult | undefined>
removeOpened(
artifact: FinalizeArtifactHandle,
quarantineRelative: string,
@@ -230,13 +240,19 @@ export class NativeFinalizeFilesystemAdapter
artifact: FinalizeArtifactHandle,
targetRoot: FinalizeRootHandle,
targetRelative: string
- ): Promise<void> {
- await this.request({
+ ): Promise<FinalizeRenameResult | undefined> {
+ const response = await this.request({
op: 'rename_opened_no_replace',
artifact: this.nativeId(artifact),
target_root: this.nativeId(targetRoot),
target_relative: targetRelative,
})
+ if (
+ response.directory_sync_mode === 'directory_flushed' ||
+ response.directory_sync_mode === 'remote_acknowledged'
+ ) {
+ return { directorySyncMode: response.directory_sync_mode }
+ }
}
async linkOpenedNoReplace(
@@ -311,14 +327,20 @@ export class NativeFinalizeFilesystemAdapter
sourceRelative: string,
targetRoot: FinalizeRootHandle,
targetRelative: string
- ): Promise<void> {
- await this.request({
+ ): Promise<FinalizeRenameResult | undefined> {
+ const response = await this.request({
op: 'rename_no_replace',
source_root: this.nativeId(sourceRoot),
source_relative: sourceRelative,
target_root: this.nativeId(targetRoot),
target_relative: targetRelative,
})
+ if (
+ response.directory_sync_mode === 'directory_flushed' ||
+ response.directory_sync_mode === 'remote_acknowledged'
+ ) {
+ return { directorySyncMode: response.directory_sync_mode }
+ }
}
async removeOpened(
@@ -337,20 +359,10 @@ export class NativeFinalizeFilesystemAdapter
}
async syncRoot(root: FinalizeRootHandle): Promise<void> {
- const response = await this.request({
+ await this.request({
op: 'sync_root',
root: this.nativeId(root),
})
- if (
- response.directory_sync_mode === 'remote_acknowledged' &&
- !this.remoteDurabilityReported
- ) {
- this.remoteDurabilityReported = true
- getLogger('finalize').warn(
- { durability: response.directory_sync_mode },
- 'SMB directory flush is unsupported; namespace durability depends on the remote server'
- )
- }
}
async close(
@@ -438,7 +450,35 @@ export class NativeFinalizeFilesystemAdapter
child.stdin.write(frame, (error) => {
if (error && this.child === child) this.markDead(error)
})
- const result = await response
+ const result = await response.catch((cause: unknown) => {
+ if (
+ body.op === 'rename_opened_no_replace' ||
+ body.op === 'rename_no_replace'
+ ) {
+ const error = new FinalizeFsError(
+ 'io_error',
+ 'rename response lost; filesystem recovery is required',
+ {
+ operation: String(body.op),
+ stage: 'transport',
+ mutation: 'unknown',
+ }
+ )
+ error.cause = cause
+ throw error
+ }
+ throw cause
+ })
+ if (
+ result.directory_sync_mode === 'remote_acknowledged' &&
+ !this.remoteDurabilityReported
+ ) {
+ this.remoteDurabilityReported = true
+ getLogger('finalize').warn(
+ { durability: result.directory_sync_mode },
+ 'SMB directory flush is unsupported; namespace durability depends on the remote server'
+ )
+ }
if (result.status === 'error') {
throw new FinalizeFsError(
result.code ?? 'io_error',
@@ -447,6 +487,9 @@ export class NativeFinalizeFilesystemAdapter
operation: result.operation ?? String(body.op),
osError: result.os_error,
ntStatus: result.nt_status,
+ stage: result.stage,
+ mutation: result.mutation,
+ attempts: result.attempts,
}
)
}
diff --git a/src/core/plugin/finalize/native-artifact-operations.integration.test.ts b/src/core/plugin/finalize/native-artifact-operations.integration.test.ts
index 52db91dd..c856d32d 100644
--- a/src/core/plugin/finalize/native-artifact-operations.integration.test.ts
+++ b/src/core/plugin/finalize/native-artifact-operations.integration.test.ts
@@ -72,6 +72,33 @@ describe.runIf(existsSync(binary))(
return { root, adapter, operations }
}
+ it.each([false, true])(
+ 'syncs rename directories in the native layer, retaining legacy fallback: %s',
+ async (legacy) => {
+ const { root, adapter, operations } = await setup()
+ const source = path.join(root, 'download.motrix')
+ const target = path.join(root, 'download')
+ await writeFile(source, 'complete')
+ const identity = await readArtifactIdentity(source)
+ const realRename = adapter.renameOpenedNoReplace.bind(adapter)
+ vi.spyOn(adapter, 'renameOpenedNoReplace').mockImplementation(
+ async (...args) => {
+ const result = await realRename(...args)
+ expect(result).toEqual({ directorySyncMode: 'directory_flushed' })
+ return legacy ? undefined : result
+ }
+ )
+ const sync = vi.spyOn(adapter, 'syncRoot')
+ try {
+ await operations.moveNoReplace(source, identity, target)
+ expect(sync).toHaveBeenCalledTimes(legacy ? 2 : 0)
+ expect(await readFile(target, 'utf8')).toBe('complete')
+ } finally {
+ await adapter.dispose()
+ }
+ }
+ )
+
it('finalizes in an existing directory whose mkdir reports EPERM like a Windows drive root', async () => {
const { root, adapter, operations } = await setup()
const source = path.join(root, 'archive.zip.motrix')
diff --git a/src/core/plugin/finalize/native-artifact-operations.ts b/src/core/plugin/finalize/native-artifact-operations.ts
index 093c46e9..751e50de 100644
--- a/src/core/plugin/finalize/native-artifact-operations.ts
+++ b/src/core/plugin/finalize/native-artifact-operations.ts
@@ -169,6 +169,7 @@ export class NativeFinalizeArtifactOperations
'rename'
)
await this.requireIdentity(sourcePath, expected)
+ let directoriesSynced = false
if (method === 'link') {
await this.adapter.linkOpenedNoReplace(
artifact,
@@ -176,14 +177,18 @@ export class NativeFinalizeArtifactOperations
path.basename(targetPath)
)
} else {
- await this.adapter.renameOpenedNoReplace(
+ const result = await this.adapter.renameOpenedNoReplace(
artifact,
targetRoot,
path.basename(targetPath)
)
+ directoriesSynced = result !== undefined
+ }
+ // Older sidecars and link publication still require caller-owned syncs.
+ if (!directoriesSynced) {
+ await this.adapter.syncRoot(sourceRoot)
+ await this.adapter.syncRoot(targetRoot)
}
- await this.adapter.syncRoot(sourceRoot)
- await this.adapter.syncRoot(targetRoot)
await this.requireIdentity(targetPath, expected)
} finally {
if (artifact) await this.adapter.close(artifact).catch(() => undefined)