A full-featured download manager.
fix(finalize): support smb shares and recover failed journals (#2132)
Dr_rOotbc98f95ddd90
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex f1552c8e..d4510c84 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -400,6 +400,7 @@ jobs:- name: Install dependenciesrun: pnpm install --frozen-lockfileenv:+ MOTRIX_SKIP_ELECTRON_REBUILD: '1'MOTRIX_SKIP_ENGINE_FETCH: '1'# Electron does not hydrate dist/ during pnpm install. build:legal@@ -418,7 +419,6 @@ jobs:pnpm run build:builtinpnpm run build:native-host -- --platform ${{ matrix.platform }} --arch ${{ matrix.arch }}pnpm run build:finalize-fs -- --platform ${{ matrix.platform }} --arch ${{ matrix.arch }}- pnpm run build:electron- name: Finalize filesystem runtime integrationenv:@@ -426,8 +426,14 @@ jobs:run: >-pnpm exec vitest runsrc/core/plugin/finalize/native-artifact-operations.integration.test.ts+ src/core/plugin/finalize/finalize-smb-recovery.integration.test.ts--reporter=verbose+ # SQLite integration tests above use Node. Switch native modules to the+ # packaged Electron ABI only after those tests have finished.+ - name: Build Electron application+ run: pnpm run build:electron+- name: Stage Electron applicationrun: >-pnpm run stage:electron --diff --git a/.github/workflows/finalize-smb.yml b/.github/workflows/finalize-smb.ymlnew file mode 100644index 00000000..4908a861--- /dev/null+++ b/.github/workflows/finalize-smb.yml@@ -0,0 +1,66 @@+name: Finalize SMB++on:+ pull_request:+ branches: [main]+ paths:+ - 'packages/finalize-fs/**'+ - 'src/core/plugin/finalize/**'+ - 'src/core/session/*finalize*'+ - '.github/workflows/finalize-smb.yml'+ push:+ branches: [main]+ paths:+ - 'packages/finalize-fs/**'+ - 'src/core/plugin/finalize/**'+ - 'src/core/session/*finalize*'+ - '.github/workflows/finalize-smb.yml'+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: finalize-smb-${{ github.ref }}+ cancel-in-progress: true++jobs:+ windows-smb:+ runs-on: windows-2025+ timeout-minutes: 15+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ - uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable+ with:+ toolchain: 1.94.1+ - name: Native Windows contract and compatibility tests+ run: cargo test --manifest-path packages/finalize-fs/Cargo.toml --locked --all-targets+ - name: Exercise UNC and mapped SMB roots+ shell: pwsh+ run: |+ $ErrorActionPreference = 'Stop'+ $shareName = "MotrixFinalize-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT"+ $shareRoot = Join-Path $env:RUNNER_TEMP $shareName+ New-Item -ItemType Directory -Path $shareRoot | Out-Null+ $account = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name+ $unc = "\\$env:COMPUTERNAME\$shareName"+ $created = $false+ $mapped = $false+ try {+ Start-Service LanmanServer+ New-SmbShare -Name $shareName -Path $shareRoot -FullAccess $account | Out-Null+ $created = $true+ $env:MOTRIX_FINALIZE_SMB_ROOT = $unc+ cargo test --manifest-path packages/finalize-fs/Cargo.toml --locked -- --ignored --exact platform::windows::tests::smb_share_supports_held_rename_copy_and_removal+ if ($LASTEXITCODE -ne 0) { throw 'UNC finalize contract failed' }+ New-PSDrive -Name M -PSProvider FileSystem -Root $unc -Persist -Scope Global | Out-Null+ $mapped = $true+ $env:MOTRIX_FINALIZE_SMB_ROOT = 'M:\'+ cargo test --manifest-path packages/finalize-fs/Cargo.toml --locked -- --ignored --exact platform::windows::tests::smb_share_supports_held_rename_copy_and_removal+ if ($LASTEXITCODE -ne 0) { throw 'Mapped-drive finalize contract failed' }+ } finally {+ Remove-Item Env:MOTRIX_FINALIZE_SMB_ROOT -ErrorAction SilentlyContinue+ if ($mapped) { Remove-PSDrive -Name M -Force }+ if ($created) { Remove-SmbShare -Name $shareName -Force }+ Remove-Item -LiteralPath $shareRoot -Recurse -Force+ }diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex a3ad3865..db6eaa49 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -220,6 +220,7 @@ jobs:env:# Fetching the package target is explicit in the next step.MOTRIX_SKIP_ENGINE_FETCH: '1'+ MOTRIX_SKIP_ELECTRON_REBUILD: '1'# Electron does not declare a postinstall script, so pnpm install# does not hydrate dist/ with the runtime and license payload.@@ -236,14 +237,11 @@ jobs:run: pnpm run check:third-party-notices# Build each target on a runner with the same native CPU architecture.- # This also ensures better-sqlite3 is rebuilt for the packaged Electron.- name: Buildrun: |pnpm run build:builtinpnpm run build:native-host -- --platform ${{ matrix.platform }} --arch ${{ matrix.arch }}pnpm run build:finalize-fs -- --platform ${{ matrix.platform }} --arch ${{ matrix.arch }}- pnpm run build:electron- pnpm run stage:electron -- --platform ${{ matrix.platform }} --arch ${{ matrix.arch }}- name: Finalize filesystem runtime integrationenv:@@ -251,8 +249,16 @@ jobs:run: >-pnpm exec vitest runsrc/core/plugin/finalize/native-artifact-operations.integration.test.ts+ src/core/plugin/finalize/finalize-smb-recovery.integration.test.ts--reporter=verbose+ # SQLite integration tests above use Node. Rebuild for Electron before+ # staging, so the packaged native dependency retains the correct ABI.+ - name: Build Electron application+ run: |+ pnpm run build:electron+ pnpm run stage:electron -- --platform ${{ matrix.platform }} --arch ${{ matrix.arch }}+# Tagged macOS and Windows outputs are deliberately unsigned here. A# fresh, no-checkout job finalizes only the verified data artifact below,# applying platform signing when it is required or configured.diff --git a/packages/finalize-fs/README.md b/packages/finalize-fs/README.mdnew file mode 100644index 00000000..45e40566--- /dev/null+++ b/packages/finalize-fs/README.md@@ -0,0 +1,79 @@+# Finalize filesystem service++The sidecar performs handle-relative, identity-checked file publication and+removal. Renames never replace an existing destination. Reparse points and+unsafe path components remain rejected on Windows.++## Windows and SMB++Windows volumes are checked when opening the actual roots, before the+application records a new finalize journal. The application flushes file data+before publication. Ordinary file FLUSH failures, access failures, full disks,+and network disconnections remain errors.++Some SMB servers reject directory FLUSH with `ERROR_INVALID_FUNCTION` or+`ERROR_NOT_SUPPORTED`. For those two errors only, the sidecar checks the held+directory's `FileRemoteProtocolInfo`. If it confirms SMB 2 or newer, directory+sync reports `remote_acknowledged`. Namespace durability then depends on the+remote server's acknowledgement and storage policy; it is not a guarantee of+survival after a NAS power loss. The host logs this distinction. Other remote+protocols, local volumes, unknown protocols, and other error codes do not use+this fallback. An offline client cache also cannot qualify as a server+acknowledgement. Copy/removal use the same directory policy. File data flushes+are never converted into directory acknowledgements.++Identity queries prefer the 128-bit `FileIdInfo`. Unsupported information+classes fall back to the volume serial and 64-bit file index obtained through+`GetFileInformationByHandle`, with a distinct identity namespace. Empty IDs+are rejected. Directory enumeration uses `FileFullDirectoryInfo`, then opens+each entry and verifies its identity and reparse attributes; enumeration IDs+are not trusted for object identity.++Name-to-handle identity and absence checks request only metadata access. They+must not try a directory-write open against a held file: SMB can report the+sharing conflict before rejecting the directory type, conflicting with the+held file's intentional denial of write sharing.++Removal prefers extended disposition. If the information class is unsupported,+it uses standard delete-on-close on the verified handle. A removal request+consumes its artifact handle, including on error; the caller must close the+registry slot and reopen an artifact to retry. Absence is checked after the+held handle closes. Other processes can delay deletion by retaining handles;+that remains a recoverable error, never a successful cleanup claim.++Error responses include the operation, OS error code and original NTSTATUS+when available. The formatted message identifies the native call/information+class. Existing protocol consumers can ignore the additive fields.++## Recovery++New I/O failures keep the last journal checkpoint available for retry.+Successful rollback closes the journal only after identity and durability+checks. Startup recovery and an explicit finalize retry use the same rollback+implementation under the task's mutation lease.++Legacy journals quarantined by the old blanket `compensation failed after`+handler are considered only for ordinary direct moves with no replacement,+private target, rollback path or removal intent. Exactly one source/target+name must survive and match the recorded source identity. The surviving file+must be flushed before a compare-and-swap reopens the old journal. Malformed+rows, identity quarantines, conflicting names and changed objects remain+isolated. No user database migration or blanket journal deletion is needed.++## Tests++```sh+cargo test --manifest-path packages/finalize-fs/Cargo.toml --locked --all-targets+```++`.github/workflows/finalize-smb.yml` creates a temporary SMB share on Windows+and exercises both UNC and mapped-drive paths. Its ignored-by-default+`smb_share_supports_held_rename_copy_and_removal` test requires+`MOTRIX_FINALIZE_SMB_ROOT` to point to an existing writable SMB share. It creates+and removes only a unique scratch directory below that root.++The application tests in `finalize-smb-recovery.integration.test.ts` use a real+native sidecar and SQLite journal, injecting unsupported-root and post-rename+sync failures at the adapter boundary. They cover live retry, startup rollback,+legacy quarantine recovery, conflicts and offline shares. They can use+`MOTRIX_FINALIZE_FS_TEST_BIN` to select the target platform's binary.diff --git a/packages/finalize-fs/src/error.rs b/packages/finalize-fs/src/error.rsindex 6a993597..631e0aff 100644--- a/packages/finalize-fs/src/error.rs+++ b/packages/finalize-fs/src/error.rs@@ -1,13 +1,22 @@use std::io;pub(crate) fn classify_error(error: &io::Error) -> &'static str {+ #[cfg(windows)]+ match os_code(error) {+ Some(17) => return "cross_device",+ Some(1 | 50 | 120 | 124) => return "unsupported",+ _ => {}+ }match error.kind() {io::ErrorKind::AlreadyExists => "target_exists",io::ErrorKind::NotFound => "not_found",io::ErrorKind::InvalidInput => "invalid_path",io::ErrorKind::PermissionDenied => "permission_denied",io::ErrorKind::Unsupported => "unsupported",- _ => match error.raw_os_error() {+ #[cfg(windows)]+ _ => "io_error",+ #[cfg(not(windows))]+ _ => match os_code(error) {Some(libc::EXDEV) => "cross_device",Some(libc::ENOSYS) | Some(libc::ENOTSUP) => "unsupported",Some(libc::ELOOP) => "symlink_rejected",@@ -15,3 +24,59 @@ pub(crate) fn classify_error(error: &io::Error) -> &'static str {},}}++#[derive(Debug)]+struct NativeError {+ operation: String,+ source: io::Error,+ nt_status: Option<i32>,+}++impl std::fmt::Display for NativeError {+ fn fmt(&self, output: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(output, "{}: {}", self.operation, self.source)?;+ if let Some(status) = self.nt_status {+ write!(output, " [NTSTATUS 0x{:08x}]", status as u32)?;+ }+ Ok(())+ }+}+impl std::error::Error for NativeError {+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {+ Some(&self.source)+ }+}++#[cfg(windows)]+pub(crate) fn native_error(+ error: io::Error,+ operation: impl Into<String>,+ nt_status: Option<i32>,+) -> io::Error {+ io::Error::new(+ error.kind(),+ NativeError {+ operation: operation.into(),+ source: error,+ nt_status,+ },+ )+}++pub(crate) fn os_code(error: &io::Error) -> Option<i32> {+ error.raw_os_error().or_else(|| {+ error+ .get_ref()?+ .downcast_ref::<NativeError>()?+ .source+ .raw_os_error()+ })+}++pub(crate) fn nt_status(error: &io::Error) -> Option<String> {+ error+ .get_ref()?+ .downcast_ref::<NativeError>()?+ .nt_status+ .map(|status| format!("0x{:08x}", status as u32))+}diff --git a/packages/finalize-fs/src/platform/mod.rs b/packages/finalize-fs/src/platform/mod.rsindex d203de9c..9a5c28e6 100644--- a/packages/finalize-fs/src/platform/mod.rs+++ b/packages/finalize-fs/src/platform/mod.rs@@ -6,6 +6,8 @@ mod unix;mod unsupported;#[cfg(windows)]mod windows;+#[cfg(any(windows, test))]+mod windows_policy;#[cfg(unix)]pub(crate) use unix::{@@ -20,5 +22,16 @@ pub(crate) use unsupported::{#[cfg(windows)]pub(crate) use windows::{ArtifactHandle, RootHandle, copy_opened, open_artifact, open_artifact_for_rename, open_root,- remove_opened, rename_no_replace, rename_opened_no_replace, sync_root,+ remove_opened, rename_no_replace, rename_opened_no_replace,};++pub(crate) fn sync_root_mode(root: &RootHandle) -> std::io::Result<&'static str> {+ #[cfg(windows)]+ {+ windows::sync_root_mode(root)+ }+ #[cfg(not(windows))]+ {+ sync_root(root).map(|()| "directory_flushed")+ }+}diff --git a/packages/finalize-fs/src/platform/windows/copy.rs b/packages/finalize-fs/src/platform/windows/copy.rsindex aa2204c3..25474249 100644--- a/packages/finalize-fs/src/platform/windows/copy.rs+++ b/packages/finalize-fs/src/platform/windows/copy.rs@@ -25,7 +25,7 @@ pub(crate) fn copy_opened(materialize(&artifact.handle, snapshot, &target_parent, &target_name)?;ensure_snapshot(&artifact.handle, snapshot)?;ensure_named_entry(&artifact.handle, &artifact.parent, &artifact.name)?;- super::nt::flush(&target_parent)+ super::nt::flush_directory(&target_parent).map(|_| ())}fn materialize(@@ -47,7 +47,11 @@ fn materialize("Windows copied artifact does not match its held source",));}- super::nt::flush(&target)+ if expected.is_directory() {+ super::nt::flush_directory(&target).map(|_| ())+ } else {+ super::nt::flush(&target)+ }}fn copy_into(diff --git a/packages/finalize-fs/src/platform/windows/metadata.rs b/packages/finalize-fs/src/platform/windows/metadata.rsindex 833db08b..41f59441 100644--- a/packages/finalize-fs/src/platform/windows/metadata.rs+++ b/packages/finalize-fs/src/platform/windows/metadata.rs@@ -1,7 +1,9 @@//! Identity and immutable tree snapshots for held Windows handles.+use super::super::windows_policy::unsupported_information;use super::digest::hash_opened_file;use super::nt;+use crate::error::{native_error, os_code};use std::io;use std::mem::{offset_of, size_of};use std::os::windows::io::{AsRawHandle, OwnedHandle};@@ -9,15 +11,22 @@ use windows_sys::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_NO_MORE_FILES, ERROR_PATH_NOT_FOUND,};use windows_sys::Win32::Storage::FileSystem::{- FILE_ATTRIBUTE_REPARSE_POINT, FILE_BASIC_INFO, FILE_ID_EXTD_DIR_INFO, FILE_ID_INFO,- FILE_STANDARD_INFO, FileBasicInfo, FileIdExtdDirectoryInfo, FileIdExtdDirectoryRestartInfo,- FileIdInfo, FileStandardInfo, GetFileInformationByHandleEx,+ BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_REPARSE_POINT, FILE_BASIC_INFO, FILE_FULL_DIR_INFO,+ FILE_ID_INFO, FILE_STANDARD_INFO, FileBasicInfo, FileFullDirectoryInfo,+ FileFullDirectoryRestartInfo, FileIdInfo, FileStandardInfo, GetFileInformationByHandle,+ GetFileInformationByHandleEx,};+#[derive(Clone, Debug, Eq, PartialEq)]+enum FileIdentity {+ Extended([u8; 16]),+ Legacy(u64),+}+#[derive(Clone, Debug, Eq, PartialEq)]pub(super) struct FileStamp {volume: u64,- file_id: [u8; 16],+ file_id: FileIdentity,size: i64,last_write: i64,attributes: u32,@@ -50,7 +59,7 @@ impl ArtifactSnapshot {pub(super) fn query_stamp(handle: &OwnedHandle) -> io::Result<FileStamp> {let basic: FILE_BASIC_INFO = query(handle, FileBasicInfo)?;- let id: FILE_ID_INFO = query(handle, FileIdInfo)?;+ let (volume, file_id) = query_identity(handle)?;let standard: FILE_STANDARD_INFO = query(handle, FileStandardInfo)?;if basic.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {return Err(io::Error::new(@@ -59,8 +68,8 @@ pub(super) fn query_stamp(handle: &OwnedHandle) -> io::Result<FileStamp> {));}Ok(FileStamp {- volume: id.VolumeSerialNumber,- file_id: id.FileId.Identifier,+ volume,+ file_id,size: standard.EndOfFile,last_write: basic.LastWriteTime,attributes: basic.FileAttributes,@@ -68,6 +77,50 @@ pub(super) fn query_stamp(handle: &OwnedHandle) -> io::Result<FileStamp> {})}+fn query_identity(handle: &OwnedHandle) -> io::Result<(u64, FileIdentity)> {+ query_identity_with(handle, query::<FILE_ID_INFO>(handle, FileIdInfo))+}++fn query_identity_with(+ handle: &OwnedHandle,+ extended: io::Result<FILE_ID_INFO>,+) -> io::Result<(u64, FileIdentity)> {+ match extended {+ Ok(id) if id.FileId.Identifier != [0; 16] => Ok((+ id.VolumeSerialNumber,+ FileIdentity::Extended(id.FileId.Identifier),+ )),+ Ok(_) => Err(io::Error::new(+ io::ErrorKind::Unsupported,+ "filesystem returned an empty file identity",+ )),+ Err(error) if unsupported_information(os_code(&error)) => {+ // SMB 2.x and older NAS implementations expose 64-bit file indices.+ // Keep the identity namespace distinct from the 128-bit query.+ let mut info = BY_HANDLE_FILE_INFORMATION::default();+ if unsafe { GetFileInformationByHandle(handle.as_raw_handle(), &mut info) } == 0 {+ return Err(native_error(+ io::Error::last_os_error(),+ "GetFileInformationByHandle",+ None,+ ));+ }+ let id = (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow);+ if id == 0 {+ return Err(io::Error::new(+ io::ErrorKind::Unsupported,+ "filesystem returned an empty legacy file identity",+ ));+ }+ Ok((+ u64::from(info.dwVolumeSerialNumber),+ FileIdentity::Legacy(id),+ ))+ }+ Err(error) => Err(error),+ }+}+pub(super) fn snapshot_opened(handle: &OwnedHandle) -> io::Result<ArtifactSnapshot> {let stamp = query_stamp(handle)?;if stamp.directory {@@ -98,7 +151,7 @@ pub(super) fn ensure_named_entry(parent: &OwnedHandle,name: &[u16],) -> io::Result<()> {- let named = nt::open_existing(parent, name)?;+ let named = nt::open_metadata(parent, name)?;ensure_same_opened(opened, &named)}@@ -115,14 +168,14 @@ pub(super) fn ensure_same_opened(left: &OwnedHandle, right: &OwnedHandle) -> io:}pub(super) fn assert_name_absent(parent: &OwnedHandle, name: &[u16]) -> io::Result<()> {- match nt::open_existing(parent, name) {+ match nt::open_metadata(parent, name) {Ok(_) => Err(io::Error::new(io::ErrorKind::InvalidData,"Windows artifact name still exists after mutation",)),Err(error)if matches!(- error.raw_os_error(),+ os_code(&error),Some(code)if code == ERROR_FILE_NOT_FOUND as i32|| code == ERROR_PATH_NOT_FOUND as i32@@ -173,9 +226,9 @@ fn directory_names(directory: &OwnedHandle) -> io::Result<Vec<Vec<u16>>> {let mut restart = true;loop {let class = if restart {- FileIdExtdDirectoryRestartInfo+ FileFullDirectoryRestartInfo} else {- FileIdExtdDirectoryInfo+ FileFullDirectoryInfo};restart = false;let result = unsafe {@@ -188,16 +241,20 @@ fn directory_names(directory: &OwnedHandle) -> io::Result<Vec<Vec<u16>>> {};if result == 0 {let error = io::Error::last_os_error();- if error.raw_os_error() == Some(ERROR_NO_MORE_FILES as i32) {+ if os_code(&error) == Some(ERROR_NO_MORE_FILES as i32) {break;}- return Err(error);+ return Err(native_error(+ error,+ format!("GetFileInformationByHandleEx(class={class})"),+ None,+ ));}let mut offset = 0_usize;loop {let header_end = offset- .checked_add(offset_of!(FILE_ID_EXTD_DIR_INFO, FileName))+ .checked_add(offset_of!(FILE_FULL_DIR_INFO, FileName)).ok_or_else(|| {io::Error::new(io::ErrorKind::InvalidData, "directory entry overflow")})?;@@ -212,7 +269,7 @@ fn directory_names(directory: &OwnedHandle) -> io::Result<Vec<Vec<u16>>> {.as_ptr().cast::<u8>().add(offset)- .cast::<FILE_ID_EXTD_DIR_INFO>()+ .cast::<FILE_FULL_DIR_INFO>()};if entry.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {return Err(io::Error::new(@@ -274,7 +331,36 @@ fn query<T: Default>(handle: &OwnedHandle, class: i32) -> io::Result<T> {)};if result == 0 {- return Err(io::Error::last_os_error());+ return Err(native_error(+ io::Error::last_os_error(),+ format!("GetFileInformationByHandleEx(class={class})"),+ None,+ ));}Ok(output)}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn legacy_identity_fallback_is_stable_and_preserves_real_errors() {+ let file = std::fs::File::open(std::env::current_exe().unwrap()).unwrap();+ let handle: OwnedHandle = file.into();+ let first = query_identity_with(&handle, Err(io::Error::from_raw_os_error(50))).unwrap();+ let second = query_identity_with(&handle, Err(io::Error::from_raw_os_error(1))).unwrap();+ assert_eq!(first, second);+ assert!(matches!(first.1, FileIdentity::Legacy(id) if id != 0));+ for code in [5, 32, 53, 64, 112, 121, 1117] {+ assert_eq!(+ os_code(+ &query_identity_with(&handle, Err(io::Error::from_raw_os_error(code)))+ .unwrap_err()+ ),+ Some(code)+ );+ }+ assert!(query_identity_with(&handle, Ok(FILE_ID_INFO::default())).is_err());+ }+}diff --git a/packages/finalize-fs/src/platform/windows/mod.rs b/packages/finalize-fs/src/platform/windows/mod.rsindex 350722dc..83358170 100644--- a/packages/finalize-fs/src/platform/windows/mod.rs+++ b/packages/finalize-fs/src/platform/windows/mod.rs@@ -128,8 +128,13 @@ pub(crate) fn rename_no_replace(rename_opened_no_replace(&artifact, target, target_relative)}+#[cfg(test)]pub(crate) fn sync_root(root: &RootHandle) -> io::Result<()> {- nt::flush(&root.handle)+ sync_root_mode(root).map(|_| ())+}++pub(crate) fn sync_root_mode(root: &RootHandle) -> io::Result<&'static str> {+ nt::flush_directory(&root.handle)}fn open_parent(root: &OwnedHandle, parts: &[&str]) -> io::Result<(OwnedHandle, Vec<u16>)> {diff --git a/packages/finalize-fs/src/platform/windows/nt.rs b/packages/finalize-fs/src/platform/windows/nt.rsindex 93e8adbf..ffe5d22f 100644--- a/packages/finalize-fs/src/platform/windows/nt.rs+++ b/packages/finalize-fs/src/platform/windows/nt.rs@@ -1,5 +1,9 @@//! Thin, checked wrappers around the Windows native handle APIs we need.+use super::super::windows_policy::{+ is_online_smb2, remote_directory_acknowledged, unsupported_information,+};+use crate::error::{native_error, os_code};use std::ffi::{OsStr, c_void};use std::io;use std::mem::size_of;@@ -9,11 +13,12 @@ use std::path::Path;use windows_sys::Wdk::Foundation::OBJECT_ATTRIBUTES;use windows_sys::Wdk::Storage::FileSystem::{FILE_CREATE, FILE_DIRECTORY_FILE, FILE_DISPOSITION_DELETE,- FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE, FILE_DISPOSITION_INFORMATION_EX,- FILE_DISPOSITION_POSIX_SEMANTICS, FILE_INFORMATION_CLASS, FILE_NON_DIRECTORY_FILE, FILE_OPEN,- FILE_OPEN_FOR_BACKUP_INTENT, FILE_OPEN_REPARSE_POINT, FILE_RENAME_INFORMATION,- FILE_SYNCHRONOUS_IO_NONALERT, FileDispositionInformationEx, FileRenameInformation,- NtCreateFile, NtFlushBuffersFile, NtSetInformationFile,+ FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE, FILE_DISPOSITION_INFORMATION,+ FILE_DISPOSITION_INFORMATION_EX, FILE_DISPOSITION_POSIX_SEMANTICS, FILE_INFORMATION_CLASS,+ FILE_NON_DIRECTORY_FILE, FILE_OPEN, FILE_OPEN_FOR_BACKUP_INTENT, FILE_OPEN_REPARSE_POINT,+ FILE_RENAME_INFORMATION, FILE_SYNCHRONOUS_IO_NONALERT, FileDispositionInformation,+ FileDispositionInformationEx, FileRenameInformation, NtCreateFile, NtFlushBuffersFile,+ NtSetInformationFile,};use windows_sys::Win32::Foundation::{ERROR_DIRECTORY, HANDLE, OBJ_CASE_INSENSITIVE, OBJ_DONT_REPARSE, RtlNtStatusToDosError,@@ -22,9 +27,10 @@ use windows_sys::Win32::Foundation::{use windows_sys::Win32::Storage::FileSystem::{CreateFileW, DELETE, FILE_ACCESS_RIGHTS, FILE_APPEND_DATA, FILE_ATTRIBUTE_NORMAL,FILE_CASE_SENSITIVE_INFO, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,- FILE_LIST_DIRECTORY, FILE_READ_ATTRIBUTES, FILE_READ_DATA, FILE_SHARE_DELETE, FILE_SHARE_READ,- FILE_SHARE_WRITE, FILE_TRAVERSE, FILE_WRITE_ATTRIBUTES, FILE_WRITE_DATA, FileCaseSensitiveInfo,- GetFileInformationByHandleEx, OPEN_EXISTING, SYNCHRONIZE,+ FILE_LIST_DIRECTORY, FILE_READ_ATTRIBUTES, FILE_READ_DATA, FILE_REMOTE_PROTOCOL_INFO,+ FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_TRAVERSE, FILE_WRITE_ATTRIBUTES,+ FILE_WRITE_DATA, FileCaseSensitiveInfo, FileRemoteProtocolInfo, GetFileInformationByHandleEx,+ OPEN_EXISTING, SYNCHRONIZE,};use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;@@ -159,7 +165,7 @@ pub(super) fn open_existing(parent: &OwnedHandle, name: &[u16]) -> io::Result<OwOPEN_COMMON | FILE_DIRECTORY_FILE,) {Ok(handle) => Ok(handle),- Err(error) if error.raw_os_error() == Some(ERROR_DIRECTORY as i32) => nt_create(+ Err(error) if os_code(&error) == Some(ERROR_DIRECTORY as i32) => nt_create(parent,name,SOURCE_FILE_ACCESS,@@ -171,6 +177,20 @@ pub(super) fn open_existing(parent: &OwnedHandle, name: &[u16]) -> io::Result<Ow}}+pub(super) fn open_metadata(parent: &OwnedHandle, name: &[u16]) -> io::Result<OwnedHandle> {+ // Identity and absence checks must not probe a file with directory write+ // access. SMB checks sharing before the requested object type, so that+ // probe conflicts with our own held file's deliberate denial of write sharing.+ nt_create(+ parent,+ name,+ FILE_READ_ATTRIBUTES | SYNCHRONIZE,+ SHARE_ALL,+ FILE_OPEN,+ OPEN_COMMON,+ )+}+pub(super) fn open_existing_directory(parent: &OwnedHandle,name: &[u16],@@ -271,7 +291,7 @@ fn nt_create(0,)};- check_status(status)?;+ check_status(status, "NtCreateFile")?;if handle.is_null() {return Err(io::Error::other("NtCreateFile returned a null handle"));}@@ -340,18 +360,92 @@ pub(super) fn mark_delete(artifact: &OwnedHandle) -> io::Result<()> {| FILE_DISPOSITION_POSIX_SEMANTICS| FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE,};- set_information(+ match set_information(artifact,(&raw const disposition).cast(),size_of::<FILE_DISPOSITION_INFORMATION_EX>(),FileDispositionInformationEx,+ ) {+ Err(error) if unsupported_information(os_code(&error)) => {+ // Standard delete disposition keeps the file until all our held+ // handles close. The caller consumes its handle before checking absence.+ mark_delete_legacy(artifact)+ }+ result => result,+ }+}++pub(super) fn mark_delete_legacy(artifact: &OwnedHandle) -> io::Result<()> {+ let legacy = FILE_DISPOSITION_INFORMATION { DeleteFile: true };+ set_information(+ artifact,+ (&raw const legacy).cast(),+ size_of::<FILE_DISPOSITION_INFORMATION>(),+ FileDispositionInformation,)}pub(super) fn flush(handle: &OwnedHandle) -> io::Result<()> {let mut io_status = IO_STATUS_BLOCK::default();let status = unsafe { NtFlushBuffersFile(handle.as_raw_handle(), &mut io_status) };- check_status(status)+ check_status(status, "NtFlushBuffersFile")+}++/// Some SMB object stores reject directory FLUSH even though namespace changes+/// have been acknowledged. Only that precise capability failure uses the remote+/// acknowledgement contract; file flush, access and transport failures still fail.+pub(super) fn flush_directory(handle: &OwnedHandle) -> io::Result<&'static str> {+ match flush(handle) {+ Ok(()) => Ok("directory_flushed"),+ Err(error) => {+ let code = os_code(&error);+ if matches!(code, Some(1 | 50)) && remote_directory_acknowledged(code, is_smb2(handle)?)+ {+ Ok("remote_acknowledged")+ } else {+ Err(error)+ }+ }+ }+}++fn is_smb2(handle: &OwnedHandle) -> io::Result<bool> {+ // Native information queries on 64-bit Windows can require stricter+ // output alignment than this Win32 structure's individual fields. Also+ // initialize the versioned header required by FileRemoteProtocolInfo.+ #[repr(C, align(8))]+ struct AlignedProtocolInfo(FILE_REMOTE_PROTOCOL_INFO);+ let mut aligned = AlignedProtocolInfo(FILE_REMOTE_PROTOCOL_INFO {+ StructureVersion: 2,+ StructureSize: size_of::<FILE_REMOTE_PROTOCOL_INFO>() as u16,+ ..FILE_REMOTE_PROTOCOL_INFO::default()+ });+ let info = &mut aligned.0;+ let result = unsafe {+ GetFileInformationByHandleEx(+ handle.as_raw_handle(),+ FileRemoteProtocolInfo,+ (info as *mut FILE_REMOTE_PROTOCOL_INFO).cast(),+ size_of::<FILE_REMOTE_PROTOCOL_INFO>() as u32,+ )+ };+ if result == 0 {+ let error = io::Error::last_os_error();+ // Local volumes do not expose remote protocol information.+ if unsupported_information(error.raw_os_error()) {+ return Ok(false);+ }+ return Err(native_error(+ error,+ "GetFileInformationByHandleEx(FileRemoteProtocolInfo)",+ None,+ ));+ }+ Ok(is_online_smb2(+ info.Protocol,+ info.ProtocolMajorVersion,+ info.Flags,+ ))}fn set_information(@@ -372,13 +466,17 @@ fn set_information(class,)};- check_status(status)+ check_status(status, &format!("NtSetInformationFile(class={class})"))}-fn check_status(status: i32) -> io::Result<()> {+fn check_status(status: i32, operation: &str) -> io::Result<()> {if status >= 0 {return Ok(());}let error = unsafe { RtlNtStatusToDosError(status) };- Err(io::Error::from_raw_os_error(error as i32))+ Err(native_error(+ io::Error::from_raw_os_error(error as i32),+ operation,+ Some(status),+ ))}diff --git a/packages/finalize-fs/src/platform/windows/remove.rs b/packages/finalize-fs/src/platform/windows/remove.rsindex 76d0e5bb..fe3c03ef 100644--- a/packages/finalize-fs/src/platform/windows/remove.rs+++ b/packages/finalize-fs/src/platform/windows/remove.rs@@ -1,14 +1,13 @@use super::ArtifactHandle;use super::metadata::{- ArtifactSnapshot, assert_name_absent, ensure_named_entry, ensure_same_opened, ensure_snapshot,- snapshot_opened,+ ArtifactSnapshot, assert_name_absent, ensure_named_entry, ensure_snapshot, snapshot_opened,};use crate::path::validate_relative;use std::io;use std::os::windows::io::OwnedHandle;pub(crate) fn remove_opened(- artifact: &ArtifactHandle,+ artifact: ArtifactHandle,quarantine_relative: &str,resume_isolated: bool,) -> io::Result<()> {@@ -47,21 +46,16 @@ pub(crate) fn remove_opened(super::nt::rename_no_replace(&artifact.handle, &artifact.parent, &quarantine_name)?;ensure_named_entry(&artifact.handle, &artifact.parent, &quarantine_name)?;assert_name_absent(&artifact.parent, &artifact.name)?;- super::nt::flush(&artifact.parent)?;+ super::nt::flush_directory(&artifact.parent)?;}remove_snapshot_contents(&artifact.handle, snapshot)?;- // The admitted artifact handle intentionally outlives this operation. Mark- // a separately opened, identity-checked handle for POSIX deletion so that- // closing it unlinks the quarantine while the admitted handle remains a- // valid reference to the now-nameless artifact.- let deletion = super::nt::open_existing(&artifact.parent, &quarantine_name)?;- ensure_same_opened(&artifact.handle, &deletion)?;- ensure_named_entry(&deletion, &artifact.parent, &quarantine_name)?;- super::nt::mark_delete(&deletion)?;- drop(deletion);+ // Consume our admitted handle before testing absence. This also supports+ // SMB servers with standard delete-on-close but no POSIX disposition class.+ super::nt::mark_delete(&artifact.handle)?;+ drop(artifact.handle);assert_name_absent(&artifact.parent, &quarantine_name)?;- super::nt::flush(&artifact.parent)+ super::nt::flush_directory(&artifact.parent).map(|_| ())}fn remove_snapshot(handle: &OwnedHandle, expected: &ArtifactSnapshot) -> io::Result<()> {@@ -88,7 +82,7 @@ fn remove_snapshot_contents(handle: &OwnedHandle, expected: &ArtifactSnapshot) -));}}- super::nt::flush(handle)?;+ super::nt::flush_directory(handle)?;}Ok(())}diff --git a/packages/finalize-fs/src/platform/windows/tests.rs b/packages/finalize-fs/src/platform/windows/tests.rsindex 3ad5d1ad..f285d759 100644--- a/packages/finalize-fs/src/platform/windows/tests.rs+++ b/packages/finalize-fs/src/platform/windows/tests.rs@@ -71,25 +71,23 @@ fn copies_and_removes_a_held_directory_without_following_paths() {sync_root(&root).expect("flush held root");let copied = open_artifact(&root, "private-target").expect("open copied artifact");- remove_opened(&copied, ".motrix-remove", false).expect("remove held copied tree");+ remove_opened(copied, ".motrix-remove", false).expect("remove held copied tree");assert!(!scratch.path().join("private-target").exists());assert!(!scratch.path().join(".motrix-remove").exists());- drop(copied);}#[test]-fn removes_a_held_file_without_closing_its_admitted_handle() {+fn removes_a_held_file_by_consuming_its_admitted_handle() {let scratch = Scratch::new("remove-file");fs::write(scratch.path().join("payload.bin"), b"payload").expect("write payload");let root =open_root(scratch.path().to_str().expect("UTF-8 scratch path")).expect("open held root");let payload = open_artifact(&root, "payload.bin").expect("open payload artifact");- remove_opened(&payload, ".motrix-remove", false).expect("remove held payload");+ remove_opened(payload, ".motrix-remove", false).expect("remove held payload");assert!(!scratch.path().join("payload.bin").exists());assert!(!scratch.path().join(".motrix-remove").exists());- drop(payload);}#[test]@@ -162,7 +160,59 @@ fn rename_only_handles_use_metadata_and_do_not_authorize_removal() {let artifact = super::open_artifact_for_rename(&root, "source").unwrap();assert!(artifact.snapshot.is_none());assert!(copy_opened(&artifact, &root, "copy").is_err());- assert!(remove_opened(&artifact, ".quarantine", false).is_err());rename_opened_no_replace(&artifact, &root, "target").unwrap();+ assert!(remove_opened(artifact, ".quarantine", false).is_err());assert_eq!(fs::read(scratch.path().join("target")).unwrap(), b"payload");}++#[test]+fn classic_delete_finishes_after_the_admitted_handle_closes() {+ let scratch = Scratch::new("classic-delete");+ fs::write(scratch.path().join("payload.bin"), b"payload").unwrap();+ let root = open_root(scratch.path().to_str().unwrap()).unwrap();+ let artifact = open_artifact(&root, "payload.bin").unwrap();+ super::nt::mark_delete_legacy(&artifact.handle).unwrap();+ drop(artifact);+ assert!(!scratch.path().join("payload.bin").exists());+}++#[test]+#[ignore = "requires MOTRIX_FINALIZE_SMB_ROOT on a real SMB share"]+fn smb_share_supports_held_rename_copy_and_removal() {+ let share = std::env::var("MOTRIX_FINALIZE_SMB_ROOT").expect("SMB test root");+ let nonce = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ let scratch =+ Scratch(PathBuf::from(share).join(format!("finalize-{}-{nonce}", std::process::id())));+ fs::create_dir_all(scratch.path().join("tree/nested")).unwrap();+ fs::write(scratch.path().join("tree/nested/payload.bin"), b"payload").unwrap();+ fs::write(scratch.path().join("source.motrix"), b"complete").unwrap();+ let root = open_root(scratch.path().to_str().unwrap()).unwrap();+ let artifact = super::open_artifact_for_rename(&root, "source.motrix").unwrap();+ assert!(+ fs::OpenOptions::new()+ .write(true)+ .open(scratch.path().join("source.motrix"))+ .is_err(),+ "holding an SMB file must continue to exclude content writers"+ );+ rename_opened_no_replace(&artifact, &root, "complete.bin").unwrap();+ sync_root(&root).unwrap();+ drop(artifact);+ assert_eq!(+ fs::read(scratch.path().join("complete.bin")).unwrap(),+ b"complete"+ );+ assert!(!scratch.path().join("source.motrix").exists());+ let tree = open_artifact(&root, "tree").unwrap();+ assert!(rename_opened_no_replace(&tree, &root, "complete.bin").is_err());+ copy_opened(&tree, &root, "copied-tree").unwrap();+ let copied = open_artifact(&root, "copied-tree").unwrap();+ remove_opened(copied, ".remove-copied", false).unwrap();+ remove_opened(tree, ".remove-tree", false).unwrap();+ let complete = open_artifact(&root, "complete.bin").unwrap();+ remove_opened(complete, ".remove-file", false).unwrap();+ assert_eq!(fs::read_dir(scratch.path()).unwrap().count(), 0);+}diff --git a/packages/finalize-fs/src/platform/windows_policy.rs b/packages/finalize-fs/src/platform/windows_policy.rsnew file mode 100644index 00000000..826d3ac3--- /dev/null+++ b/packages/finalize-fs/src/platform/windows_policy.rs@@ -0,0 +1,54 @@+//! Narrow Windows compatibility decisions, also tested on non-Windows hosts.++pub(super) fn unsupported_information(code: Option<i32>) -> bool {+ // INVALID_FUNCTION, NOT_SUPPORTED, INVALID_PARAMETER, CALL_NOT_IMPLEMENTED,+ // INVALID_LEVEL. Sharing, permissions, disconnection and I/O are not fallbacks.+ matches!(code, Some(1 | 50 | 87 | 120 | 124))+}++pub(super) fn remote_directory_acknowledged(code: Option<i32>, smb2: bool) -> bool {+ smb2 && matches!(code, Some(1 | 50))+}++pub(super) fn is_online_smb2(protocol: u32, major: u16, flags: u32) -> bool {+ // WNNC_NET_SMB and REMOTE_PROTOCOL_INFO_FLAG_OFFLINE. A client-side+ // offline cache cannot attest that a remote server acknowledged a mutation.+ protocol == 0x0002_0000 && major >= 2 && flags & 0x2 == 0+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn remote_acknowledgement_requires_online_smb2_or_newer() {+ assert!(is_online_smb2(0x0002_0000, 2, 0));+ assert!(is_online_smb2(0x0002_0000, 3, 0x11));+ assert!(!is_online_smb2(0x0002_0000, 3, 0x2));+ assert!(!is_online_smb2(0x0002_0000, 1, 0));+ assert!(!is_online_smb2(0x0007_0000, 3, 0));+ }++ #[test]+ fn only_smb_directory_unsupported_errors_allow_server_acknowledgement() {+ for code in [1, 50] {+ assert!(remote_directory_acknowledged(Some(code), true));+ assert!(!remote_directory_acknowledged(Some(code), false));+ }+ for code in [5, 32, 53, 64, 87, 112, 121, 995, 1117] {+ assert!(!remote_directory_acknowledged(Some(code), true));+ }+ assert!(!remote_directory_acknowledged(None, true));+ }++ #[test]+ fn metadata_fallback_does_not_mask_operational_errors() {+ for code in [1, 50, 87, 120, 124] {+ assert!(unsupported_information(Some(code)));+ }+ for code in [5, 32, 53, 64, 112, 121, 995, 1117] {+ assert!(!unsupported_information(Some(code)));+ }+ assert!(!unsupported_information(None));+ }+}diff --git a/packages/finalize-fs/src/protocol.rs b/packages/finalize-fs/src/protocol.rsindex 4e0355d2..78ffd7c1 100644--- a/packages/finalize-fs/src/protocol.rs+++ b/packages/finalize-fs/src/protocol.rs@@ -55,6 +55,22 @@ pub(crate) enum Request {},}+impl Request {+ pub(crate) fn operation(&self) -> &'static str {+ match self {+ Self::Capabilities => "capabilities",+ Self::OpenRoot { .. } => "open_root",+ Self::OpenArtifact { .. } => "open_artifact",+ Self::RenameOpenedNoReplace { .. } => "rename_opened_no_replace",+ Self::CopyOpened { .. } => "copy_opened",+ Self::RenameNoReplace { .. } => "rename_no_replace",+ Self::RemoveOpened { .. } => "remove_opened",+ Self::SyncRoot { .. } => "sync_root",+ Self::Close { .. } => "close",+ }+ }+}+#[derive(Serialize)]pub(crate) struct Response<'a> {request_id: Option<u64>,@@ -75,6 +91,14 @@ pub(crate) struct Response<'a> {pub(crate) directory_sync: Option<bool>,#[serde(skip_serializing_if = "Option::is_none")]pub(crate) held_artifacts: Option<bool>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub(crate) operation: Option<&'static str>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub(crate) directory_sync_mode: Option<&'static str>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub(crate) os_error: Option<i32>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub(crate) nt_status: Option<String>,}impl<'a> Response<'a> {@@ -90,9 +114,24 @@ impl<'a> Response<'a> {held_roots: None,directory_sync: None,held_artifacts: None,+ operation: None,+ directory_sync_mode: None,+ os_error: None,+ nt_status: None,}}+ pub(crate) fn filesystem_error(request_id: u64, error: io::Error) -> Self {+ let mut response = Self::error(+ Some(request_id),+ crate::error::classify_error(&error),+ &error,+ );+ response.os_error = crate::error::os_code(&error);+ response.nt_status = crate::error::nt_status(&error);+ response+ }+pub(crate) fn error(request_id: Option<u64>, code: &'a str, error: impl ToString) -> Self {let mut response = Self::ok(request_id);response.status = "error";diff --git a/packages/finalize-fs/src/state.rs b/packages/finalize-fs/src/state.rsindex e36e737b..981882e2 100644--- a/packages/finalize-fs/src/state.rs+++ b/packages/finalize-fs/src/state.rs@@ -1,9 +1,8 @@//! Handle registry and request dispatch, independent of platform syscalls.-use crate::error::classify_error;use crate::platform::{ArtifactHandle, RootHandle, copy_opened, open_artifact, open_artifact_for_rename, open_root,- remove_opened, rename_no_replace, rename_opened_no_replace, sync_root,+ remove_opened, rename_no_replace, rename_opened_no_replace, sync_root_mode,};use crate::protocol::{Request, Response};use std::collections::HashMap;@@ -11,7 +10,7 @@ use std::collections::HashMap;pub(crate) struct State {next_handle: u64,roots: HashMap<u64, RootHandle>,- artifacts: HashMap<u64, ArtifactHandle>,+ artifacts: HashMap<u64, Option<ArtifactHandle>>,}impl State {@@ -24,6 +23,13 @@ impl State {}pub(crate) fn handle(&mut self, request: Request) -> Response<'static> {+ let operation = request.operation();+ let mut response = self.dispatch(request);+ response.operation = Some(operation);+ response+ }++ fn dispatch(&mut self, request: Request) -> Response<'static> {match request {Request::Capabilities => self.capabilities(),Request::OpenRoot { request_id, path } => match open_root(&path) {@@ -33,7 +39,7 @@ impl State {response.handle = Some(handle);response}- Err(error) => Response::error(Some(request_id), classify_error(&error), error),+ Err(error) => Response::filesystem_error(request_id, error),},Request::OpenArtifact {request_id,@@ -56,7 +62,7 @@ impl State {response.handle = Some(handle);response}- Err(error) => Response::error(Some(request_id), classify_error(&error), error),+ Err(error) => Response::filesystem_error(request_id, error),}}Request::RenameOpenedNoReplace {@@ -65,7 +71,7 @@ impl State {target_root,target_relative,} => {- let Some(artifact) = self.artifacts.get(&artifact) else {+ let Some(artifact) = self.artifacts.get(&artifact).and_then(Option::as_ref) else {return Response::error(Some(request_id), "invalid_handle", "unknown artifact");};let Some(target) = self.roots.get(&target_root) else {@@ -86,7 +92,7 @@ impl State {target_root,target_relative,} => {- let Some(artifact) = self.artifacts.get(&artifact) else {+ let Some(artifact) = self.artifacts.get(&artifact).and_then(Option::as_ref) else {return Response::error(Some(request_id), "invalid_handle", "unknown artifact");};let Some(target) = self.roots.get(&target_root) else {@@ -130,19 +136,31 @@ impl State {quarantine_relative,resume_isolated,} => {- let Some(artifact) = self.artifacts.get(&artifact) else {+ let Some(artifact) = self.artifacts.get_mut(&artifact).and_then(Option::take)+ else {return Response::error(Some(request_id), "invalid_handle", "unknown artifact");};- operation_response(- request_id,- remove_opened(artifact, &quarantine_relative, resume_isolated),- )+ // Removal consumes the held handle so classic SMB delete-on-close+ // can finish. Keep its empty registry slot until the caller closes it.+ #[cfg(windows)]+ let result = remove_opened(artifact, &quarantine_relative, resume_isolated);+ #[cfg(not(windows))]+ let result = remove_opened(&artifact, &quarantine_relative, resume_isolated);+ operation_response(request_id, result)}+Request::SyncRoot { request_id, root } => {let Some(root) = self.roots.get(&root) else {return Response::error(Some(request_id), "invalid_handle", "unknown root");};- operation_response(request_id, sync_root(root))+ match sync_root_mode(root) {+ Ok(mode) => {+ let mut response = Response::ok(Some(request_id));+ response.directory_sync_mode = Some(mode);+ response+ }+ Err(error) => Response::filesystem_error(request_id, error),+ }}Request::Close { request_id, handle } => {if self.roots.remove(&handle).is_some() || self.artifacts.remove(&handle).is_some()@@ -180,7 +198,7 @@ impl State {fn insert_artifact(&mut self, artifact: ArtifactHandle) -> u64 {let handle = self.next_handle();- self.artifacts.insert(handle, artifact);+ self.artifacts.insert(handle, Some(artifact));handle}}@@ -188,7 +206,7 @@ impl State {fn operation_response(request_id: u64, result: std::io::Result<()>) -> Response<'static> {match result {Ok(()) => Response::ok(Some(request_id)),- Err(error) => Response::error(Some(request_id), classify_error(&error), error),+ Err(error) => Response::filesystem_error(request_id, error),}}diff --git a/src/core/plugin/finalize/artifact-identity-errors.test.ts b/src/core/plugin/finalize/artifact-identity-errors.test.tsnew file mode 100644index 00000000..705eca7f--- /dev/null+++ b/src/core/plugin/finalize/artifact-identity-errors.test.ts@@ -0,0 +1,47 @@+import { lstat, open } from 'node:fs/promises'+import { describe, expect, it, vi } from 'vitest'+import { readArtifactIdentity } from './artifact-identity'++vi.mock('node:fs/promises', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:fs/promises')>()+ const lstat = vi.fn(actual.lstat)+ const open = vi.fn(actual.open)+ return { ...actual, default: { ...actual, lstat, open }, lstat, open }+})++describe('artifact identity I/O errors', () => {+ it.each(['EACCES', 'EIO', 'ETIMEDOUT', 'ELOOP'])(+ 'does not treat lstat %s as a missing file',+ async (code) => {+ const error = Object.assign(new Error(code), { code })+ vi.mocked(lstat).mockRejectedValueOnce(error)+ await expect(readArtifactIdentity('/unavailable/file')).rejects.toBe(+ error+ )+ }+ )++ it.each(['EACCES', 'EIO', 'ETIMEDOUT', 'ELOOP'])(+ 'does not treat open %s as a missing file',+ async (code) => {+ const error = Object.assign(new Error(code), { code })+ vi.mocked(lstat).mockResolvedValueOnce({+ isSymbolicLink: () => false,+ isFile: () => true,+ } as Awaited<ReturnType<typeof lstat>>)+ vi.mocked(open).mockRejectedValueOnce(error)+ await expect(readArtifactIdentity('/unavailable/file')).rejects.toBe(+ error+ )+ }+ )++ it('still classifies ENOENT as a missing artifact', async () => {+ vi.mocked(lstat).mockRejectedValueOnce(+ Object.assign(new Error('missing'), { code: 'ENOENT' })+ )+ await expect(readArtifactIdentity('/missing/file')).rejects.toMatchObject({+ code: 'artifact_missing',+ })+ })+})diff --git a/src/core/plugin/finalize/artifact-identity.ts b/src/core/plugin/finalize/artifact-identity.tsindex b1bf9d1c..95f68997 100644--- a/src/core/plugin/finalize/artifact-identity.ts+++ b/src/core/plugin/finalize/artifact-identity.ts@@ -89,6 +89,7 @@ async function identityForFile(try {handle = await open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW)} catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw errorthrow new ArtifactIdentityError('artifact_missing',`cannot open artifact without following links: ${filePath}`,@@ -204,6 +205,7 @@ export async function readArtifactIdentity(options: ArtifactIdentityOptions = {}): Promise<ArtifactIdentity> {const root = await lstat(artifactPath, { bigint: true }).catch((error) => {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw errorthrow new ArtifactIdentityError('artifact_missing',`artifact does not exist: ${artifactPath}`,diff --git a/src/core/plugin/finalize/filesystem-adapter.test.ts b/src/core/plugin/finalize/filesystem-adapter.test.tsindex 2b48732b..f2bf73ba 100644--- a/src/core/plugin/finalize/filesystem-adapter.test.ts+++ b/src/core/plugin/finalize/filesystem-adapter.test.ts@@ -50,6 +50,11 @@ 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.relative === 'unsupported' ? {+ status: 'error', code: 'unsupported',+ operation: request.op, os_error: 1, nt_status: '0xc0000010',+ message: 'NtCreateFile: Incorrect function. (os error 1)',+ } : {}),}))const frame = Buffer.alloc(payload.length + 4)frame.writeUInt32LE(payload.length)@@ -113,6 +118,28 @@ describe.runIf(process.platform !== 'win32')(await expect(adapter.capabilities()).rejects.toThrow('disposed')})+ it('preserves the native operation and status across the sidecar protocol', async () => {+ const adapter = new NativeFinalizeFilesystemAdapter(await framedSidecar())+ try {+ const root = await adapter.openRoot(os.tmpdir())+ await expect(+ adapter.openArtifact(root, 'unsupported')+ ).rejects.toMatchObject({+ name: 'FinalizeFsError',+ code: 'unsupported',+ message:+ 'open_artifact: NtCreateFile: Incorrect function. (os error 1)',+ details: {+ operation: 'open_artifact',+ osError: 1,+ ntStatus: '0xc0000010',+ },+ })+ } finally {+ await adapter.dispose()+ }+ })+async function rejectedError(operation: Promise<unknown>): Promise<Error> {let caught: unknowntry {diff --git a/src/core/plugin/finalize/filesystem-adapter.ts b/src/core/plugin/finalize/filesystem-adapter.tsindex df1686a0..a82dca5f 100644--- a/src/core/plugin/finalize/filesystem-adapter.ts+++ b/src/core/plugin/finalize/filesystem-adapter.ts@@ -1,5 +1,6 @@import { type ChildProcessWithoutNullStreams, spawn } from 'node:child_process'import path from 'node:path'+import { getLogger } from '@core/logger'export type FinalizeFsErrorCode =| 'unsupported'@@ -15,7 +16,12 @@ export type FinalizeFsErrorCode =export class FinalizeFsError extends Error {constructor(readonly code: FinalizeFsErrorCode,- message: string+ message: string,+ readonly details?: {+ operation?: string+ osError?: number+ ntStatus?: string+ }) {super(message)this.name = 'FinalizeFsError'@@ -36,6 +42,10 @@ interface WireResponse {handle?: numbercode?: FinalizeFsErrorCodemessage?: string+ operation?: string+ os_error?: number+ nt_status?: string+ directory_sync_mode?: 'directory_flushed' | 'remote_acknowledged'platform?: stringrename_no_replace?: booleanheld_roots?: boolean@@ -108,6 +118,7 @@ export class NativeFinalizeFilesystemAdapterprivate readonly pending = new Map<number, PendingRequest>()private readonly requestTimeoutMs: numberprivate deadError: Error | null = null+ private remoteDurabilityReported = falseconstructor(private readonly binaryPath: string,@@ -261,7 +272,20 @@ export class NativeFinalizeFilesystemAdapter}async syncRoot(root: FinalizeRootHandle): Promise<void> {- await this.request({ op: 'sync_root', root: this.nativeId(root) })+ const response = 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(@@ -353,7 +377,12 @@ export class NativeFinalizeFilesystemAdapterif (result.status === 'error') {throw new FinalizeFsError(result.code ?? 'io_error',- result.message ?? 'finalize filesystem operation failed'+ `${result.operation ?? body.op}: ${result.message ?? 'finalize filesystem operation failed'}`,+ {+ operation: result.operation ?? String(body.op),+ osError: result.os_error,+ ntStatus: result.nt_status,+ })}return resultdiff --git a/src/core/plugin/finalize/finalize-committer.test.ts b/src/core/plugin/finalize/finalize-committer.test.tsindex b634cd9b..01c1a81d 100644--- a/src/core/plugin/finalize/finalize-committer.test.ts+++ b/src/core/plugin/finalize/finalize-committer.test.ts@@ -142,6 +142,23 @@ function makeCommitter(}describe('FinalizeCommitter', () => {+ it('does not compensate a different journal when prepare rejects the retry', async () => {+ const fs = new FakeFilesystem()+ const plan = makePlan()+ fs.artifacts.set(plan.sourcePath, sourceIdentity)+ fs.artifacts.set(plan.targetPath, sourceIdentity)+ const { repository } = makeRepository()+ repository.prepare = vi+ .fn()+ .mockRejectedValue(new Error('old journal still pending'))+ await expect(makeCommitter(fs, repository).commit(plan)).rejects.toThrow(+ 'old journal still pending'+ )+ expect(fs.actions).toEqual([])+ expect(fs.artifacts.get(plan.targetPath)).toBe(sourceIdentity)+ expect(fs.artifacts.get(plan.sourcePath)).toBe(sourceIdentity)+ })+it('moves an ordinary same-filesystem source without copying it', async () => {const fs = new FakeFilesystem()const plan = makePlan()diff --git a/src/core/plugin/finalize/finalize-committer.ts b/src/core/plugin/finalize/finalize-committer.tsindex 65962ad6..3de76af1 100644--- a/src/core/plugin/finalize/finalize-committer.ts+++ b/src/core/plugin/finalize/finalize-committer.ts@@ -5,6 +5,7 @@ import type {ArtifactMutationLease,ArtifactMutationLeaseCoordinator,} from './artifact-mutation-lease'+import { FinalizeRecovery } from './finalize-recovery'import { assertValidHookPlan, type HookPlan } from './hook-plan'export type FinalizeJournalPhase =@@ -66,10 +67,13 @@ export interface FinalizeJournalRepository {): Promise<void>commitTerminal(record: FinalizeJournalRecord): Promise<void>quarantine(journalId: string, reason: string): Promise<void>- listRecoverable(): Promise<FinalizeJournalRecord[]>+ listRecoverable(taskId?: string): Promise<FinalizeJournalRecord[]>+ resumeQuarantined?(record: FinalizeJournalRecord): Promise<void>}export interface FinalizeArtifactOperations {+ /** Validate the actual roots and flush source data before journaled mutation. */+ preflight?(sourcePath: string, targetPath: string): Promise<void>identity(artifactPath: string): Promise<ArtifactIdentity | null>sameFilesystem(leftPath: string, rightPath: string): Promise<boolean>materializePrivate(@@ -135,6 +139,7 @@ export class FinalizeCommitter {plan,publicationMode: 'copy',}+ let prepared = falsetry {await this.requireExactIdentity(plan.sourcePath,@@ -149,11 +154,16 @@ export class FinalizeCommitter {)}record.publicationMode = await this.selectPublicationMode(plan)+ await this.options.fs.preflight?.(+ plan.replacement?.stagedPath ?? plan.sourcePath,+ plan.targetPath+ )await this.options.repository.prepare(record)+ prepared = truereturn await this.commitPrepared(record, lease)} catch (error) {if (error instanceof FinalizeQuarantinedError) throw error- await this.compensate(record, lease, error)+ if (prepared) await this.compensate(record, lease, error)throw error} finally {if (ownsLease) await lease.release()@@ -317,87 +327,34 @@ export class FinalizeCommitter {private async compensate(record: FinalizeJournalRecord,- _lease: ArtifactMutationLease,+ lease: ArtifactMutationLease,cause: unknown): Promise<void> {if (record.phase === 'db_committed' || record.phase === 'cleaned') returntry {- const movesSource = record.publicationMode === 'move'- const installedIdentity =- record.targetIdentity ??- record.privateTargetIdentity ??- (movesSource ? record.plan.sourceIdentity : undefined)- const target = await this.options.fs.identity(record.plan.targetPath)- if (- target &&- installedIdentity &&- this.options.exactIdentity(target, installedIdentity)- ) {- if (movesSource) {- await this.options.fs.moveNoReplace(- record.plan.targetPath,- installedIdentity,- record.plan.sourcePath- )- await this.options.fs.makeDurable(record.plan.sourcePath)- } else {- await this.removeTracked(- record,- record.plan.targetPath,- installedIdentity- )- }- } else if (target) {- await this.quarantine(record, 'compensation target identity mismatch')- }- if (record.rollbackPath) {- await this.requireExactIdentity(- record.rollbackPath,- record.plan.sourceIdentity,- record- )- await this.options.fs.moveNoReplace(- record.rollbackPath,- record.plan.sourceIdentity,- record.plan.sourcePath- )- await this.options.fs.makeDurable(record.plan.sourcePath)- }- if (record.privateTargetPath) {- const privateTarget = await this.options.fs.identity(- record.privateTargetPath- )- if (privateTarget) {- const expectedPrivate = record.privateTargetIdentity- const selected =- record.plan.replacement?.identity ?? record.plan.sourceIdentity- if (- expectedPrivate- ? !this.options.exactIdentity(privateTarget, expectedPrivate)- : !this.options.sameContent(privateTarget, selected)- ) {- await this.quarantine(- record,- 'compensation private target identity mismatch'- )- }- await this.removeTracked(- record,- record.privateTargetPath,- expectedPrivate ?? privateTarget- )- }- }+ // Live rollback and startup recovery must make the same identity checks,+ // and only mark the journal cleaned after the rollback is durable.+ await new FinalizeRecovery({+ ...this.options,+ rollForwardTargetInstalled: false,+ }).recover(record, lease)} catch (compensationError) {- await this.options.repository.quarantine(- record.journalId,- `compensation failed after ${String(cause)}: ${String(compensationError)}`- )- throw new FinalizeQuarantinedError(- record.journalId,- 'compensation failed',- { cause: compensationError }+ const failures = new AggregateError(+ [cause, compensationError],+ 'finalize failed and rollback needs recovery')+ if (compensationError instanceof FinalizeQuarantinedError) {+ throw new FinalizeQuarantinedError(+ record.journalId,+ compensationError.reason,+ {+ cause: failures,+ }+ )+ }+ // I/O and connectivity failures retain the journal's last checkpoint.+ // Recovery rechecks both names; only identity conflicts are quarantined.+ throw failures}}diff --git a/src/core/plugin/finalize/finalize-recovery.test.ts b/src/core/plugin/finalize/finalize-recovery.test.tsindex 9e9620a6..618b6690 100644--- a/src/core/plugin/finalize/finalize-recovery.test.ts+++ b/src/core/plugin/finalize/finalize-recovery.test.ts@@ -377,6 +377,8 @@ describe('FinalizeRecovery', () => {expect(state.artifacts.get('/save/.motrix-finalize-remove-persisted')).toBe(unknown)- expect(state.quarantines[0]).toContain('persisted removal intent failed')+ expect(state.quarantines[0]).toContain(+ 'persisted removal intent identity mismatch'+ )})})diff --git a/src/core/plugin/finalize/finalize-recovery.ts b/src/core/plugin/finalize/finalize-recovery.tsindex ed39be11..3800633b 100644--- a/src/core/plugin/finalize/finalize-recovery.ts+++ b/src/core/plugin/finalize/finalize-recovery.ts@@ -1,4 +1,7 @@-import type { ArtifactMutationLeaseCoordinator } from './artifact-mutation-lease'+import type {+ ArtifactMutationLease,+ ArtifactMutationLeaseCoordinator,+} from './artifact-mutation-lease'import {type FinalizeArtifactOperations,type FinalizeJournalRecord,@@ -40,10 +43,44 @@ export class FinalizeRecovery {}}- async recover(record: FinalizeJournalRecord): Promise<void> {- const lease = await this.options.leases.acquire(record.plan.taskId)+ async recoverTask(+ taskId: string,+ lease: ArtifactMutationLease+ ): Promise<void> {+ for (const record of await this.options.repository.listRecoverable(+ taskId+ )) {+ await this.recover(record, lease)+ }+ }++ async recover(+ record: FinalizeJournalRecord,+ existingLease?: ArtifactMutationLease+ ): Promise<void> {+ const lease =+ existingLease ?? (await this.options.leases.acquire(record.plan.taskId))try {- if (record.quarantineReason) return+ if (record.quarantineReason) {+ if (!this.options.repository.resumeQuarantined) return+ // Legacy compensation failures can be reopened only for an ordinary+ // move with exactly one surviving, identity-verified name.+ if (!isRetryableMoveQuarantine(record)) return+ const source = await this.options.fs.identity(record.plan.sourcePath)+ const target = await this.options.fs.identity(record.plan.targetPath)+ const surviving = source ?? target+ if (+ !surviving ||+ Boolean(source) === Boolean(target) ||+ !this.options.exactIdentity(surviving, record.plan.sourceIdentity)+ )+ return+ await this.options.fs.makeDurable(+ source ? record.plan.sourcePath : record.plan.targetPath+ )+ await this.options.repository.resumeQuarantined(record)+ record.quarantineReason = undefined+ }await this.resumeRemovalIntent(record)const selected =record.plan.replacement?.identity ?? record.plan.sourceIdentity@@ -186,7 +223,7 @@ export class FinalizeRecovery {return}} finally {- await lease.release()+ if (!existingLease) await lease.release()}}@@ -332,6 +369,7 @@ export class FinalizeRecovery {if (!this.options.exactIdentity(source, record.plan.sourceIdentity)) {await this.quarantine(record, 'moved source identity mismatch')}+ await this.options.fs.makeDurable(record.plan.sourcePath)await this.options.repository.advance(record.journalId, 'cleaned')return}@@ -424,22 +462,27 @@ export class FinalizeRecovery {): Promise<void> {const intent = record.removalIntentif (!intent) return- try {- await this.options.fs.removeKnown(- intent.artifactPath,- intent.identity,- intent.quarantinePath- )- record.removalIntent = undefined- await this.options.repository.checkpoint(record.journalId, {- removalIntent: undefined,- })- } catch (error) {+ const original = await this.options.fs.identity(intent.artifactPath)+ const quarantined = await this.options.fs.identity(intent.quarantinePath)+ if (+ (original && quarantined) ||+ (original && !this.options.exactIdentity(original, intent.identity)) ||+ (quarantined && !this.options.exactIdentity(quarantined, intent.identity))+ ) {await this.quarantine(record,- `persisted removal intent failed: ${error instanceof Error ? error.message : String(error)}`+ 'persisted removal intent identity mismatch')}+ await this.options.fs.removeKnown(+ intent.artifactPath,+ intent.identity,+ intent.quarantinePath+ )+ record.removalIntent = undefined+ await this.options.repository.checkpoint(record.journalId, {+ removalIntent: undefined,+ })}private async removeTracked(@@ -475,3 +518,21 @@ export class FinalizeRecovery {throw new FinalizeQuarantinedError(record.journalId, reason)}}++/** Only the old blanket compensation quarantine is eligible for automatic retry. */+export function isRetryableMoveQuarantine(+ record: FinalizeJournalRecord+): boolean {+ return (+ record.quarantineReason?.startsWith('compensation failed after ') ===+ true &&+ record.publicationMode === 'move' &&+ (record.phase === 'prepared' || record.phase === 'target_installed') &&+ !record.plan.replacement &&+ !record.privateTargetPath &&+ !record.privateTargetIdentity &&+ !record.rollbackPath &&+ !record.removalIntent &&+ !finalizePathsEquivalent(record.plan.sourcePath, record.plan.targetPath)+ )+}diff --git a/src/core/plugin/finalize/finalize-smb-recovery.integration.test.ts b/src/core/plugin/finalize/finalize-smb-recovery.integration.test.tsnew file mode 100644index 00000000..bb9a144a--- /dev/null+++ b/src/core/plugin/finalize/finalize-smb-recovery.integration.test.ts@@ -0,0 +1,263 @@+import { existsSync } from 'node:fs'+import { mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { DurableFinalizeRuntime } from '@core/session/durable-finalize-runtime'+import { SqliteFinalizeJournalRepository } from '@core/session/finalize-journal-repository'+import { migrate } from '@core/session/migrations'+import { makeDownloadTask } from '@test-utils/task'+import Database from 'better-sqlite3'+import { afterEach, describe, expect, it, vi } from 'vitest'+import {+ FinalizeFsError,+ NativeFinalizeFilesystemAdapter,+} from './filesystem-adapter'+import type { FinalizeJournalRecord } from './finalize-committer'+import { NativeFinalizeArtifactOperations } from './native-artifact-operations'++const binary = path.resolve(+ process.env.MOTRIX_FINALIZE_FS_TEST_BIN ??+ path.join(+ 'packages/finalize-fs/target/debug',+ process.platform === 'win32'+ ? 'motrix-finalize-fs.exe'+ : 'motrix-finalize-fs'+ )+)++describe.runIf(existsSync(binary))('SMB finalize failure recovery', () => {+ const cleanup: (() => Promise<void>)[] = []+ afterEach(async () => {+ vi.restoreAllMocks()+ for (const dispose of cleanup.splice(0)) await dispose()+ })++ async function setup() {+ const root = await realpath(+ await mkdtemp(path.join(os.tmpdir(), 'motrix-smb-recovery-'))+ )+ const adapter = new NativeFinalizeFilesystemAdapter(binary)+ const fs = new NativeFinalizeArtifactOperations(adapter)+ const db = new Database(':memory:')+ migrate(db)+ cleanup.push(async () => {+ await adapter.dispose()+ db.close()+ await rm(root, { recursive: true, force: true })+ })+ const sourcePath = path.join(root, 'download.bin.motrix')+ const targetPath = path.join(root, 'download.bin')+ await writeFile(sourcePath, 'complete download')+ const input = {+ task: makeDownloadTask({+ id: 'task-smb',+ saveDir: root,+ diskPath: sourcePath,+ finalPath: targetPath,+ }),+ occurrence: null,+ sourcePath,+ targetPath,+ metadataOps: [],+ contributors: [],+ postDeliveries: [],+ }+ const runtime = new DurableFinalizeRuntime({+ db,+ fs,+ session: {+ persistFinalizedArtifact: async (+ _task,+ _occurrence,+ _effects,+ commit+ ) =>+ commit((journal) => {+ const raw = db+ .prepare(+ 'SELECT plan_json FROM plugin_finalize_journals WHERE plan_id=?'+ )+ .get(journal.journalId) as { plan_json: string }+ db.prepare(+ "UPDATE plugin_finalize_journals SET phase='db_committed', plan_json=? WHERE plan_id=?"+ ).run(+ JSON.stringify({+ ...JSON.parse(raw.plan_json),+ phase: 'db_committed',+ }),+ journal.journalId+ )+ }),+ },+ })+ const repository = new SqliteFinalizeJournalRepository(db, {+ commitTerminalBoundary: () => {+ throw new Error('not used')+ },+ })+ const row = () =>+ db+ .prepare(+ 'SELECT phase, quarantine_reason FROM plugin_finalize_journals'+ )+ .get()+ async function legacyJournal(targetInstalled = false) {+ const sourceIdentity = await fs.identity(sourcePath)+ if (!sourceIdentity) throw new Error('missing fixture')+ const record: FinalizeJournalRecord = {+ journalId: 'legacy-plan',+ phase: 'prepared',+ publicationMode: 'move',+ plan: {+ planId: 'legacy-plan',+ taskId: input.task.id,+ saveDir: root,+ sourcePath,+ targetPath,+ sourceIdentity,+ metadataOps: [],+ contributors: [],+ },+ }+ await repository.prepare(record)+ if (targetInstalled)+ await fs.moveNoReplace(sourcePath, sourceIdentity, targetPath)+ await repository.quarantine(+ record.journalId,+ 'compensation failed after FinalizeFsError: Incorrect function. (os error 1): FinalizeFsError: Incorrect function. (os error 1)'+ )+ return record+ }+ return {+ adapter,+ db,+ fs,+ root,+ runtime,+ repository,+ input,+ row,+ legacyJournal,+ }+ }++ it('rejects unsupported roots before creating a journal or renaming the download', async () => {+ const s = await setup()+ vi.spyOn(s.adapter, 'syncRoot').mockRejectedValue(+ new FinalizeFsError('unsupported', 'directory flush unsupported')+ )+ const rename = vi.spyOn(s.adapter, 'renameOpenedNoReplace')+ await expect(s.runtime.commit(s.input)).rejects.toThrow(+ 'directory flush unsupported'+ )+ expect(s.row()).toBeUndefined()+ expect(rename).not.toHaveBeenCalled()+ expect(await readFile(s.input.sourcePath, 'utf8')).toBe('complete download')+ })++ it('retains both I/O errors and retries a failed rollback without restarting', async () => {+ const s = await setup()+ const realSync = s.adapter.syncRoot.bind(s.adapter)+ let calls = 0+ const injected = vi+ .spyOn(s.adapter, 'syncRoot')+ .mockImplementation(async (root) => {+ if (++calls >= 3)+ throw new FinalizeFsError('io_error', `sync failure ${calls}`)+ await realSync(root)+ })+ const rename = vi.spyOn(s.adapter, 'renameOpenedNoReplace')+ const failure = await s.runtime+ .commit(s.input)+ .catch((error: unknown) => error)+ expect(failure).toBeInstanceOf(AggregateError)+ expect((failure as AggregateError).errors.map(String)).toEqual([+ 'FinalizeFsError: sync failure 3',+ 'FinalizeFsError: sync failure 4',+ ])+ expect(rename).toHaveBeenCalledTimes(2)+ expect(s.row()).toMatchObject({+ phase: 'prepared',+ quarantine_reason: null,+ })+ expect(await readFile(s.input.sourcePath, 'utf8')).toBe('complete download')+ injected.mockRestore()+ await s.runtime.commit(s.input)+ expect(s.row()).toMatchObject({ phase: 'cleaned' })+ expect(await readFile(s.input.targetPath, 'utf8')).toBe('complete download')+ expect(existsSync(s.input.sourcePath)).toBe(false)+ })++ it.each([false, true])(+ 'recovers a legacy quarantine with targetInstalled=%s before task restore',+ async (installed) => {+ const s = await setup()+ await s.legacyJournal(installed)+ await s.runtime.recoverAll()+ expect(s.row()).toMatchObject({+ phase: 'cleaned',+ quarantine_reason: null,+ })+ expect(await readFile(s.input.sourcePath, 'utf8')).toBe(+ 'complete download'+ )+ expect(existsSync(s.input.targetPath)).toBe(false)+ await s.runtime.commit(s.input)+ expect(await readFile(s.input.targetPath, 'utf8')).toBe(+ 'complete download'+ )+ }+ )++ it('recovers the old quarantine on explicit retry without a restart', async () => {+ const s = await setup()+ await s.legacyJournal(true)+ await s.runtime.commit(s.input)+ expect(s.row()).toMatchObject({ phase: 'cleaned' })+ expect(await readFile(s.input.targetPath, 'utf8')).toBe('complete download')+ })++ it.each(['both', 'replaced', 'missing', 'identity-quarantine', 'malformed'])(+ 'preserves unsafe old journals: %s',+ async (state) => {+ const s = await setup()+ const record = await s.legacyJournal()+ if (state === 'both')+ await writeFile(s.input.targetPath, 'unrelated target')+ if (state === 'replaced')+ await writeFile(s.input.sourcePath, 'changed source')+ if (state === 'missing') await rm(s.input.sourcePath)+ if (state === 'identity-quarantine')+ await s.repository.quarantine(+ record.journalId,+ 'compensation target identity mismatch'+ )+ if (state === 'malformed')+ s.db.prepare("UPDATE plugin_finalize_journals SET plan_json='{}'").run()+ const rename = vi.spyOn(s.adapter, 'renameOpenedNoReplace')+ await s.runtime.recoverAll()+ expect(s.row()).toMatchObject({ phase: 'quarantined' })+ expect(rename).not.toHaveBeenCalled()+ if (state === 'both')+ expect(await readFile(s.input.targetPath, 'utf8')).toBe(+ 'unrelated target'+ )+ if (state === 'replaced')+ expect(await readFile(s.input.sourcePath, 'utf8')).toBe(+ 'changed source'+ )+ }+ )++ it('does not reopen a legacy quarantine while the share is offline', async () => {+ const s = await setup()+ await s.legacyJournal()+ vi.spyOn(s.fs, 'identity').mockRejectedValue(+ Object.assign(new Error('share offline'), { code: 'EIO' })+ )+ await expect(s.runtime.recoverAll()).rejects.toThrow(+ 'one or more finalize journals failed'+ )+ expect(s.row()).toMatchObject({ phase: 'quarantined' })+ })+})diff --git a/src/core/plugin/finalize/native-artifact-operations.ts b/src/core/plugin/finalize/native-artifact-operations.tsindex a6c574b9..737d2f70 100644--- a/src/core/plugin/finalize/native-artifact-operations.ts+++ b/src/core/plugin/finalize/native-artifact-operations.ts@@ -38,6 +38,18 @@ export class NativeFinalizeArtifactOperations}}+ async preflight(sourcePath: string, targetPath: string): Promise<void> {+ await this.assertSupported()+ await this.ensureSafeDirectory(path.dirname(targetPath))+ await this.makeDurable(sourcePath)+ const targetRoot = await this.adapter.openRoot(path.dirname(targetPath))+ try {+ await this.adapter.syncRoot(targetRoot)+ } finally {+ await this.adapter.close(targetRoot).catch(() => undefined)+ }+ }+async identity(artifactPath: string): Promise<ArtifactIdentity | null> {try {return await readArtifactIdentity(artifactPath, {@@ -83,12 +95,12 @@ export class NativeFinalizeArtifactOperations)}const sourceRoot = await this.adapter.openRoot(path.dirname(sourcePath))- const targetRoot = await this.adapter.openRoot(- path.dirname(privateTargetPath)- )+ let targetRoot: Awaited<ReturnType<typeof this.adapter.openRoot>> | null =+ nulllet artifact: Awaited<ReturnType<typeof this.adapter.openArtifact>> | null =nulltry {+ targetRoot = await this.adapter.openRoot(path.dirname(privateTargetPath))artifact = await this.adapter.openArtifact(sourceRoot,path.basename(sourcePath)@@ -102,7 +114,8 @@ export class NativeFinalizeArtifactOperations} finally {if (artifact) await this.adapter.close(artifact).catch(() => undefined)await this.adapter.close(sourceRoot).catch(() => undefined)- await this.adapter.close(targetRoot).catch(() => undefined)+ if (targetRoot)+ await this.adapter.close(targetRoot).catch(() => undefined)}const copied = await readArtifactIdentity(privateTargetPath, {cache: this.identityCache,@@ -121,10 +134,12 @@ export class NativeFinalizeArtifactOperationsawait this.requireIdentity(sourcePath, expected)await this.ensureSafeDirectory(path.dirname(targetPath))const sourceRoot = await this.adapter.openRoot(path.dirname(sourcePath))- const targetRoot = await this.adapter.openRoot(path.dirname(targetPath))+ let targetRoot: Awaited<ReturnType<typeof this.adapter.openRoot>> | null =+ nulllet artifact: Awaited<ReturnType<typeof this.adapter.openArtifact>> | null =nulltry {+ targetRoot = await this.adapter.openRoot(path.dirname(targetPath))artifact = await this.adapter.openArtifact(sourceRoot,path.basename(sourcePath),@@ -142,7 +157,8 @@ export class NativeFinalizeArtifactOperations} finally {if (artifact) await this.adapter.close(artifact).catch(() => undefined)await this.adapter.close(sourceRoot).catch(() => undefined)- await this.adapter.close(targetRoot).catch(() => undefined)+ if (targetRoot)+ await this.adapter.close(targetRoot).catch(() => undefined)}}diff --git a/src/core/session/durable-finalize-runtime.ts b/src/core/session/durable-finalize-runtime.tsindex e902906a..8d63aedf 100644--- a/src/core/session/durable-finalize-runtime.ts+++ b/src/core/session/durable-finalize-runtime.ts@@ -82,6 +82,7 @@ export class DurableFinalizeRuntime {}const lease = await this.leases.acquire(input.task.id)try {+ await this.createRecovery().recoverTask(input.task.id, lease)// H8: identity capture is inside the mutation lease, after every// engine/Host writer has successfully quiesced.const sourceIdentity = await this.captureIdentity(input.sourcePath)@@ -167,6 +168,10 @@ export class DurableFinalizeRuntime {/** Recover before task restore: committed rows clean up; uncommitted targets roll back. */async recoverAll(): Promise<void> {+ await this.createRecovery().recoverAll()+ }++ private createRecovery(): FinalizeRecovery {const repository = new SqliteFinalizeJournalRepository(this.options.db, {now: this.now,commitTerminalBoundary: () => {@@ -175,7 +180,7 @@ export class DurableFinalizeRuntime {)},})- const recovery = new FinalizeRecovery({+ return new FinalizeRecovery({repository,leases: this.leases,fs: this.options.fs,@@ -183,6 +188,5 @@ export class DurableFinalizeRuntime {sameContent: artifactContentEquals,rollForwardTargetInstalled: false,})- await recovery.recoverAll()}}diff --git a/src/core/session/finalize-journal-repository.test.ts b/src/core/session/finalize-journal-repository.test.tsindex d94830bd..8cf22fc5 100644--- a/src/core/session/finalize-journal-repository.test.ts+++ b/src/core/session/finalize-journal-repository.test.ts@@ -14,6 +14,42 @@ describe('SqliteFinalizeJournalRepository', () => {afterEach(() => db.close())+ it('reopens only the exact legacy journal snapshot selected for recovery', async () => {+ const repository = new SqliteFinalizeJournalRepository(db, {+ commitTerminalBoundary: vi.fn(),+ })+ const record = { ...makeRecord('legacy'), publicationMode: 'move' as const }+ await repository.prepare(record)+ await repository.quarantine(+ record.journalId,+ 'compensation failed after I/O failure'+ )+ const [candidate] = await repository.listRecoverable(record.plan.taskId)+ expect(candidate).toMatchObject({+ quarantineReason: 'compensation failed after I/O failure',+ })+ expect(await repository.listRecoverable('another-task')).toEqual([])+ await repository.quarantine(+ record.journalId,+ 'compensation failed after a newer I/O failure'+ )+ await expect(repository.resumeQuarantined(candidate)).rejects.toThrow(+ 'changed before recovery'+ )+ expect(+ db.prepare('SELECT phase FROM plugin_finalize_journals').get()+ ).toEqual({ phase: 'quarantined' })+ const [current] = await repository.listRecoverable(record.plan.taskId)+ await repository.resumeQuarantined(current)+ expect(+ db+ .prepare(+ 'SELECT phase, quarantine_reason FROM plugin_finalize_journals'+ )+ .get()+ ).toEqual({ phase: 'prepared', quarantine_reason: null })+ })+it('persists the monotonic finalize state and all recovery identities', async () => {const commitTerminalBoundary = vi.fn((record: FinalizeJournalRecord) => {db.prepare(diff --git a/src/core/session/finalize-journal-repository.ts b/src/core/session/finalize-journal-repository.tsindex 54d78242..56347e61 100644--- a/src/core/session/finalize-journal-repository.ts+++ b/src/core/session/finalize-journal-repository.ts@@ -4,6 +4,7 @@ import type {FinalizeJournalRepository,} from '@core/plugin/finalize/finalize-committer'import { finalizePathsEquivalent } from '@core/plugin/finalize/finalize-committer'+import { isRetryableMoveQuarantine } from '@core/plugin/finalize/finalize-recovery'import { assertValidHookPlan } from '@core/plugin/finalize/hook-plan'import type Database from 'better-sqlite3'@@ -201,19 +202,25 @@ export class SqliteFinalizeJournalRepository}}- async listRecoverable(): Promise<FinalizeJournalRecord[]> {+ async listRecoverable(taskId?: string): Promise<FinalizeJournalRecord[]> {const rows = this.db.prepare(`SELECT * FROM plugin_finalize_journals- WHERE phase NOT IN ('cleaned','quarantined')+ WHERE phase <> 'cleaned' AND (? IS NULL OR task_id=?)ORDER BY created_at, plan_id`)- .all() as RawFinalizeJournal[]+ .all(taskId ?? null, taskId ?? null) as RawFinalizeJournal[]const records: FinalizeJournalRecord[] = []for (const row of rows) {try {- records.push(parseRecord(row))+ if (row.phase === 'quarantined') {+ const candidate = parseQuarantinedMove(row)+ if (candidate) records.push(candidate)+ } else {+ records.push(parseRecord(row))+ }} catch (error) {+ if (row.phase === 'quarantined') continueawait this.quarantine(row.plan_id,`invalid persisted finalize journal: ${errorMessage(error)}`@@ -223,6 +230,22 @@ export class SqliteFinalizeJournalRepositoryreturn records}+ async resumeQuarantined(record: FinalizeJournalRecord): Promise<void> {+ this.db.transaction(() => {+ const raw = this.readRaw(record.journalId)+ const candidate = raw && parseQuarantinedMove(raw)+ if (!candidate || JSON.stringify(candidate) !== JSON.stringify(record)) {+ throw new Error('quarantined finalize journal changed before recovery')+ }+ this.db+ .prepare(+ `UPDATE plugin_finalize_journals SET phase=?, quarantine_reason=NULL, updated_at=?+ WHERE plan_id=? AND phase='quarantined'`+ )+ .run(candidate.phase, Math.max(1, this.now()), candidate.journalId)+ })()+ }+private requireRecord(journalId: string): FinalizeJournalRecord {const raw = this.readRaw(journalId)if (!raw) throw new Error('finalize journal does not exist')@@ -239,6 +262,29 @@ export class SqliteFinalizeJournalRepository}}+function parseQuarantinedMove(+ raw: RawFinalizeJournal+): FinalizeJournalRecord | null {+ if (+ raw.phase !== 'quarantined' ||+ !raw.quarantine_reason?.startsWith('compensation failed after ')+ )+ return null+ const value: unknown = JSON.parse(raw.plan_json)+ if (+ !value ||+ typeof value !== 'object' ||+ !('phase' in value) ||+ (value.phase !== 'prepared' && value.phase !== 'target_installed')+ )+ return null+ const record = {+ ...parseRecord({ ...raw, phase: value.phase }),+ quarantineReason: raw.quarantine_reason,+ }+ return isRetryableMoveQuarantine(record) ? record : null+}+function serializeRecord(record: FinalizeJournalRecord): string {return JSON.stringify(record)}