A full-featured download manager.
fix(finalize): support cross-platform publication and storage recovery (#2339)
Dr_rOot7892fafa553d
diff --git a/.github/scripts/finalize-filesystems.sh b/.github/scripts/finalize-filesystems.shnew file mode 100644index 00000000..e9fde486--- /dev/null+++ b/.github/scripts/finalize-filesystems.sh@@ -0,0 +1,66 @@+#!/usr/bin/env bash+# Only newly allocated image files are formatted; never accept a device path.+set -euo pipefail+filesystem=${1:?expected a filesystem name}+shift+case "$filesystem" in+ ext4|btrfs|xfs|f2fs|exfat|vfat|ntfs3|ntfs-3g|tmpfs|overlay) ;;+ *) echo "Unsupported matrix filesystem: $filesystem" >&2; exit 2 ;;+esac+scratch=$(mktemp -d "${TMPDIR:-/tmp}/motrix-fs-matrix-XXXXXX")+privilege=()+if [ "$(id -u)" != 0 ]; then privilege=(sudo); fi+mounted=false+bound=false+backing=false+cleanup() {+ # Do not remove paths beneath a mount that could not be detached.+ if [ "$bound" = true ]; then "${privilege[@]}" umount "$scratch/bind" || return 1; fi+ if [ "$mounted" = true ]; then "${privilege[@]}" umount "$scratch/volume" || return 1; fi+ if [ "$backing" = true ]; then "${privilege[@]}" umount "$scratch/backing" || return 1; fi+ "${privilege[@]}" rm -rf "$scratch"+}+trap cleanup EXIT+mkdir "$scratch/volume" "$scratch/bind" "$scratch/backing"+uid=$(id -u)+gid=$(id -g)+if [ "$filesystem" = tmpfs ]; then+ "${privilege[@]}" mount -t tmpfs -o "size=64m,uid=$uid,gid=$gid" tmpfs "$scratch/volume"+elif [ "$filesystem" = overlay ]; then+ # Overlay upper/work must live on a real supported backing filesystem,+ # not the runner's possibly nested overlay/virtiofs checkout.+ truncate -s 512M "$scratch/backing.img"+ mkfs.ext4 -F -q "$scratch/backing.img"+ "${privilege[@]}" mount -o loop "$scratch/backing.img" "$scratch/backing"+ backing=true+ "${privilege[@]}" mkdir "$scratch/backing/lower" "$scratch/backing/upper" "$scratch/backing/work"+ "${privilege[@]}" mount -t overlay overlay -o "lowerdir=$scratch/backing/lower,upperdir=$scratch/backing/upper,workdir=$scratch/backing/work" "$scratch/volume"+else+ truncate -s 512M "$scratch/disk.img"+ options=loop+ case "$filesystem" in+ ext4) mkfs.ext4 -F -q "$scratch/disk.img" ;;+ btrfs) mkfs.btrfs -f -q "$scratch/disk.img" ;;+ xfs) mkfs.xfs -f -q "$scratch/disk.img" ;;+ f2fs) mkfs.f2fs -q "$scratch/disk.img" ;;+ exfat) mkfs.exfat "$scratch/disk.img" ;;+ vfat) mkfs.vfat -F 32 "$scratch/disk.img" ;;+ ntfs3|ntfs-3g) mkfs.ntfs -F -Q -q "$scratch/disk.img" ;;+ esac+ case "$filesystem" in+ exfat|vfat|ntfs3|ntfs-3g) options="$options,uid=$uid,gid=$gid,umask=022" ;;+ esac+ "${privilege[@]}" mount -t "$filesystem" -o "$options" "$scratch/disk.img" "$scratch/volume"+fi+mounted=true+case "$filesystem" in+ exfat|vfat|ntfs3|ntfs-3g) ;;+ *) "${privilege[@]}" chown "$uid:$gid" "$scratch/volume" ;;+esac+"${privilege[@]}" mount --bind "$scratch/volume" "$scratch/bind"+bound=true+findmnt --target "$scratch/volume"+export MOTRIX_FINALIZE_MATRIX_ROOT="$scratch/volume"+export MOTRIX_FINALIZE_MATRIX_BIND_ROOT="$scratch/bind"+export MOTRIX_FINALIZE_MATRIX_TYPE="$filesystem"+pnpm exec vitest run src/core/plugin/finalize/finalize-filesystems.integration.test.ts "$@" --reporter=verbosediff --git a/.github/workflows/finalize-exfat.yml b/.github/workflows/finalize-exfat.ymlnew file mode 100644index 00000000..394b8e29--- /dev/null+++ b/.github/workflows/finalize-exfat.yml@@ -0,0 +1,76 @@+name: Finalize macOS exFAT++on:+ pull_request:+ branches: [main]+ paths:+ - 'packages/finalize-fs/**'+ - 'src/core/plugin/finalize/**'+ - 'src/core/session/*finalize*'+ - 'src/core/task/task-recovery-service*'+ - '.github/workflows/finalize-exfat.yml'+ push:+ branches: [main]+ paths:+ - 'packages/finalize-fs/**'+ - 'src/core/plugin/finalize/**'+ - 'src/core/session/*finalize*'+ - 'src/core/task/task-recovery-service*'+ - '.github/workflows/finalize-exfat.yml'+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: finalize-exfat-${{ github.ref }}+ cancel-in-progress: true++jobs:+ macos-exfat:+ runs-on: macos-26+ timeout-minutes: 20+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0+ with:+ version: 12.8.1+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0+ with:+ node-version: 24+ cache: pnpm+ - uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable+ with:+ toolchain: 1.94.1+ components: clippy+ - name: Install dependencies+ run: pnpm install --frozen-lockfile+ env:+ MOTRIX_SKIP_ELECTRON_REBUILD: '1'+ MOTRIX_SKIP_ENGINE_FETCH: '1'+ - name: Validate and build the macOS sidecar+ run: |+ cargo clippy --manifest-path packages/finalize-fs/Cargo.toml --all-targets --locked -- -D warnings+ cargo test --manifest-path packages/finalize-fs/Cargo.toml --all-targets --locked+ cargo build --manifest-path packages/finalize-fs/Cargo.toml --locked+ - name: Exercise a disposable exFAT image+ shell: bash+ run: |+ set -euo pipefail+ scratch=$(mktemp -d "$RUNNER_TEMP/motrix-exfat-XXXXXX")+ mounted=false+ cleanup() {+ if [ "$mounted" = true ]; then+ hdiutil detach "$scratch/volume" || return 1+ fi+ rm -rf "$scratch"+ }+ trap cleanup EXIT+ mkdir "$scratch/volume"+ hdiutil create -size 128m -fs ExFAT -volname MotrixTest "$scratch/test.dmg"+ hdiutil attach "$scratch/test.dmg" -mountpoint "$scratch/volume" -nobrowse+ mounted=true+ export MOTRIX_FINALIZE_EXFAT_ROOT="$scratch/volume"+ export MOTRIX_FINALIZE_EXFAT_TEST_IMAGE="$scratch/test.dmg"+ cargo test --manifest-path packages/finalize-fs/Cargo.toml --locked -- --ignored --exact platform::unix::reserved::tests::exfat_reservations_preserve_conflicts_and_publish_held_files+ pnpm exec vitest run src/core/plugin/finalize/finalize-exfat.integration.test.tsdiff --git a/.github/workflows/finalize-filesystems.yml b/.github/workflows/finalize-filesystems.ymlnew file mode 100644index 00000000..feedfdb3--- /dev/null+++ b/.github/workflows/finalize-filesystems.yml@@ -0,0 +1,71 @@+name: Finalize Linux filesystems++on:+ pull_request:+ branches: [main]+ paths:+ - 'packages/finalize-fs/**'+ - 'src/core/plugin/finalize/**'+ - 'src/core/session/*finalize*'+ - '.github/scripts/finalize-filesystems.sh'+ - '.github/workflows/finalize-filesystems.yml'+ push:+ branches: [main]+ paths:+ - 'packages/finalize-fs/**'+ - 'src/core/plugin/finalize/**'+ - 'src/core/session/*finalize*'+ - '.github/scripts/finalize-filesystems.sh'+ - '.github/workflows/finalize-filesystems.yml'+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: finalize-filesystems-${{ github.ref }}+ cancel-in-progress: true++jobs:+ linux-filesystem:+ runs-on: ubuntu-24.04+ timeout-minutes: 20+ strategy:+ fail-fast: false+ matrix:+ filesystem: [ext4, btrfs, xfs, f2fs, exfat, vfat, ntfs3, ntfs-3g, tmpfs, overlay]+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0+ with:+ version: 12.8.1+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0+ with:+ node-version: 24+ cache: pnpm+ - uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable+ with:+ toolchain: 1.94.1+ - name: Install dependencies+ run: |+ pnpm install --frozen-lockfile+ sudo apt-get update -qq+ sudo apt-get install -y e2fsprogs btrfs-progs xfsprogs f2fs-tools exfatprogs dosfstools ntfs-3g+ env:+ MOTRIX_SKIP_ELECTRON_REBUILD: '1'+ MOTRIX_SKIP_ENGINE_FETCH: '1'+ - name: Install and load optional filesystem drivers+ if: contains(fromJSON('["f2fs", "exfat", "ntfs3"]'), matrix.filesystem)+ env:+ MATRIX_FILESYSTEM: ${{ matrix.filesystem }}+ run: |+ # Formatting tools do not provide the Azure runner's kernel drivers.+ # Match the running kernel rather than installing a newer meta-package.+ sudo apt-get install --yes --no-install-recommends "linux-modules-extra-$(uname -r)"+ sudo modprobe "$MATRIX_FILESYSTEM"+ - name: Build native sidecar+ run: cargo build --manifest-path packages/finalize-fs/Cargo.toml --locked+ - name: Test publication and recovery on a disposable volume+ env:+ MATRIX_FILESYSTEM: ${{ matrix.filesystem }}+ run: bash .github/scripts/finalize-filesystems.sh "$MATRIX_FILESYSTEM"diff --git a/packages/finalize-fs/README.md b/packages/finalize-fs/README.mdindex f97683a8..9d1d3834 100644--- a/packages/finalize-fs/README.md+++ b/packages/finalize-fs/README.md@@ -1,7 +1,9 @@# Finalize filesystem serviceThe sidecar performs handle-relative, identity-checked file publication and-removal. Renames never replace an existing destination. Reparse points and+removal. No-replace operations never replace an existing destination. The+separate macOS exFAT compatibility operation replaces a journaled reservation+under the ownership assumptions below. Reparse points andunsafe path components remain rejected on Windows.## Filename sanitization@@ -84,7 +86,7 @@ and unlink another against unrestricted external writers. A crash before theremoval checkpoint can leave an empty private directory, but cannot removesource data.-Public targets are never overwritten. Permissions, target conflicts, I/O and+The hard-link fallback never overwrites public targets. Permissions, target conflicts, I/O andsync errors remain errors. Directory publication and same-path pluginreplacement still require native no-replace rename; they do not use the filefallback. Filesystems without hard links or a usable Linux `/proc/self/fd`@@ -92,6 +94,115 @@ retain the journal and return an error. `rustix` supplies the safe Unix syscallwrappers; `sha2` supplies the shared digest implementation. Neither replacesthe application's durable transaction and recovery rules.+## Cross-mount publication and Linux coverage++Device numbers are an optimization hint, not proof that rename can succeed.+Linux bind mounts can share `st_dev` while rename returns `EXDEV`; OverlayFS+can also return `EXDEV` for a lower-layer directory. After an actual+cross-device error, the host revalidates the source and target absence, then+durably switches a still-prepared move journal to copy mode before creating+anything. The existing private-copy, exclusive publication, database commit,+and survivor-checked cleanup protocol handles the rest. An applied mutation,+publication intent, permission failure, or generic I/O failure cannot trigger+this switch. The repository rejects mode changes after staging or publication.++The Linux matrix in `finalize-filesystems.yml` formats only newly created+image files and runs the real native sidecar with a local SQLite journal on+ext4, Btrfs, XFS, F2FS, FAT32, exFAT, NTFS3, NTFS-3G, tmpfs, and OverlayFS.+It checks empty files, Unicode and long names, existing targets, case-sensitive+and case-insensitive conflicts, real cross-device copies, bind mounts with+equal device numbers, unavailable paths, and restart after a lost response.+Storage disappearance is modeled by moving the scratch directory out of the+recorded path; it is not a hardware unplug or power-loss test. OverlayFS tests+create downloads in the writable upper layer. NTFS-3G's unsupported exclusive+directory rename is explicitly tested as a refusal that preserves the source,+not as successful directory publication. Lost hard-link acknowledgements still+preserve both names for reconciliation.++To run one matrix entry on Linux with the listed formatter installed and+passwordless mount privileges:++```sh+cargo build --manifest-path packages/finalize-fs/Cargo.toml --locked+bash .github/scripts/finalize-filesystems.sh ext4+```++The matrix supplements the NFS, Windows SMB/FAT-family, and macOS exFAT suites;+it does not assert support for every FUSE driver, network server, kernel, or+mount configuration. Synchronization success remains subject to the storage+implementation; tmpfs, in particular, is volatile across system restart.++## macOS local exFAT++Some FSKit exFAT volumes reject exclusive rename with `ENOTSUP` (45), which+differs from `EOPNOTSUPP` (102) on Darwin, and do not support hard links.+Ordinary download suffix removal can use `reserve_exfat_target` followed by+`rename_opened_reserved`. The original no-replace operation keeps its strict+contract. This compatibility route requires a regular file, the same parent,+an exact `.motrix` suffix removal, a local exFAT mount, and no plugin replacement+or staged metadata. Permission, space, I/O and other errors do not enable it.++The host durably journals a version-3 intent containing a random reservation+token and the volume UUID before creating the final name with+`O_CREAT|O_EXCL|O_NOFOLLOW`. The small, nonempty marker contains the token;+its contents establish ownership across remounts, including a lost creation+response before the reservation identity checkpoint. An existing target is+accepted only if it contains the exact journaled marker. A partial marker or+unrelated file is preserved as a conflict. The sidecar retains the source and+reservation descriptors, rechecks both names and marker contents before+ordinary rename, binds the installed name to the held source, and flushes the+parent before replying. The final name may briefly contain the marker; task+completion waits for the database transaction.++Recovery probes the persisted volume UUID before reading file identities.+Missing or different volumes leave the journal pending for reconnection.+Nonempty files must still match their inode and complete content digest;+only their mount-specific device number may change. Legacy version-2 empty+reservations retain their exact-identity checks because they have no token.++This is an application-owned-name contract, not atomic no-replace: an unrelated+writer can replace the reservation between the final check and `renameat`.+Holding its descriptor does not prevent POSIX unlink/replacement. Shared and+unknown filesystems, directory publication, and plugin replacement do not use+this route. Do not describe it as protection against unrestricted concurrent+external writers.++FSKit may change an empty file's inode during rename. The response reports its+actual installed identity, proven through the held descriptor. Synthetic inode+values use Node BigIntStats' signed 64-bit representation on this wire path.+An unacknowledged changed identity cannot be recovered from an empty digest;+recovery retains the file and quarantines the journal instead of guessing.++Critical journal writes use a synchronous `FULL` transaction and enable+SQLite `fullfsync` on macOS, restoring the connection's previous settings+afterward. Native reservation and macOS root syncs use Rust `File::sync_all`,+which requests `F_FULLFSYNC` with std's fallback when unsupported. `WAL` with+`NORMAL` alone does not make each intent durable against system failure. Database task completion and+the journal commit remain one transaction. Durability depends on the volume+and device honoring their synchronization operations.++Before task restore, recovery validates reservations and installed files but+does not roll a reserved publication back through unsupported exclusive rename.+Task recovery routes unfinished journals through the normal finalizer, which+resumes with the task/effects commit boundary. A reservation created before its+identity checkpoint is not automatically removed. A known installed target+rolls forward; conflicting or unknown identities preserve all surviving files.+Older sidecars cannot execute this operation. Older applications reject the+version-3 intent and may quarantine it without deleting its files.++`finalize-exfat.yml` provisions a disposable macOS exFAT image and exercises the+native reservation contract plus real sidecar/SQLite recovery, including host+`SIGKILL` after marker creation, after rename, and before the terminal database+commit. Remount/offline tests run only when `MOTRIX_FINALIZE_EXFAT_TEST_IMAGE`+identifies the disposable image backing the test root; they never detach a+volume supplied through the root variable alone. To run against+an existing disposable volume, set `MOTRIX_FINALIZE_EXFAT_ROOT` and run:++```sh+cargo test --manifest-path packages/finalize-fs/Cargo.toml --locked -- --ignored --exact platform::unix::reserved::tests::exfat_reservations_preserve_conflicts_and_publish_held_files+pnpm exec vitest run src/core/plugin/finalize/finalize-exfat.integration.test.ts+```+## Windows and SMBWindows rename retries transient sharing conflicts with exponential backoff,@@ -145,6 +256,16 @@ class. Existing protocol consumers can ignore the additive fields.## RecoveryNew I/O failures keep the last journal checkpoint available for retry.+Missing artifacts alone also keep the checkpoint retryable: an unmounted disk+or unavailable share can present as `ENOENT`. This includes a missing committed+target and a temporarily unavailable survivor during pending cleanup. A changed+identity remains a conflict, and no file is removed while its required survivor+is unavailable. A reconnect still has to pass the existing identity checks;+this does not infer ownership from matching content on a different volume.+Startup logs and defers these journals, including recognized stale-mount and+disconnection errors, while allowing other tasks to restore. An explicit task+retry still fails until storage is available. Generic I/O, permission, database,+and programming errors are not silently converted into storage deferrals.Successful rollback closes the journal only after identity and durabilitychecks. Startup recovery and an explicit finalize retry use the same rollbackimplementation under the task's mutation lease.diff --git a/packages/finalize-fs/src/error.rs b/packages/finalize-fs/src/error.rsindex b4fe346a..56723478 100644--- a/packages/finalize-fs/src/error.rs+++ b/packages/finalize-fs/src/error.rs@@ -94,10 +94,10 @@ pub(crate) fn nt_status(error: &io::Error) -> Option<String> {#[cfg(unix)]pub(crate) fn rename_error(error: io::Error, regular_file: bool) -> io::Error {- let unsupported = matches!(- error.raw_os_error(),- Some(libc::EINVAL | libc::ENOSYS | libc::EOPNOTSUPP)- );+ // ENOTSUP and EOPNOTSUPP have different values on Darwin.+ let unsupported = error.raw_os_error().is_some_and(|code| {+ [libc::EINVAL, libc::ENOSYS, libc::EOPNOTSUPP, libc::ENOTSUP].contains(&code)+ });let code = (unsupported && regular_file).then_some("rename_unsupported");io::Error::new(error.kind(),@@ -116,7 +116,7 @@ mod rename_tests {#[test]fn rename_capability_errors_keep_the_original_errno() {- for code in [libc::EINVAL, libc::ENOSYS, libc::EOPNOTSUPP] {+ for code in [libc::EINVAL, libc::ENOSYS, libc::EOPNOTSUPP, libc::ENOTSUP] {let error = rename_error(io::Error::from_raw_os_error(code), true);assert_eq!(classify_error(&error), "rename_unsupported");assert_eq!(os_code(&error), Some(code));diff --git a/packages/finalize-fs/src/platform/mod.rs b/packages/finalize-fs/src/platform/mod.rsindex 256694cd..2d20768b 100644--- a/packages/finalize-fs/src/platform/mod.rs+++ b/packages/finalize-fs/src/platform/mod.rs@@ -1,5 +1,8 @@//! Compile-time platform facade for handle-bound filesystem operations.+#[cfg(target_os = "macos")]+pub(crate) use unix::{exfat_volume_identity, rename_opened_reserved, reserve_exfat_target};+#[cfg(unix)]mod unix;#[cfg(not(any(unix, windows)))]diff --git a/packages/finalize-fs/src/platform/unix/mod.rs b/packages/finalize-fs/src/platform/unix/mod.rsindex ddd4d284..35b77ad7 100644--- a/packages/finalize-fs/src/platform/unix/mod.rs+++ b/packages/finalize-fs/src/platform/unix/mod.rs@@ -13,7 +13,12 @@ mod tests;use crate::path::validate_relative;use digest::hash_opened_file;use metadata::artifact_stamp;++#[cfg(target_os = "macos")]+mod reserved;use remove::snapshot_directory;+#[cfg(target_os = "macos")]+pub(crate) use reserved::{exfat_volume_identity, rename_opened_reserved, reserve_exfat_target};use std::ffi::CString;use std::io;use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};@@ -36,6 +41,8 @@ pub(crate) struct ArtifactHandle {opened_link_count: libc::nlink_t,opened_tree: Option<Vec<TreeEntrySnapshot>>,opened_file_sha256: Option<[u8; 32]>,+ #[cfg(target_os = "macos")]+ reservation_digest: Option<[u8; 32]>,}#[derive(Clone, Copy, Debug, Eq, PartialEq)]@@ -207,6 +214,8 @@ fn open_artifact_internal(opened_link_count: opened_stat.st_nlink,opened_tree,opened_file_sha256,+ #[cfg(target_os = "macos")]+ reservation_digest: None,})}@@ -231,8 +240,13 @@ fn assert_opened_artifact(}pub(crate) fn sync_root(root: &RootHandle) -> io::Result<()> {- if unsafe { libc::fsync(root.0.as_raw_fd()) } < 0 {- return Err(io::Error::last_os_error());+ #[cfg(target_os = "macos")]+ return reserved::sync_full(&root.0);+ #[cfg(not(target_os = "macos"))]+ {+ if unsafe { libc::fsync(root.0.as_raw_fd()) } < 0 {+ return Err(io::Error::last_os_error());+ }+ Ok(())}- Ok(())}diff --git a/packages/finalize-fs/src/platform/unix/reserved.rs b/packages/finalize-fs/src/platform/unix/reserved.rsnew file mode 100644index 00000000..16fdce00--- /dev/null+++ b/packages/finalize-fs/src/platform/unix/reserved.rs@@ -0,0 +1,464 @@+//! Compatibility publication for local macOS exFAT downloads. The final name+//! must remain application-owned between its last check and ordinary rename.+//! This deliberately does not implement the atomic no-replace contract.++use super::metadata::{artifact_stamp, ensure_same_entry, stat_named, stat_opened};+use super::{ArtifactHandle, RootHandle, assert_opened_artifact};+use crate::error::{native_error, operation_error};+use crate::rename::RenameOutcome;+use std::ffi::{CStr, CString};+use std::io::{self, Write};+use std::os::fd::AsRawFd;+use std::os::unix::fs::FileExt;++fn identity(stat: &libc::stat) -> String {+ // Node BigIntStats exposes inode through a signed 64-bit slot. FSKit's+ // synthetic empty-file IDs set the high bit; preserve the host's existing+ // journal representation instead of changing identities of older records.+ format!("{}:{}", stat.st_dev, stat.st_ino as i64)+}++/// Query a persistent volume UUID, not the mount's transient device number.+pub(crate) fn exfat_volume_identity(root: &RootHandle) -> io::Result<Option<String>> {+ let mut fs = std::mem::MaybeUninit::<libc::statfs>::uninit();+ if unsafe { libc::fstatfs(root.0.as_raw_fd(), fs.as_mut_ptr()) } != 0 {+ return Err(io::Error::last_os_error());+ }+ let fs = unsafe { fs.assume_init() };+ if fs.f_flags & libc::MNT_LOCAL as u32 == 0+ || unsafe { CStr::from_ptr(fs.f_fstypename.as_ptr()) }.to_bytes() != b"exfat"+ {+ return Ok(None);+ }+ let mut attributes = libc::attrlist {+ bitmapcount: libc::ATTR_BIT_MAP_COUNT,+ reserved: 0,+ commonattr: 0,+ volattr: libc::ATTR_VOL_INFO | libc::ATTR_VOL_UUID,+ dirattr: 0,+ fileattr: 0,+ forkattr: 0,+ };+ // Darwin attribute buffers have a 4-byte length followed by the UUID.+ let mut buffer = [0_u8; 20];+ if unsafe {+ libc::fgetattrlist(+ root.0.as_raw_fd(),+ (&mut attributes as *mut libc::attrlist).cast(),+ buffer.as_mut_ptr().cast(),+ buffer.len(),+ 0,+ )+ } != 0+ {+ return Err(io::Error::last_os_error());+ }+ if u32::from_ne_bytes(buffer[..4].try_into().unwrap()) != 20+ || buffer[4..].iter().all(|byte| *byte == 0)+ {+ return Err(io::Error::new(+ io::ErrorKind::Unsupported,+ "missing exFAT volume UUID",+ ));+ }+ Ok(Some(+ buffer[4..]+ .iter()+ .map(|byte| format!("{byte:02x}"))+ .collect(),+ ))+}++pub(super) fn sync_full(fd: &std::os::fd::OwnedFd) -> io::Result<()> {+ // std uses F_FULLFSYNC on Apple, with its platform fallback when unsupported.+ std::fs::File::from(fd.try_clone()?).sync_all()+}++fn marker(token: &str) -> io::Result<Vec<u8>> {+ if token.len() != 64+ || !token+ .bytes()+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))+ {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ "invalid reservation token",+ ));+ }+ Ok(format!("motrix-reservation-v1:{token}\n").into_bytes())+}++fn validate_scope(+ source: &ArtifactHandle,+ target: &std::os::fd::OwnedFd,+ name: &CStr,+) -> io::Result<()> {+ let from = stat_opened(source.parent.as_raw_fd())?;+ let to = stat_opened(target.as_raw_fd())?;+ let mut fs = std::mem::MaybeUninit::<libc::statfs>::uninit();+ if unsafe { libc::fstatfs(target.as_raw_fd(), fs.as_mut_ptr()) } != 0 {+ return Err(io::Error::last_os_error());+ }+ let fs = unsafe { fs.assume_init() };+ let fs_name = unsafe { CStr::from_ptr(fs.f_fstypename.as_ptr()) };+ if from.st_dev != to.st_dev+ || from.st_ino != to.st_ino+ || fs.f_flags & libc::MNT_LOCAL as u32 == 0+ || fs_name.to_bytes() != b"exfat"+ || source.name.to_bytes().strip_suffix(b".motrix") != Some(name.to_bytes())+ || name.to_bytes().is_empty()+ {+ return Err(io::Error::new(+ io::ErrorKind::Unsupported,+ "reserved rename requires same-directory suffix removal on local exFAT",+ ));+ }+ unchanged(source)?;+ Ok(())+}++fn unchanged(artifact: &ArtifactHandle) -> io::Result<libc::stat> {+ assert_opened_artifact(artifact, artifact.parent.as_raw_fd(), &artifact.name)?;+ let stat = stat_opened(artifact.artifact.as_raw_fd())?;+ if stat.st_mode & libc::S_IFMT != libc::S_IFREG+ || stat.st_nlink != 1+ || artifact_stamp(&stat) != artifact.opened_stamp+ {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ "reserved publication artifact changed",+ ));+ }+ Ok(stat)+}++pub(crate) fn reserve_exfat_target(+ source: &ArtifactHandle,+ root: &RootHandle,+ relative: &str,+ expected: Option<&str>,+ ownership: Option<(&str, &str)>,+) -> io::Result<(ArtifactHandle, String)> {+ let parts = crate::path::validate_relative(relative)?;+ if parts.len() != 1 {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ "reservation requires an immediate child",+ ));+ }+ let name = CString::new(relative).expect("validated component");+ validate_scope(source, &root.0, &name)+ .map_err(|e| operation_error(e, "validate_reservation", "not_attempted", None))?;+ let contents = ownership.map(|(token, _)| marker(token)).transpose()?;+ if let Some((_, volume)) = ownership+ && exfat_volume_identity(root)?.as_deref() != Some(volume)+ {+ return Err(io::Error::new(+ io::ErrorKind::NotFound,+ "reserved volume is unavailable",+ ));+ }+ let flags =+ rustix::fs::OFlags::RDWR | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC;+ // The token was persisted before CREATE. A lost response can therefore+ // reopen only the exact marker, even before its file ID was checkpointed.+ let (artifact, created) = if expected.is_none() {+ match rustix::fs::openat(+ &root.0,+ &name,+ flags | rustix::fs::OFlags::CREATE | rustix::fs::OFlags::EXCL,+ rustix::fs::Mode::from_bits_truncate(0o600),+ ) {+ Ok(fd) => (fd, true),+ Err(rustix::io::Errno::EXIST) if contents.is_some() => (+ rustix::fs::openat(&root.0, &name, flags, rustix::fs::Mode::empty())?,+ false,+ ),+ Err(e) => {+ return Err(operation_error(+ native_error(e.into(), "openat(exclusive_reservation)", None),+ "reserve_target",+ "unknown",+ None,+ ));+ }+ }+ } else {+ (+ rustix::fs::openat(&root.0, &name, flags, rustix::fs::Mode::empty())?,+ false,+ )+ };+ if created && let Some(contents) = &contents {+ std::fs::File::from(artifact.try_clone()?).write_all(contents)?;+ }+ // Never unlink on a failure: an unacknowledged reservation must be retained.+ let stat = ensure_same_entry(artifact.as_raw_fd(), root.0.as_raw_fd(), &name)?;+ let id = identity(&stat);+ if stat.st_mode & libc::S_IFMT != libc::S_IFREG+ || stat.st_size != contents.as_ref().map_or(0, |bytes| bytes.len() as i64)+ || stat.st_nlink != 1+ || (contents.is_none() && expected.is_some_and(|expected| expected != id))+ {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ "reservation identity mismatch",+ ));+ }+ if let Some(contents) = &contents {+ let mut actual = vec![0; contents.len()];+ std::fs::File::from(artifact.try_clone()?).read_exact_at(&mut actual, 0)?;+ if actual != *contents {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ "reservation token mismatch",+ ));+ }+ }+ let digest = super::digest::hash_opened_file(artifact.as_raw_fd())?;+ sync_full(&artifact)?;+ sync_full(&root.0)?;+ Ok((+ ArtifactHandle {+ artifact,+ parent: root.0.try_clone()?,+ name,+ device: stat.st_dev,+ inode: stat.st_ino,+ opened_stamp: artifact_stamp(&stat),+ opened_link_count: stat.st_nlink,+ opened_tree: None,+ opened_file_sha256: None,+ reservation_digest: Some(digest),+ },+ id,+ ))+}++pub(crate) fn rename_opened_reserved(+ source: &ArtifactHandle,+ reservation: &ArtifactHandle,+) -> io::Result<(RenameOutcome, String)> {+ let before = (|| {+ validate_scope(source, &reservation.parent, &reservation.name)?;+ unchanged(reservation)?;+ if reservation.reservation_digest+ != Some(super::digest::hash_opened_file(+ reservation.artifact.as_raw_fd(),+ )?)+ {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ "reservation contents changed",+ ));+ }+ unchanged(source)+ })()+ .map_err(|e| operation_error(e, "validate_reservation", "not_attempted", None))?;+ rustix::fs::renameat(+ &source.parent,+ &source.name,+ &reservation.parent,+ &reservation.name,+ )+ .map_err(|e| {+ operation_error(+ native_error(e.into(), "renameat(owned_reservation)", None),+ "rename",+ "unknown",+ Some(1),+ )+ })?;+ let installed = (|| {+ // FSKit exFAT can change an empty file's ID during rename, including+ // the ID returned by the continuously held descriptor. Bind the new+ // name to that descriptor, rather than trusting an equal empty digest.+ let after = ensure_same_entry(+ source.artifact.as_raw_fd(),+ reservation.parent.as_raw_fd(),+ &reservation.name,+ )?;+ if after.st_dev != before.st_dev+ || after.st_size != before.st_size+ || after.st_mode & libc::S_IFMT != libc::S_IFREG+ || after.st_nlink != 1+ || after.st_mtime != before.st_mtime+ || after.st_mtime_nsec != before.st_mtime_nsec+ || (before.st_size != 0 && after.st_ino != before.st_ino)+ {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ "installed file changed",+ ));+ }+ match stat_named(source.parent.as_raw_fd(), &source.name) {+ Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(identity(&after)),+ Err(e) => Err(e),+ Ok(_) => Err(io::Error::new(+ io::ErrorKind::InvalidData,+ "source name reappeared after publication",+ )),+ }+ })()+ .map_err(|e| operation_error(e, "verify_target", "applied", None))?;+ let outcome = crate::rename::sync_parents(true, |_| {+ sync_full(&reservation.parent)?;+ Ok("directory_flushed")+ })?;+ Ok((outcome, installed))+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::path::PathBuf;++ struct Scratch(PathBuf);+ impl Drop for Scratch {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+ }++ struct Files(Vec<PathBuf>);+ impl Drop for Files {+ fn drop(&mut self) {+ for file in &self.0 {+ let _ = std::fs::remove_file(file);+ }+ }+ }++ fn scratch(parent: PathBuf) -> Scratch {+ let path = parent.join(format!(+ "motrix-reserved-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ std::fs::create_dir(&path).unwrap();+ Scratch(path.canonicalize().unwrap())+ }++ #[test]+ fn reservation_rejects_other_filesystems_without_creating_a_target() {+ let dir = scratch(std::env::temp_dir());+ std::fs::write(dir.0.join("file.motrix"), b"source").unwrap();+ let root = super::super::open_root(dir.0.to_str().unwrap()).unwrap();+ let source = super::super::open_artifact_for_rename(&root, "file.motrix").unwrap();+ let error = reserve_exfat_target(&source, &root, "file", None, None)+ .err()+ .expect("non-exFAT root accepted");+ assert_eq!(error.kind(), io::ErrorKind::Unsupported);+ assert!(!dir.0.join("file").exists());+ }++ #[test]+ #[ignore = "requires MOTRIX_FINALIZE_EXFAT_ROOT on a disposable local exFAT volume"]+ fn exfat_reservations_preserve_conflicts_and_publish_held_files() {+ let parent =+ PathBuf::from(std::env::var("MOTRIX_FINALIZE_EXFAT_ROOT").expect("exFAT test root"));+ let dir = scratch(parent.clone());+ // Also exercise a held volume root, with names unique to this fixture.+ let root_name = dir.0.file_name().unwrap().to_str().unwrap().to_owned() + "-payload";+ let from_name = format!("{root_name}.motrix");+ let files = Files(vec![parent.join(&from_name), parent.join(&root_name)]);+ let file = std::fs::File::create_new(&files.0[0]).unwrap();+ drop(file);+ let volume = super::super::open_root(parent.to_str().unwrap()).unwrap();+ let source = super::super::open_artifact_for_rename(&volume, &from_name).unwrap();+ let (reserved, _) = reserve_exfat_target(&source, &volume, &root_name, None, None).unwrap();+ rename_opened_reserved(&source, &reserved).unwrap();+ assert!(!files.0[0].exists());+ assert!(files.0[1].exists());+ let root = super::super::open_root(dir.0.to_str().unwrap()).unwrap();+ for (name, contents) in [+ ("empty", b"".as_slice()),+ ("download", b"complete download".as_slice()),+ ] {+ let source_name = format!("{name}.motrix");+ std::fs::write(dir.0.join(&source_name), contents).unwrap();+ let source = super::super::open_artifact_for_rename(&root, &source_name).unwrap();+ let (reserved, id) = reserve_exfat_target(&source, &root, name, None, None).unwrap();+ assert_eq!(+ reserve_exfat_target(&source, &root, name, None, None)+ .err()+ .unwrap()+ .kind(),+ io::ErrorKind::AlreadyExists+ );+ assert!(reserve_exfat_target(&source, &root, name, Some("wrong-id"), None).is_err());+ let (reopened, _) =+ reserve_exfat_target(&source, &root, name, Some(&id), None).unwrap();+ drop(reserved);+ let (outcome, installed) = rename_opened_reserved(&source, &reopened).unwrap();+ assert_eq!(outcome.directory_sync_mode, "directory_flushed");+ assert_eq!(+ installed,+ identity(&stat_named(root.0.as_raw_fd(), &CString::new(name).unwrap()).unwrap())+ );+ assert_eq!(std::fs::read(dir.0.join(name)).unwrap(), contents);+ assert!(!dir.0.join(&source_name).exists());+ }+ let volume_id = exfat_volume_identity(&root).unwrap().unwrap();+ std::fs::write(dir.0.join("token.motrix"), b"download").unwrap();+ let source = super::super::open_artifact_for_rename(&root, "token.motrix").unwrap();+ let token = "a".repeat(64);+ let ownership = Some((token.as_str(), volume_id.as_str()));+ assert!(+ reserve_exfat_target(+ &source,+ &root,+ "token",+ None,+ Some((&token, "wrong-volume"))+ )+ .is_err()+ );+ assert!(!dir.0.join("token").exists());+ let (reserved, _) = reserve_exfat_target(&source, &root, "token", None, ownership).unwrap();+ assert_eq!(+ std::fs::read(dir.0.join("token")).unwrap(),+ marker(&token).unwrap()+ );+ let unreserved = super::super::open_artifact(&root, "token").unwrap();+ assert!(rename_opened_reserved(&source, &unreserved).is_err());+ assert!(dir.0.join("token.motrix").exists());+ // No acknowledged file ID is needed when the pre-journaled token matches.+ let (reopened, _) = reserve_exfat_target(&source, &root, "token", None, ownership).unwrap();+ assert!(+ reserve_exfat_target(+ &source,+ &root,+ "token",+ None,+ Some((&"b".repeat(64), &volume_id))+ )+ .is_err()+ );+ drop(reserved);+ rename_opened_reserved(&source, &reopened).unwrap();+ assert_eq!(std::fs::read(dir.0.join("token")).unwrap(), b"download");++ std::fs::write(dir.0.join("conflict.motrix"), b"download").unwrap();+ let source = super::super::open_artifact_for_rename(&root, "conflict.motrix").unwrap();+ let (reserved, _) = reserve_exfat_target(&source, &root, "conflict", None, None).unwrap();+ std::fs::rename(dir.0.join("conflict"), dir.0.join("old-reservation")).unwrap();+ std::fs::write(dir.0.join("conflict"), b"other owner").unwrap();+ let error = rename_opened_reserved(&source, &reserved).unwrap_err();+ assert_eq!(+ crate::error::operation_context(&error).unwrap().mutation,+ "not_attempted"+ );+ assert_eq!(+ std::fs::read(dir.0.join("conflict")).unwrap(),+ b"other owner"+ );+ assert_eq!(+ std::fs::read(dir.0.join("conflict.motrix")).unwrap(),+ b"download"+ );+ }+}diff --git a/packages/finalize-fs/src/protocol.rs b/packages/finalize-fs/src/protocol.rsindex 398e8095..5b38c963 100644--- a/packages/finalize-fs/src/protocol.rs+++ b/packages/finalize-fs/src/protocol.rs@@ -38,6 +38,27 @@ pub(crate) enum Request {target_root: u64,target_relative: String,},+ ExfatVolumeIdentity {+ request_id: u64,+ root: u64,+ },+ ReserveExfatTarget {+ request_id: u64,+ artifact: u64,+ target_root: u64,+ target_relative: String,+ #[serde(default)]+ expected_identity: Option<String>,+ #[serde(default)]+ token: Option<String>,+ #[serde(default)]+ volume_id: Option<String>,+ },+ RenameOpenedReserved {+ request_id: u64,+ artifact: u64,+ reservation: u64,+ },IsolateOpened {expected_root_identity: String,request_id: u64,@@ -90,6 +111,9 @@ impl Request {Self::OpenArtifact { .. } => "open_artifact",Self::RenameOpenedNoReplace { .. } => "rename_opened_no_replace",Self::LinkOpenedNoReplace { .. } => "link_opened_no_replace",+ Self::ExfatVolumeIdentity { .. } => "exfat_volume_identity",+ Self::ReserveExfatTarget { .. } => "reserve_exfat_target",+ Self::RenameOpenedReserved { .. } => "rename_opened_reserved",Self::IsolateOpened { .. } => "isolate_opened",Self::CopyOpened { .. } => "copy_opened",Self::RenameNoReplace { .. } => "rename_no_replace",@@ -124,6 +148,14 @@ pub(crate) struct Response<'a> {#[serde(skip_serializing_if = "Option::is_none")]pub(crate) held_artifacts: Option<bool>,#[serde(skip_serializing_if = "Option::is_none")]+ pub(crate) reserved_exfat_rename: Option<bool>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub(crate) token_exfat_reservation: Option<bool>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub(crate) volume_id: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub(crate) platform_file_id: Option<String>,+ #[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>,@@ -153,6 +185,10 @@ impl<'a> Response<'a> {held_roots: None,directory_sync: None,held_artifacts: None,+ reserved_exfat_rename: None,+ token_exfat_reservation: None,+ volume_id: None,+ platform_file_id: None,operation: None,directory_sync_mode: None,os_error: None,diff --git a/packages/finalize-fs/src/state.rs b/packages/finalize-fs/src/state.rsindex da760625..4346057a 100644--- a/packages/finalize-fs/src/state.rs+++ b/packages/finalize-fs/src/state.rs@@ -126,6 +126,136 @@ impl State {&target_relative,crate::platform::link_opened_no_replace,),+ Request::ExfatVolumeIdentity { request_id, root } => {+ #[cfg(target_os = "macos")]+ {+ let Some(root) = self.roots.get(&root) else {+ return Response::error(Some(request_id), "invalid_handle", "unknown root");+ };+ match crate::platform::exfat_volume_identity(root) {+ Ok(id) => {+ let mut response = Response::ok(Some(request_id));+ response.volume_id = id;+ response+ }+ Err(error) => Response::filesystem_error(request_id, error),+ }+ }+ #[cfg(not(target_os = "macos"))]+ {+ let _ = root;+ Response::error(+ Some(request_id),+ "unsupported",+ "exFAT volume identity requires macOS",+ )+ }+ }+ Request::ReserveExfatTarget {+ request_id,+ artifact,+ target_root,+ target_relative,+ expected_identity,+ token,+ volume_id,+ } => {+ #[cfg(target_os = "macos")]+ {+ let Some(source) = self.artifacts.get(&artifact).and_then(Option::as_ref)+ else {+ return Response::error(+ Some(request_id),+ "invalid_handle",+ "unknown artifact",+ );+ };+ let Some(root) = self.roots.get(&target_root) else {+ return Response::error(Some(request_id), "invalid_handle", "unknown root");+ };+ if token.is_some() != volume_id.is_some() {+ return Response::error(+ Some(request_id),+ "invalid_request",+ "incomplete reservation ownership",+ );+ }+ match crate::platform::reserve_exfat_target(+ source,+ root,+ &target_relative,+ expected_identity.as_deref(),+ token.as_deref().zip(volume_id.as_deref()),+ ) {+ Ok((reservation, identity)) => {+ let handle = self.insert_artifact(reservation);+ let mut response = Response::ok(Some(request_id));+ response.handle = Some(handle);+ response.platform_file_id = Some(identity);+ response+ }+ Err(error) => Response::filesystem_error(request_id, error),+ }+ }+ #[cfg(not(target_os = "macos"))]+ {+ let _ = (+ artifact,+ target_root,+ target_relative,+ expected_identity,+ token,+ volume_id,+ );+ Response::error(+ Some(request_id),+ "unsupported",+ "reserved exFAT rename requires macOS",+ )+ }+ }+ Request::RenameOpenedReserved {+ request_id,+ artifact,+ reservation,+ } => {+ #[cfg(target_os = "macos")]+ {+ let Some(source) = self.artifacts.get(&artifact).and_then(Option::as_ref)+ else {+ return Response::error(+ Some(request_id),+ "invalid_handle",+ "unknown artifact",+ );+ };+ let Some(reserved) = self.artifacts.get(&reservation).and_then(Option::as_ref)+ else {+ return Response::error(+ Some(request_id),+ "invalid_handle",+ "unknown reservation",+ );+ };+ match crate::platform::rename_opened_reserved(source, reserved) {+ Ok((outcome, identity)) => {+ let mut response = rename_response(request_id, Ok(outcome));+ response.platform_file_id = Some(identity);+ response+ }+ Err(error) => Response::filesystem_error(request_id, error),+ }+ }+ #[cfg(not(target_os = "macos"))]+ {+ let _ = (artifact, reservation);+ Response::error(+ Some(request_id),+ "unsupported",+ "reserved exFAT rename requires macOS",+ )+ }+ }Request::IsolateOpened {request_id,artifact,@@ -312,6 +442,8 @@ impl State {response.held_roots = Some(cfg!(any(unix, windows)));response.directory_sync = Some(cfg!(any(unix, windows)));response.held_artifacts = Some(cfg!(any(unix, windows)));+ response.reserved_exfat_rename = Some(cfg!(target_os = "macos"));+ response.token_exfat_reservation = Some(cfg!(target_os = "macos"));response}diff --git a/src/core/plugin/finalize/filesystem-adapter.ts b/src/core/plugin/finalize/filesystem-adapter.tsindex 046e8399..fefa8531 100644--- a/src/core/plugin/finalize/filesystem-adapter.ts+++ b/src/core/plugin/finalize/filesystem-adapter.ts@@ -43,6 +43,8 @@ export interface FinalizeFsCapabilities {heldRoots: booleandirectorySync: booleanheldArtifacts: boolean+ reservedExfatRename?: boolean+ tokenExfatReservation?: boolean}interface WireResponse {@@ -64,6 +66,10 @@ interface WireResponse {held_roots?: booleandirectory_sync?: booleanheld_artifacts?: boolean+ reserved_exfat_rename?: boolean+ token_exfat_reservation?: boolean+ volume_id?: string+ platform_file_id?: string}interface PendingRequest {@@ -84,8 +90,30 @@ export interface FinalizeArtifactHandle {readonly id: number}+export interface FinalizeReservation {+ handle: FinalizeArtifactHandle+ platformFileId: string+}++export interface FinalizeReservationOwnership {+ token: string+ volumeId: string+}+export interface FinalizeFilesystemAdapter {+ exfatVolumeIdentity?(root: FinalizeRootHandle): Promise<string | null>capabilities(): Promise<FinalizeFsCapabilities>+ reserveExfatTarget?(+ artifact: FinalizeArtifactHandle,+ targetRoot: FinalizeRootHandle,+ targetRelative: string,+ expectedIdentity?: string,+ ownership?: FinalizeReservationOwnership+ ): Promise<FinalizeReservation>+ renameOpenedReserved?(+ artifact: FinalizeArtifactHandle,+ reservation: FinalizeArtifactHandle+ ): Promise<FinalizeRenameResult & { platformFileId: string }>/** Map a final-name candidate onto the shared cross-platform domain. */sanitizeName?(name: string): Promise<string>openRoot(@@ -215,6 +243,64 @@ export class NativeFinalizeFilesystemAdapterheldRoots: response.held_roots === true,directorySync: response.directory_sync === true,heldArtifacts: response.held_artifacts === true,+ reservedExfatRename: response.reserved_exfat_rename === true,+ tokenExfatReservation: response.token_exfat_reservation === true,+ }+ }++ async exfatVolumeIdentity(root: FinalizeRootHandle): Promise<string | null> {+ const response = await this.request({+ op: 'exfat_volume_identity',+ root: this.nativeId(root),+ })+ if (response.volume_id === undefined) return null+ if (!/^[a-f0-9]{32}$/.test(response.volume_id))+ throw new Error('invalid volume identity')+ return response.volume_id+ }++ async reserveExfatTarget(+ artifact: FinalizeArtifactHandle,+ targetRoot: FinalizeRootHandle,+ targetRelative: string,+ expectedIdentity?: string,+ ownership?: FinalizeReservationOwnership+ ): Promise<FinalizeReservation> {+ const generation = this.generation+ const response = await this.request({+ op: 'reserve_exfat_target',+ artifact: this.nativeId(artifact),+ target_root: this.nativeId(targetRoot),+ target_relative: targetRelative,+ expected_identity: expectedIdentity,+ token: ownership?.token,+ volume_id: ownership?.volumeId,+ })+ if (response.handle === undefined || !response.platform_file_id)+ throw new Error('sidecar omitted reservation identity')+ return {+ handle: this.heldHandle(response.handle, generation),+ platformFileId: response.platform_file_id,+ }+ }++ async renameOpenedReserved(+ artifact: FinalizeArtifactHandle,+ reservation: FinalizeArtifactHandle+ ): Promise<FinalizeRenameResult & { platformFileId: string }> {+ const response = await this.request({+ op: 'rename_opened_reserved',+ artifact: this.nativeId(artifact),+ reservation: this.nativeId(reservation),+ })+ if (+ !response.platform_file_id ||+ response.directory_sync_mode !== 'directory_flushed'+ )+ throw new Error('sidecar omitted reserved publication result')+ return {+ platformFileId: response.platform_file_id,+ directorySyncMode: response.directory_sync_mode,}}@@ -453,7 +539,9 @@ export class NativeFinalizeFilesystemAdapterconst result = await response.catch((cause: unknown) => {if (body.op === 'rename_opened_no_replace' ||- body.op === 'rename_no_replace'+ body.op === 'rename_no_replace' ||+ body.op === 'rename_opened_reserved' ||+ body.op === 'reserve_exfat_target') {const error = new FinalizeFsError('io_error',diff --git a/src/core/plugin/finalize/finalize-adversarial.integration.test.ts b/src/core/plugin/finalize/finalize-adversarial.integration.test.tsindex 5deae6b9..072d86de 100644--- a/src/core/plugin/finalize/finalize-adversarial.integration.test.ts+++ b/src/core/plugin/finalize/finalize-adversarial.integration.test.ts@@ -149,8 +149,9 @@ describe.runIf(process.platform !== 'win32' && existsSync(binary))()const [persisted] = await s.repository.listRecoverable()await expect(s.recovery.recover(persisted)).rejects.toThrow(- 'quarantined'+ 'survivor is unavailable')+ expect(await s.repository.listRecoverable()).toHaveLength(1)const survivors = [s.plan.sourcePath,s.plan.targetPath,@@ -298,6 +299,14 @@ describe.runIf(process.platform !== 'win32' && existsSync(binary))(expect(await readFile(pending.removalIntent!.quarantinePath, 'utf8')).toBe('the only complete payload')+ if (mutation === 'missing') {+ await expect(s.recovery.recoverAll()).resolves.toBeUndefined()+ expect(await s.repository.listRecoverable()).toHaveLength(1)+ expect(+ await readFile(pending.removalIntent!.quarantinePath, 'utf8')+ ).toBe('the only complete payload')+ return+ }await s.recovery.recoverAll()expect(s.dbdiff --git a/src/core/plugin/finalize/finalize-committer.test.ts b/src/core/plugin/finalize/finalize-committer.test.tsindex f9350b49..8e9328ee 100644--- a/src/core/plugin/finalize/finalize-committer.test.ts+++ b/src/core/plugin/finalize/finalize-committer.test.ts@@ -143,6 +143,145 @@ function makeCommitter(}describe('FinalizeCommitter', () => {+ it.each([false, true])(+ 'falls back after actual EXDEV despite matching devices (directory: %s)',+ async (directory) => {+ const fs = new FakeFilesystem()+ const plan = makePlan()+ if (directory)+ plan.sourceIdentity = {+ kind: 'directory',+ entryCount: 1,+ totalBytes: 6,+ treeSha256: 'a'.repeat(64),+ platformFileId: '1:1',+ }+ fs.artifacts.set(plan.sourcePath, plan.sourceIdentity)+ const { repository } = makeRepository()+ const checkpoint = vi.spyOn(repository, 'checkpoint')+ vi.spyOn(fs, 'moveNoReplace').mockRejectedValueOnce(+ new FinalizeFsError('cross_device', 'bind mount boundary')+ )+ const materialize = fs.materializePrivate.bind(fs)+ vi.spyOn(fs, 'materializePrivate').mockImplementation(async (...args) => {+ expect(checkpoint).toHaveBeenCalledWith(plan.planId, {+ publicationMode: 'copy',+ })+ return materialize(...args)+ })+ repository.commitTerminal = async (record) => {+ expect(record.publicationMode).toBe('copy')+ expect(fs.artifacts.has(plan.sourcePath)).toBe(true)+ }+ await makeCommitter(fs, repository).commit(plan)+ expect([...fs.artifacts.keys()]).toEqual([plan.targetPath])+ expect(fs.materializePrivate).toHaveBeenCalledOnce()+ }+ )++ it('does not copy if the EXDEV mode checkpoint fails', async () => {+ const fs = new FakeFilesystem()+ const plan = makePlan()+ fs.artifacts.set(plan.sourcePath, sourceIdentity)+ const { repository } = makeRepository()+ vi.spyOn(fs, 'moveNoReplace').mockRejectedValueOnce(+ new FinalizeFsError('cross_device', 'mount boundary')+ )+ vi.spyOn(repository, 'checkpoint').mockRejectedValue(+ new Error('journal offline')+ )+ await expect(makeCommitter(fs, repository).commit(plan)).rejects.toThrow(+ 'journal offline'+ )+ expect(fs.actions.some((action) => action.startsWith('copy:'))).toBe(false)+ expect([...fs.artifacts.keys()]).toEqual([plan.sourcePath])+ })++ it.each(['source', 'target', 'applied'] as const)(+ 'does not fall back after EXDEV when %s changed',+ async (change) => {+ const fs = new FakeFilesystem()+ const plan = makePlan()+ fs.artifacts.set(plan.sourcePath, sourceIdentity)+ const { repository } = makeRepository()+ vi.spyOn(fs, 'moveNoReplace').mockImplementation(async () => {+ if (change !== 'applied')+ fs.artifacts.set(+ change === 'source' ? plan.sourcePath : plan.targetPath,+ replacementIdentity+ )+ throw new FinalizeFsError('cross_device', 'unexpected EXDEV', {+ mutation: change === 'applied' ? 'applied' : 'unknown',+ })+ })+ await expect(makeCommitter(fs, repository).commit(plan)).rejects.toThrow()+ expect(fs.actions.some((action) => action.startsWith('copy:'))).toBe(+ false+ )+ expect(fs.actions.some((action) => action.startsWith('remove:'))).toBe(+ false+ )+ }+ )++ it.each([+ { code: 'permission_denied', osError: 13 },+ { code: 'io_error', osError: 5 },+ { code: 'rename_unsupported', osError: 22 },+ { code: 'rename_unsupported', osError: 38 },+ ] as const)(+ 'does not relax publication on $code/$osError',+ async ({ code, osError }) => {+ const fs = new FakeFilesystem()+ const plan = { ...makePlan(), targetPath: '/save/source' }+ fs.artifacts.set(plan.sourcePath, sourceIdentity)+ const publishReserved = vi.fn()+ Object.assign(fs, {+ publishReserved,+ reservedRenameSupported: async () => true,+ })+ vi.spyOn(fs, 'moveNoReplace').mockRejectedValue(+ new FinalizeFsError(code, 'original failure', {+ operation: 'rename_opened_no_replace',+ osError,+ })+ )+ const { repository } = makeRepository()+ await expect(makeCommitter(fs, repository).commit(plan)).rejects.toThrow(+ 'original failure'+ )+ expect(publishReserved).not.toHaveBeenCalled()+ expect(fs.artifacts.get(plan.sourcePath)).toBe(sourceIdentity)+ }+ )++ it.each(['plugin', 'renamed-target', 'missing-capability'])(+ 'keeps strict publication for %s',+ async (scenario) => {+ const fs = new FakeFilesystem()+ const plan = { ...makePlan(), targetPath: '/save/source' }+ if (scenario === 'plugin') plan.contributors = ['example.plugin']+ if (scenario === 'renamed-target') plan.targetPath = '/save/different'+ fs.artifacts.set(plan.sourcePath, sourceIdentity)+ const publishReserved = vi.fn()+ Object.assign(fs, {+ publishReserved,+ reservedRenameSupported: async () => scenario !== 'missing-capability',+ })+ vi.spyOn(fs, 'moveNoReplace').mockRejectedValue(+ new FinalizeFsError(+ 'rename_unsupported',+ 'exclusive rename unsupported',+ { operation: 'rename_opened_no_replace', osError: 45 }+ )+ )+ const { repository } = makeRepository()+ await expect(makeCommitter(fs, repository).commit(plan)).rejects.toThrow(+ 'exclusive rename unsupported'+ )+ expect(publishReserved).not.toHaveBeenCalled()+ }+ )it('does not compensate a different journal when prepare rejects the retry', 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 5044e058..67e1d62a 100644--- a/src/core/plugin/finalize/finalize-committer.ts+++ b/src/core/plugin/finalize/finalize-committer.ts@@ -1,14 +1,24 @@-import { createHash } from 'node:crypto'+import { createHash, randomBytes } from 'node:crypto'import path from 'node:path'-import type { ArtifactIdentity } from './artifact-identity'+import type {+ ArtifactIdentity,+ FileArtifactIdentity,+} from './artifact-identity'import type {ArtifactMutationLease,ArtifactMutationLeaseCoordinator,} from './artifact-mutation-lease'-import { FinalizeFsError } from './filesystem-adapter'+import {+ FinalizeFsError,+ type FinalizeReservationOwnership,+} from './filesystem-adapter'import { FinalizeRecovery } from './finalize-recovery'import { selectRemovalSurvivor } from './finalize-removal-safety'-import { assertValidHookPlan, type HookPlan } from './hook-plan'+import {+ assertValidHookPlan,+ type HookPlan,+ isOrdinarySuffixRemoval,+} from './hook-plan'export type FinalizeJournalPhase =| 'prepared'@@ -33,7 +43,7 @@ export interface FinalizeJournalRecord {quarantineReason?: string}-export interface FinalizePublicationIntent {+export interface FinalizeLinkIntent {/** Written only after the native exclusive link call returns success. */confirmed?: trueversion: 1@@ -42,6 +52,24 @@ export interface FinalizePublicationIntent {identity: ArtifactIdentity}+interface FinalizeReservedRenameBase {+ method: 'reserved_rename'+ confirmed?: never+ sourcePath: string+ identity: FileArtifactIdentity+ reservationIdentity?: FileArtifactIdentity+}++export type FinalizeReservedRenameIntent = FinalizeReservedRenameBase &+ (+ | { version: 2; ownership?: never }+ | { version: 3; ownership: FinalizeReservationOwnership }+ )++export type FinalizePublicationIntent =+ | FinalizeLinkIntent+ | FinalizeReservedRenameIntent+export interface FinalizeIsolation {directory: stringplatformFileId: string@@ -66,6 +94,7 @@ export interface FinalizeJournalRepository {patch: Partial<Pick<FinalizeJournalRecord,+ | 'publicationMode'| 'privateTargetPath'| 'privateTargetIdentity'| 'targetIdentity'@@ -96,6 +125,16 @@ export interface FinalizeJournalRepository {}export interface FinalizeArtifactOperations {+ reservedRenameSupported?(): Promise<boolean>+ reservedVolumeIdentity?(directoryPath: string): Promise<string | null>+ publishReserved?(+ sourcePath: string,+ expected: FileArtifactIdentity,+ targetPath: string,+ checkpoint: (reservation: FileArtifactIdentity) => Promise<void>,+ reservation?: FileArtifactIdentity,+ ownership?: FinalizeReservationOwnership+ ): Promise<FileArtifactIdentity>/** Validate the actual roots and flush source data before journaled mutation. */preflight?(sourcePath: string, targetPath: string): Promise<void>identity(artifactPath: string): Promise<ArtifactIdentity | null>@@ -215,6 +254,7 @@ export class FinalizeCommitter {const selectedIdentity = plan.replacement?.identity ?? plan.sourceIdentityconst samePath = finalizePathsEquivalent(plan.sourcePath, plan.targetPath)const movesSource = record.publicationMode === 'move'+ let publishedIdentity: ArtifactIdentity | undefinedif (samePath && !plan.replacement) {await this.requireExactIdentity(@@ -226,12 +266,36 @@ export class FinalizeCommitter {} else if (movesSource) {// moveNoReplace validates the expected source identity while holding the// artifact and both roots. Avoid hashing large artifacts once more here.- await this.publish(- record,- plan.sourcePath,- plan.sourceIdentity,- plan.targetPath- )+ try {+ publishedIdentity = await this.publish(+ record,+ plan.sourcePath,+ plan.sourceIdentity,+ plan.targetPath+ )+ } catch (error) {+ // st_dev is only a hint: bind mounts and OverlayFS can return EXDEV+ // even when both paths report the same device. Reconcile the names+ // before durably switching to the existing private-copy protocol.+ if (+ !(error instanceof FinalizeFsError) ||+ error.code !== 'cross_device' ||+ error.details?.mutation === 'applied' ||+ record.publicationIntent+ )+ throw error+ await this.requireExactIdentity(+ plan.sourcePath,+ plan.sourceIdentity,+ record+ )+ if (await this.options.fs.identity(plan.targetPath)) throw error+ await this.options.repository.checkpoint(record.journalId, {+ publicationMode: 'copy',+ })+ record.publicationMode = 'copy'+ return this.commitPrepared(record, _lease)+ }await this.options.fs.makeDurable(plan.targetPath)} else {if (samePath) {@@ -289,11 +353,10 @@ export class FinalizeCommitter {await this.options.fs.makeDurable(plan.targetPath)}- // A same-filesystem rename preserves the platform file identity and the- // move operation already verifies the installed target. Persist that- // identity directly, then retain the final pre-DB verification below.+ // Compatibility publication returns the actual installed identity: FSKit+ // exFAT may change an empty file's ID while the source descriptor stays open.const targetIdentity = movesSource- ? plan.sourceIdentity+ ? (publishedIdentity ?? plan.sourceIdentity): await this.requireExactIdentity(plan.targetPath,samePath && !plan.replacement@@ -316,7 +379,10 @@ export class FinalizeCommitter {record.phase = 'db_committed'let cleanupPending = falsetry {- if (!samePath && (!movesSource || record.publicationIntent)) {+ if (+ !samePath &&+ (!movesSource || record.publicationIntent?.method === 'hard_link')+ ) {await this.requireExactIdentity(plan.sourcePath,plan.sourceIdentity,@@ -324,7 +390,10 @@ export class FinalizeCommitter {)await this.removeTracked(record, plan.sourcePath, plan.sourceIdentity)}- if (record.publicationIntent && record.privateTargetPath) {+ if (+ record.publicationIntent?.method === 'hard_link' &&+ record.privateTargetPath+ ) {await this.removeTracked(record,record.privateTargetPath,@@ -375,19 +444,45 @@ export class FinalizeCommitter {sourcePath: string,identity: ArtifactIdentity,targetPath: string- ): Promise<void> {+ ): Promise<ArtifactIdentity | undefined> {try {await this.options.fs.moveNoReplace(sourcePath, identity, targetPath)} catch (error) {if (!(error instanceof FinalizeFsError) ||error.code !== 'rename_unsupported' ||- identity.kind !== 'file' ||- !this.options.fs.linkNoReplace+ identity.kind !== 'file')throw errorawait this.requireExactIdentity(sourcePath, identity, record)if (await this.options.fs.identity(targetPath)) throw error+ if (+ record.publicationMode === 'move' &&+ isOrdinarySuffixRemoval(record.plan) &&+ error.details?.operation === 'rename_opened_no_replace' &&+ (error.details.osError === 45 || error.details.osError === 102) &&+ this.options.fs.publishReserved &&+ this.options.fs.reservedVolumeIdentity &&+ (await this.options.fs.reservedRenameSupported?.())+ ) {+ const volumeId = await this.options.fs.reservedVolumeIdentity(+ path.dirname(sourcePath)+ )+ if (!volumeId) throw error+ const publicationIntent: FinalizeReservedRenameIntent = {+ version: 3,+ ownership: { token: randomBytes(32).toString('hex'), volumeId },+ method: 'reserved_rename',+ sourcePath,+ identity,+ }+ await this.options.repository.checkpoint(record.journalId, {+ publicationIntent,+ })+ record.publicationIntent = publicationIntent+ return publishReserved(record, this.options.fs, this.options.repository)+ }+ if (!this.options.fs.linkNoReplace) throw errorconst publicationIntent: FinalizePublicationIntent = {version: 1,method: 'hard_link',@@ -514,6 +609,33 @@ export class FinalizeCommitter {}}+/** Persist ownership before replacing a reservation; keep uncertainty recoverable. */+export async function publishReserved(+ record: FinalizeJournalRecord,+ fs: FinalizeArtifactOperations,+ repository: FinalizeJournalRepository+): Promise<FileArtifactIdentity> {+ const intent = record.publicationIntent+ if (intent?.method !== 'reserved_rename' || !fs.publishReserved)+ throw new Error('reserved publication is unsupported')+ const installed = await fs.publishReserved(+ intent.sourcePath,+ intent.identity,+ record.plan.targetPath,+ async (reservationIdentity) => {+ const publicationIntent = { ...intent, reservationIdentity }+ await repository.checkpoint(record.journalId, { publicationIntent })+ record.publicationIntent = publicationIntent+ },+ intent.reservationIdentity,+ intent.ownership+ )+ // Capture a changed file ID before any subsequent host sync can fail.+ await repository.checkpoint(record.journalId, { targetIdentity: installed })+ record.targetIdentity = installed+ return installed+}+export async function prepareRemovalIntent(fs: FinalizeArtifactOperations,journalId: string,diff --git a/src/core/plugin/finalize/finalize-exfat.integration.test.ts b/src/core/plugin/finalize/finalize-exfat.integration.test.tsnew file mode 100644index 00000000..f559a779--- /dev/null+++ b/src/core/plugin/finalize/finalize-exfat.integration.test.ts@@ -0,0 +1,627 @@+// @vitest-environment node+import { execFileSync, spawn } from 'node:child_process'+import { existsSync } from 'node:fs'+import {+ mkdtemp,+ readFile,+ realpath,+ rename,+ 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 {+ defaultRecoveryFs,+ TaskRecoveryServiceImpl,+} from '@core/task/task-recovery-service'+import { TaskStatus, TransitionPhase } from '@shared/types/task'+import { makeDownloadTask } from '@test-utils/task'+import Database from 'better-sqlite3'+import { build } from 'esbuild'+import { afterEach, describe, expect, it, vi } from 'vitest'+import {+ FinalizeFsError,+ NativeFinalizeFilesystemAdapter,+} from './filesystem-adapter'+import { NativeFinalizeArtifactOperations } from './native-artifact-operations'+import { reservationMarker } from './reserved-identity'++const volume = process.env.MOTRIX_FINALIZE_EXFAT_ROOT+// Set only by the disposable-image harness; never detach a user-supplied volume.+const image = process.env.MOTRIX_FINALIZE_EXFAT_TEST_IMAGE+// Disk Arbitration can take several seconds per attach/detach on CI runners.+const diskImageCommandOptions = { timeout: 20_000 }+const binary = path.resolve(+ process.env.MOTRIX_FINALIZE_FS_TEST_BIN ??+ 'packages/finalize-fs/target/debug/motrix-finalize-fs'+)++describe.runIf(+ process.platform === 'darwin' && Boolean(volume) && existsSync(binary)+)('macOS exFAT publication and recovery', () => {+ const cleanup: (() => Promise<void>)[] = []+ afterEach(async () => {+ vi.restoreAllMocks()+ for (const dispose of cleanup.splice(0).reverse()) await dispose()+ })++ async function setup(content = 'complete download', name = '下载.bin') {+ const root = await realpath(+ await mkdtemp(path.join(volume as string, 'motrix-exfat-'))+ )+ const local = await realpath(+ await mkdtemp(path.join(os.tmpdir(), 'motrix-exfat-db-'))+ )+ const dbPath = path.join(local, 'journal.sqlite')+ const sourcePath = path.join(root, `${name}.motrix`)+ const targetPath = path.join(root, name)+ await writeFile(sourcePath, content)+ let commits = 0+ const input = {+ task: makeDownloadTask({+ id: 'exfat-download',+ saveDir: root,+ diskPath: sourcePath,+ finalPath: targetPath,+ status: TaskStatus.Finalizing,+ transitionPhase: TransitionPhase.Renaming,+ }),+ occurrence: null,+ sourcePath,+ targetPath,+ contributors: [],+ metadataOps: [],+ postDeliveries: [],+ }+ const connect = () => {+ const db = new Database(dbPath)+ db.pragma('journal_mode = WAL')+ db.pragma('synchronous = NORMAL')+ migrate(db)+ const adapter = new NativeFinalizeFilesystemAdapter(binary)+ const fs = new NativeFinalizeArtifactOperations(adapter)+ const runtime = new DurableFinalizeRuntime({+ db,+ fs,+ session: {+ persistFinalizedArtifact: async (+ _task,+ _occurrence,+ _effects,+ install+ ) =>+ install((journal) => {+ expect(db.pragma('synchronous', { simple: true })).toBe(2)+ 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+ )+ commits+++ }),+ },+ })+ cleanup.push(async () => {+ await adapter.dispose()+ if (db.open) db.close()+ })+ return { db, adapter, fs, runtime }+ }+ cleanup.push(async () => {+ await rm(root, { recursive: true, force: true })+ await rm(local, { recursive: true, force: true })+ })+ const s = connect()+ const row = () =>+ s.db+ .prepare(+ 'SELECT phase, plan_json, quarantine_reason FROM plugin_finalize_journals'+ )+ .get() as+ | { phase: string; plan_json: string; quarantine_reason: string | null }+ | undefined+ const requireCompatibility = () =>+ vi.spyOn(s.adapter, 'renameOpenedNoReplace').mockRejectedValue(+ new FinalizeFsError(+ 'rename_unsupported',+ 'exclusive rename unsupported',+ {+ operation: 'rename_opened_no_replace',+ osError: 45,+ mutation: 'unknown',+ }+ )+ )+ const restart = async () => {+ await s.adapter.dispose()+ if (s.db.open) s.db.close()+ Object.assign(s, connect())+ }+ const recoverViaTaskService = async () => {+ const service = new TaskRecoveryServiceImpl({+ taskManager: { getAll: () => [input.task], persist: vi.fn() },+ adapter: { listActiveAndWaiting: async () => [] },+ fs: defaultRecoveryFs,+ hasPendingFinalization: (id) => s.runtime.hasPendingFinalization(id),+ finalizeTask: async () => {+ await s.runtime.commit(input)+ },+ activityRecorder: {+ recordSubmitted: vi.fn(),+ recordDownloadCompleted: vi.fn(),+ },+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ })+ const report = await service.recoverOnStartup()+ expect(report.errors).toEqual([])+ expect(report.recovered).toHaveLength(1)+ }+ return {+ ...s,+ connection: s,+ root,+ local,+ dbPath,+ input,+ row,+ restart,+ recoverViaTaskService,+ requireCompatibility,+ commits: () => commits,+ }+ }++ it.each(+ ['', 'complete download', 'x'.repeat(1024 * 1024)].map((content) => ({+ content,+ bytes: content.length,+ }))+ )('finishes real suffix removal ($bytes bytes)', async ({ content }) => {+ const s = await setup(content)+ const before = await s.fs.identity(s.input.sourcePath)+ const copy = vi.spyOn(s.adapter, 'copyOpened')+ const result = await s.runtime.commit(s.input)+ expect(await readFile(s.input.targetPath, 'utf8')).toBe(content)+ expect(existsSync(s.input.sourcePath)).toBe(false)+ expect(result.targetIdentity).toEqual(+ await s.fs.identity(s.input.targetPath)+ )+ expect(result.targetIdentity.kind).toBe(before?.kind)+ expect(s.row()?.phase).toBe('cleaned')+ expect(s.commits()).toBe(1)+ expect(copy).not.toHaveBeenCalled()+ expect(s.db.pragma('synchronous', { simple: true })).toBe(1)+ })++ it('preserves an existing target without creating a reservation', async () => {+ const s = await setup()+ await writeFile(s.input.targetPath, 'unrelated file')+ const reserve = vi.spyOn(s.adapter, 'reserveExfatTarget')+ await expect(s.runtime.commit(s.input)).rejects.toThrow()+ expect(await readFile(s.input.targetPath, 'utf8')).toBe('unrelated file')+ expect(await readFile(s.input.sourcePath, 'utf8')).toBe('complete download')+ expect(reserve).not.toHaveBeenCalled()+ })++ it('refuses a reservation replaced before the native identity check', async () => {+ const s = await setup()+ s.requireCompatibility()+ const real = s.adapter.renameOpenedReserved.bind(s.adapter)+ vi.spyOn(s.adapter, 'renameOpenedReserved').mockImplementation(+ async (...args) => {+ await rename(s.input.targetPath, path.join(s.root, 'old-reservation'))+ await writeFile(s.input.targetPath, 'competing writer')+ return real(...args)+ }+ )+ await expect(s.runtime.commit(s.input)).rejects.toThrow()+ expect(s.row()?.phase).toBe('quarantined')+ expect(await readFile(s.input.targetPath, 'utf8')).toBe('competing writer')+ expect(await readFile(s.input.sourcePath, 'utf8')).toBe('complete download')+ })++ it('recovers a lost reservation response using its pre-journaled token', async () => {+ const s = await setup()+ s.requireCompatibility()+ const real = s.adapter.reserveExfatTarget.bind(s.adapter)+ vi.spyOn(s.adapter, 'reserveExfatTarget').mockImplementation(+ async (...args) => {+ await real(...args)+ throw new Error('lost reservation response')+ }+ )+ await expect(s.runtime.commit(s.input)).rejects.toThrow()+ expect(s.row()?.phase).toBe('prepared')+ const intent = JSON.parse(s.row()!.plan_json).publicationIntent+ expect(await readFile(s.input.targetPath)).toEqual(+ reservationMarker(intent.ownership.token)+ )+ await s.restart()+ await s.recoverViaTaskService()+ expect(s.row()?.phase).toBe('cleaned')+ expect(await readFile(s.input.targetPath, 'utf8')).toBe('complete download')+ expect(existsSync(s.input.sourcePath)).toBe(false)+ })++ it('resumes a journaled reservation after reopening the database and sidecar', async () => {+ const s = await setup()+ s.requireCompatibility()+ vi.spyOn(s.adapter, 'renameOpenedReserved').mockRejectedValue(+ new Error('stopped before rename')+ )+ await expect(s.runtime.commit(s.input)).rejects.toThrow(+ 'stopped before rename'+ )+ expect(s.row()?.phase).toBe('prepared')+ await s.restart()+ await s.connection.runtime.recoverAll()+ expect(s.row()?.phase).toBe('prepared')+ await s.recoverViaTaskService()+ expect(s.row()?.phase).toBe('cleaned')+ expect(await readFile(s.input.targetPath, 'utf8')).toBe('complete download')+ expect(existsSync(s.input.sourcePath)).toBe(false)+ expect(s.commits()).toBe(1)+ })++ it('recovers a lost successful rename response without replay or rollback', async () => {+ const s = await setup()+ s.requireCompatibility()+ const real = s.adapter.renameOpenedReserved.bind(s.adapter)+ vi.spyOn(s.adapter, 'renameOpenedReserved').mockImplementation(+ async (...args) => {+ await real(...args)+ throw new Error('lost rename response')+ }+ )+ await expect(s.runtime.commit(s.input)).rejects.toThrow(+ 'lost rename response'+ )+ expect(s.row()?.phase).toBe('target_installed')+ await s.restart()+ await s.connection.runtime.recoverAll()+ expect(s.row()?.phase).toBe('target_installed')+ const renameAgain = vi.spyOn(s.connection.adapter, 'renameOpenedReserved')+ await s.recoverViaTaskService()+ expect(renameAgain).not.toHaveBeenCalled()+ expect(s.row()?.phase).toBe('cleaned')+ expect(s.commits()).toBe(1)+ })++ it('keeps an installed empty file when its acknowledged identity precedes a later sync failure', async () => {+ const s = await setup('')+ s.requireCompatibility()+ const real = s.fs.makeDurable.bind(s.fs)+ vi.spyOn(s.fs, 'makeDurable').mockImplementation(async (file) => {+ if (file === s.input.targetPath)+ throw new Error('post-install sync failed')+ return real(file)+ })+ await expect(s.runtime.commit(s.input)).rejects.toThrow()+ expect(s.row()?.phase).toBe('prepared')+ expect(JSON.parse(s.row()!.plan_json).targetIdentity).toEqual(+ await s.fs.identity(s.input.targetPath)+ )+ await s.restart()+ await s.connection.runtime.recoverAll()+ await s.connection.runtime.commit(s.input)+ expect(s.row()?.phase).toBe('cleaned')+ expect(await readFile(s.input.targetPath)).toHaveLength(0)+ })++ it('does not rename after the reservation checkpoint fails', async () => {+ const s = await setup()+ s.requireCompatibility()+ const real = SqliteFinalizeJournalRepository.prototype.checkpoint+ vi.spyOn(+ SqliteFinalizeJournalRepository.prototype,+ 'checkpoint'+ ).mockImplementation(async function (+ this: SqliteFinalizeJournalRepository,+ id,+ patch+ ) {+ if (+ patch.publicationIntent?.method === 'reserved_rename' &&+ patch.publicationIntent.reservationIdentity+ )+ throw new Error('reservation checkpoint failed')+ return real.call(this, id, patch)+ })+ const renameReserved = vi.spyOn(s.adapter, 'renameOpenedReserved')+ await expect(s.runtime.commit(s.input)).rejects.toThrow()+ expect(renameReserved).not.toHaveBeenCalled()+ expect(existsSync(s.input.sourcePath)).toBe(true)+ expect(await readFile(s.input.targetPath)).toEqual(+ reservationMarker(+ JSON.parse(s.row()!.plan_json).publicationIntent.ownership.token+ )+ )+ })++ it('preserves a target created between the unsupported rename and reservation', async () => {+ const s = await setup()+ s.requireCompatibility()+ const real = s.adapter.reserveExfatTarget.bind(s.adapter)+ vi.spyOn(s.adapter, 'reserveExfatTarget').mockImplementation(+ async (...args) => {+ await writeFile(s.input.targetPath, 'concurrent download')+ return real(...args)+ }+ )+ await expect(s.runtime.commit(s.input)).rejects.toThrow()+ expect(await readFile(s.input.targetPath, 'utf8')).toBe(+ 'concurrent download'+ )+ expect(await readFile(s.input.sourcePath, 'utf8')).toBe('complete download')+ })++ it('does not infer an unacknowledged empty-file identity transition from equal content', async () => {+ const s = await setup('')+ const before = await s.fs.identity(s.input.sourcePath)+ s.requireCompatibility()+ const real = s.adapter.renameOpenedReserved.bind(s.adapter)+ vi.spyOn(s.adapter, 'renameOpenedReserved').mockImplementation(+ async (...args) => {+ await real(...args)+ throw new Error('lost empty-file rename response')+ }+ )+ await expect(s.runtime.commit(s.input)).rejects.toThrow()+ const after = await s.fs.identity(s.input.targetPath)+ expect(s.row()?.phase).toBe(+ before?.platformFileId === after?.platformFileId+ ? 'target_installed'+ : 'quarantined'+ )+ expect(existsSync(s.input.sourcePath)).toBe(false)+ expect(await readFile(s.input.targetPath)).toHaveLength(0)+ expect(s.commits()).toBe(0)+ })++ it('retries a failed terminal transaction without replaying publication', async () => {+ const s = await setup()+ s.requireCompatibility()+ const real = SqliteFinalizeJournalRepository.prototype.commitTerminal+ const failure = vi+ .spyOn(SqliteFinalizeJournalRepository.prototype, 'commitTerminal')+ .mockRejectedValue(new Error('database unavailable'))+ await expect(s.runtime.commit(s.input)).rejects.toThrow(+ 'database unavailable'+ )+ expect(s.row()?.phase).toBe('target_installed')+ failure.mockImplementation(real)+ const renameAgain = vi.spyOn(s.adapter, 'renameOpenedReserved')+ await s.recoverViaTaskService()+ expect(renameAgain).not.toHaveBeenCalled()+ expect(s.row()?.phase).toBe('cleaned')+ expect(s.commits()).toBe(1)+ })++ it('revalidates the installed target after recovery flushes before committing', async () => {+ const s = await setup()+ s.requireCompatibility()+ const failedCommit = vi+ .spyOn(SqliteFinalizeJournalRepository.prototype, 'commitTerminal')+ .mockRejectedValue(new Error('database unavailable'))+ await expect(s.runtime.commit(s.input)).rejects.toThrow()+ failedCommit.mockRestore()+ const real = s.fs.makeDurable.bind(s.fs)+ vi.spyOn(s.fs, 'makeDurable').mockImplementation(async (file) => {+ await real(file)+ if (file === s.input.targetPath)+ await writeFile(file, 'changed during recovery')+ })+ await expect(s.runtime.commit(s.input)).rejects.toThrow(+ 'reserved target changed before commit'+ )+ expect(s.commits()).toBe(0)+ expect(s.row()?.phase).toBe('quarantined')+ expect(await readFile(s.input.targetPath, 'utf8')).toBe(+ 'changed during recovery'+ )+ })++ it('does not fail a recovered task after its terminal transaction has committed', async () => {+ const s = await setup()+ s.requireCompatibility()+ const failedCommit = vi+ .spyOn(SqliteFinalizeJournalRepository.prototype, 'commitTerminal')+ .mockRejectedValue(new Error('database unavailable'))+ await expect(s.runtime.commit(s.input)).rejects.toThrow()+ failedCommit.mockRestore()+ const advance = SqliteFinalizeJournalRepository.prototype.advance+ const failedCleanup = vi+ .spyOn(SqliteFinalizeJournalRepository.prototype, 'advance')+ .mockImplementation(async function (+ this: SqliteFinalizeJournalRepository,+ id,+ phase,+ patch+ ) {+ if (phase === 'cleaned') throw new Error('cleanup unavailable')+ return advance.call(this, id, phase, patch)+ })+ await expect(s.runtime.commit(s.input)).resolves.toMatchObject({+ targetPath: s.input.targetPath,+ cleanupPending: true,+ })+ expect(s.row()?.phase).toBe('db_committed')+ expect(s.commits()).toBe(1)+ failedCleanup.mockRestore()+ await s.runtime.recoverAll()+ expect(s.row()?.phase).toBe('cleaned')+ expect(s.commits()).toBe(1)+ expect(await readFile(s.input.targetPath, 'utf8')).toBe('complete download')+ })+ it.runIf(Boolean(image))(+ 'resumes the owned reservation after an exFAT remount',+ async () => {+ const s = await setup()+ s.requireCompatibility()+ vi.spyOn(s.adapter, 'renameOpenedReserved').mockRejectedValue(+ new Error('stopped before rename')+ )+ await expect(s.runtime.commit(s.input)).rejects.toThrow()+ const volumeId = await s.fs.reservedVolumeIdentity(s.root)+ await s.adapter.dispose()+ execFileSync('hdiutil', ['detach', volume!], diskImageCommandOptions)+ execFileSync(+ 'hdiutil',+ ['attach', image!, '-mountpoint', volume!, '-nobrowse'],+ diskImageCommandOptions+ )+ await s.restart()+ expect(await s.connection.fs.reservedVolumeIdentity(s.root)).toBe(+ volumeId+ )+ await s.connection.runtime.recoverAll()+ expect(s.row()?.phase).toBe('prepared')+ await s.recoverViaTaskService()+ expect(s.row()?.phase).toBe('cleaned')+ expect(await readFile(s.input.targetPath, 'utf8')).toBe(+ 'complete download'+ )+ expect(existsSync(s.input.sourcePath)).toBe(false)+ },+ 60_000+ )++ it.runIf(Boolean(image))(+ 'waits for an offline volume and completes after reconnection',+ async () => {+ const s = await setup()+ s.requireCompatibility()+ vi.spyOn(s.adapter, 'renameOpenedReserved').mockRejectedValue(+ new Error('stopped before rename')+ )+ await expect(s.runtime.commit(s.input)).rejects.toThrow()+ await s.adapter.dispose()+ execFileSync('hdiutil', ['detach', volume!], diskImageCommandOptions)+ try {+ await s.restart()+ await s.connection.runtime.recoverAll()+ expect(s.row()?.phase).toBe('prepared')+ await expect(s.connection.runtime.commit(s.input)).rejects.toThrow()+ expect(s.row()?.phase).toBe('prepared')+ } finally {+ execFileSync(+ 'hdiutil',+ ['attach', image!, '-mountpoint', volume!, '-nobrowse'],+ diskImageCommandOptions+ )+ }+ await s.recoverViaTaskService()+ expect(s.row()?.phase).toBe('cleaned')+ expect(await readFile(s.input.targetPath, 'utf8')).toBe(+ 'complete download'+ )+ },+ 60_000+ )++ it('rejects a changed marker even when its size is unchanged', async () => {+ const s = await setup()+ s.requireCompatibility()+ vi.spyOn(s.adapter, 'renameOpenedReserved').mockRejectedValue(+ new Error('stopped before rename')+ )+ await expect(s.runtime.commit(s.input)).rejects.toThrow()+ const foreign = reservationMarker('f'.repeat(64))+ await writeFile(s.input.targetPath, foreign)+ await s.restart()+ await s.connection.runtime.recoverAll()+ expect(s.row()?.phase).toBe('quarantined')+ expect(await readFile(s.input.targetPath)).toEqual(foreign)+ expect(await readFile(s.input.sourcePath, 'utf8')).toBe('complete download')+ })++ it.each([+ 'reservation-created',+ 'target-installed',+ 'before-terminal-commit',+ ])(+ 'recovers after SIGKILL at %s without running compensation',+ async (cut) => {+ const s = await setup()+ await s.adapter.dispose()+ s.db.close()+ const childPath = path.join(s.local, 'crash-child.cjs')+ await build({+ entryPoints: ['src/test-utils/finalize-crash-child.ts'],+ outfile: childPath,+ bundle: true,+ platform: 'node',+ format: 'cjs',+ packages: 'external',+ banner: {+ js: `require = require('node:module').createRequire(${JSON.stringify(path.join(process.cwd(), 'package.json'))});`,+ },+ })+ const child = spawn(+ process.execPath,+ [childPath, s.dbPath, binary, cut, JSON.stringify(s.input)],+ { stdio: ['ignore', 'pipe', 'pipe'] }+ )+ let stderr = ''+ child.stderr.on('data', (chunk) => {+ stderr += chunk+ })+ try {+ await new Promise<void>((resolve, reject) => {+ const timer = setTimeout(+ () => reject(new Error(`crash child timed out: ${stderr}`)),+ 15_000+ )+ let output = ''+ child.once('error', (error) => {+ clearTimeout(timer)+ reject(error)+ })+ child.once('exit', (code) => {+ clearTimeout(timer)+ reject(new Error(`crash child exited ${code}: ${stderr}`))+ })+ child.stdout.on('data', (chunk) => {+ output += chunk+ if (output.includes('FINALIZE_CRASH_CUT')) {+ clearTimeout(timer)+ resolve()+ }+ })+ })+ const killed = new Promise<string | null>((resolve) =>+ child.once('close', (_code, signal) => resolve(signal))+ )+ child.kill('SIGKILL')+ expect(await killed).toBe('SIGKILL')+ } finally {+ if (child.exitCode === null && child.signalCode === null)+ child.kill('SIGKILL')+ }+ await s.restart()+ await s.connection.runtime.recoverAll()+ expect(s.row()?.phase).not.toBe('quarantined')+ await s.recoverViaTaskService()+ expect(s.row()?.phase).toBe('cleaned')+ expect(await readFile(s.input.targetPath, 'utf8')).toBe(+ 'complete download'+ )+ expect(existsSync(s.input.sourcePath)).toBe(false)+ expect(s.commits()).toBe(1)+ },+ 30_000+ )+})diff --git a/src/core/plugin/finalize/finalize-filesystems.integration.test.ts b/src/core/plugin/finalize/finalize-filesystems.integration.test.tsnew file mode 100644index 00000000..4463f949--- /dev/null+++ b/src/core/plugin/finalize/finalize-filesystems.integration.test.ts@@ -0,0 +1,312 @@+// @vitest-environment node+import { existsSync } from 'node:fs'+import {+ mkdir,+ mkdtemp,+ readFile,+ realpath,+ rename,+ rm,+ stat,+ statfs,+ writeFile,+} from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { DurableFinalizeRuntime } from '@core/session/durable-finalize-runtime'+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 { NativeFinalizeFilesystemAdapter } from './filesystem-adapter'+import { NativeFinalizeArtifactOperations } from './native-artifact-operations'++const root = process.env.MOTRIX_FINALIZE_MATRIX_ROOT+const bindRoot = process.env.MOTRIX_FINALIZE_MATRIX_BIND_ROOT+const fsType = process.env.MOTRIX_FINALIZE_MATRIX_TYPE+const binary = path.resolve(+ process.env.MOTRIX_FINALIZE_FS_TEST_BIN ??+ 'packages/finalize-fs/target/debug/motrix-finalize-fs'+)+if (root && (process.platform !== 'linux' || !existsSync(binary) || !fsType))+ throw new Error(+ 'filesystem matrix requires Linux, a built sidecar and the expected filesystem type'+ )+const magic: Record<string, number> = {+ ext4: 0xef53,+ btrfs: 0x9123683e,+ xfs: 0x58465342,+ f2fs: 0xf2f52010,+ vfat: 0x4d44,+ exfat: 0x2011bab0,+ ntfs3: 0x7366746e,+ 'ntfs-3g': 0x65735546,+ tmpfs: 0x01021994,+ overlay: 0x794c7630,+}++describe.runIf(Boolean(root))(+ 'mounted Linux filesystem publication',+ { timeout: 30_000 },+ () => {+ const cleanups: (() => Promise<void>)[] = []+ afterEach(async () => {+ vi.restoreAllMocks()+ for (const cleanup of cleanups.splice(0)) await cleanup()+ })++ async function setup(+ mode: 'same' | 'copy' | 'bind' = 'same',+ name = 'download.bin',+ directory = false+ ) {+ expect((await statfs(root!)).type >>> 0).toBe(magic[fsType!])+ const local = await realpath(+ await mkdtemp(path.join(os.tmpdir(), 'motrix-matrix-db-'))+ )+ const artifacts = await realpath(+ await mkdtemp(path.join(root!, 'motrix-matrix-'))+ )+ const source = path.join(+ mode === 'copy' ? local : artifacts,+ `${name}.motrix`+ )+ const target = path.join(+ mode === 'bind'+ ? path.join(bindRoot!, path.basename(artifacts))+ : artifacts,+ name+ )+ if (directory) {+ await mkdir(source)+ await writeFile(path.join(source, 'leaf'), 'payload')+ } else await writeFile(source, name === 'empty' ? '' : 'payload')+ let db: Database.Database+ let adapter: NativeFinalizeFilesystemAdapter+ let fs: NativeFinalizeArtifactOperations+ let runtime: DurableFinalizeRuntime+ const start = () => {+ db = new Database(path.join(local, 'journal.sqlite'))+ migrate(db)+ adapter = new NativeFinalizeFilesystemAdapter(binary)+ fs = new NativeFinalizeArtifactOperations(adapter)+ runtime = new DurableFinalizeRuntime({+ db,+ fs,+ session: {+ persistFinalizedArtifact: async (+ _task,+ _occurrence,+ _effects,+ commit+ ) =>+ commit((journal) => {+ const row = 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(row.plan_json),+ phase: 'db_committed',+ }),+ journal.journalId+ )+ }),+ },+ })+ }+ start()+ cleanups.push(async () => {+ await adapter.dispose()+ db.close()+ await rm(artifacts, { recursive: true, force: true })+ await rm(local, { recursive: true, force: true })+ })+ const input = {+ task: makeDownloadTask({+ id: 'task-matrix',+ saveDir: path.dirname(target),+ diskPath: source,+ finalPath: target,+ }),+ occurrence: null,+ sourcePath: source,+ targetPath: target,+ metadataOps: [],+ contributors: [],+ postDeliveries: [],+ }+ return {+ source,+ target,+ input,+ get runtime() {+ return runtime+ },+ get fs() {+ return fs+ },+ get adapter() {+ return adapter+ },+ rows: () =>+ db+ .prepare('SELECT phase, plan_json FROM plugin_finalize_journals')+ .all() as { phase: string; plan_json: string }[],+ async restart() {+ await adapter.dispose()+ db.close()+ start()+ },+ }+ }++ it.each(['empty', '中文-é-😀.bin', 'a'.repeat(240)])(+ 'publishes %s without copying',+ async (name) => {+ const state = await setup('same', name)+ const copy = vi.spyOn(state.fs, 'materializePrivate')+ await state.runtime.commit(state.input)+ expect(await readFile(state.target, 'utf8')).toBe(+ name === 'empty' ? '' : 'payload'+ )+ expect(existsSync(state.source)).toBe(false)+ expect(copy).not.toHaveBeenCalled()+ expect(state.rows().at(-1)?.phase).toBe('cleaned')+ }+ )++ it('preserves an existing target and its source', async () => {+ const state = await setup()+ await writeFile(state.target, 'unrelated')+ await expect(state.runtime.commit(state.input)).rejects.toThrow()+ expect(await readFile(state.target, 'utf8')).toBe('unrelated')+ expect(await readFile(state.source, 'utf8')).toBe('payload')+ })++ it('respects the mounted filesystem case sensitivity on target conflicts', async () => {+ const state = await setup()+ const otherCase = path.join(path.dirname(state.target), 'DOWNLOAD.BIN')+ await writeFile(otherCase, 'unrelated')+ if (existsSync(state.target)) {+ await expect(state.runtime.commit(state.input)).rejects.toThrow()+ expect(await readFile(state.source, 'utf8')).toBe('payload')+ } else {+ await state.runtime.commit(state.input)+ expect(await readFile(state.target, 'utf8')).toBe('payload')+ }+ expect(await readFile(otherCase, 'utf8')).toBe('unrelated')+ })++ it('keeps unavailable paths retryable and finishes after they return', async () => {+ const state = await setup()+ const directory = path.dirname(state.source)+ const hidden = `${directory}-offline`+ vi.spyOn(state.fs, 'moveNoReplace').mockImplementationOnce(async () => {+ await rename(directory, hidden)+ throw new Error('storage disconnected')+ })+ try {+ await expect(state.runtime.commit(state.input)).rejects.toThrow()+ expect(state.rows().at(-1)?.phase).toBe('prepared')+ } finally {+ if (existsSync(hidden)) await rename(hidden, directory)+ }+ await state.restart()+ await state.runtime.commit(state.input)+ expect(await readFile(state.target, 'utf8')).toBe('payload')+ expect(existsSync(state.source)).toBe(false)+ expect(state.rows().every((row) => row.phase === 'cleaned')).toBe(true)+ })++ it('copies across real devices and removes the source only after commit', async () => {+ const state = await setup('copy')+ expect((await stat(state.source)).dev).not.toBe(+ (await stat(path.dirname(state.target))).dev+ )+ await state.runtime.commit(state.input)+ expect(await readFile(state.target, 'utf8')).toBe('payload')+ expect(existsSync(state.source)).toBe(false)+ expect(state.rows().at(-1)?.phase).toBe('cleaned')+ })++ it.runIf(Boolean(bindRoot))(+ 'copies across bind mounts despite equal device numbers',+ async () => {+ const state = await setup('bind')+ expect((await stat(state.source)).dev).toBe(+ (await stat(path.dirname(state.target))).dev+ )+ const move = vi.spyOn(state.adapter, 'renameOpenedNoReplace')+ const copy = vi.spyOn(state.fs, 'materializePrivate')+ await state.runtime.commit(state.input)+ expect(+ await move.mock.results[0].value.catch((error: unknown) => error)+ ).toMatchObject({ code: 'cross_device' })+ expect(copy).toHaveBeenCalledOnce()+ expect(await readFile(state.target, 'utf8')).toBe('payload')+ expect(existsSync(state.source)).toBe(false)+ expect(state.rows().at(-1)?.phase).toBe('cleaned')+ }+ )++ it('recovers a lost publication response after reopening SQLite and the sidecar', async () => {+ const state = await setup()+ if (fsType === 'ntfs-3g') {+ const link = state.adapter.linkOpenedNoReplace.bind(state.adapter)+ vi.spyOn(state.adapter, 'linkOpenedNoReplace').mockImplementation(+ async (...args) => {+ await link(...args)+ throw new Error('lost link response')+ }+ )+ await expect(state.runtime.commit(state.input)).rejects.toThrow()+ await state.restart()+ // An unacknowledged hard link cannot be distinguished from a link+ // created by another client. Preserve both names for reconciliation.+ await expect(state.runtime.commit(state.input)).rejects.toThrow()+ expect(await readFile(state.source, 'utf8')).toBe('payload')+ expect(await readFile(state.target, 'utf8')).toBe('payload')+ expect(state.rows().some((row) => row.phase === 'quarantined')).toBe(+ true+ )+ return+ }+ const original = state.fs.moveNoReplace.bind(state.fs)+ const move = vi+ .spyOn(state.fs, 'moveNoReplace')+ .mockImplementation(async (...args) => {+ await original(...args)+ throw new Error('lost response')+ })+ await expect(state.runtime.commit(state.input)).rejects.toThrow()+ move.mockRestore()+ await state.restart()+ await state.runtime.commit(state.input)+ expect(await readFile(state.target, 'utf8')).toBe('payload')+ expect(existsSync(state.source)).toBe(false)+ expect(state.rows().at(-1)?.phase).toBe('cleaned')+ })++ it('publishes directory artifacts where exclusive directory rename is supported', async () => {+ const state = await setup('same', 'tree', true)+ if (fsType === 'ntfs-3g') {+ await expect(state.runtime.commit(state.input)).rejects.toThrow()+ expect(await readFile(path.join(state.source, 'leaf'), 'utf8')).toBe(+ 'payload'+ )+ expect(existsSync(state.target)).toBe(false)+ return+ }+ await state.runtime.commit(state.input)+ expect(await readFile(path.join(state.target, 'leaf'), 'utf8')).toBe(+ 'payload'+ )+ expect(existsSync(state.source)).toBe(false)+ })+ }+)diff --git a/src/core/plugin/finalize/finalize-recovery-errors.ts b/src/core/plugin/finalize/finalize-recovery-errors.tsnew file mode 100644index 00000000..ebbcfae0--- /dev/null+++ b/src/core/plugin/finalize/finalize-recovery-errors.ts@@ -0,0 +1,48 @@+import { constants } from 'node:os'+import { ArtifactIdentityError } from './artifact-identity'+import { FinalizeFsError } from './filesystem-adapter'++/** Storage absence must block this task's retry without blocking app startup. */+export class FinalizeRecoveryDeferredError extends Error {+ constructor(message: string) {+ super(message)+ this.name = 'FinalizeRecoveryDeferredError'+ }+}++const unavailableCodes = [+ 'ENOENT',+ 'ENODEV',+ 'ENXIO',+ 'ESTALE',+ 'ENOTCONN',+ 'ECONNRESET',+ 'ECONNREFUSED',+ 'ENETDOWN',+ 'ENETUNREACH',+ 'EHOSTDOWN',+ 'EHOSTUNREACH',+ 'ETIMEDOUT',+] as const++/** Limit startup deferral to missing/disconnected storage, not arbitrary I/O. */+export function isUnavailableArtifactError(error: unknown): boolean {+ if (error instanceof FinalizeRecoveryDeferredError) return true+ if (error instanceof ArtifactIdentityError)+ return error.code === 'artifact_missing'+ if (error instanceof FinalizeFsError) {+ if (error.code === 'not_found') return true+ if (process.platform === 'win32') return false+ const errno = constants.errno as Record<string, number | undefined>+ return (+ error.code === 'io_error' &&+ error.details?.osError !== undefined &&+ unavailableCodes.some((code) => errno[code] === error.details?.osError)+ )+ }+ return (+ error instanceof Error &&+ 'code' in error &&+ unavailableCodes.some((code) => code === error.code)+ )+}diff --git a/src/core/plugin/finalize/finalize-recovery.test.ts b/src/core/plugin/finalize/finalize-recovery.test.tsindex 9d282576..24ea397a 100644--- a/src/core/plugin/finalize/finalize-recovery.test.ts+++ b/src/core/plugin/finalize/finalize-recovery.test.ts@@ -1,3 +1,4 @@+import { constants } from 'node:os'import { describe, expect, it, vi } from 'vitest'import {type ArtifactIdentity,@@ -5,6 +6,7 @@ import {artifactIdentityEquals,} from './artifact-identity'import { ArtifactMutationLeaseCoordinator } from './artifact-mutation-lease'+import { FinalizeFsError } from './filesystem-adapter'import type {FinalizeArtifactOperations,FinalizeJournalRecord,@@ -94,10 +96,171 @@ function fixture(sameContent: artifactContentEquals,rollForwardTargetInstalled: options.rollForwardTargetInstalled,})- return { artifacts, phases, quarantines, recovery }+ return { artifacts, phases, quarantines, recovery, fs, repository }}describe('FinalizeRecovery', () => {+ it.each([+ 'ENOENT',+ 'ENODEV',+ 'ESTALE',+ 'ENOTCONN',+ 'ECONNRESET',+ 'ETIMEDOUT',+ ])('defers startup for %s while explicit retry still fails', async (code) => {+ const pending = record('prepared')+ const state = fixture({}, { recoverable: [pending] })+ state.fs.identity = async () => {+ throw Object.assign(new Error('storage unavailable'), { code })+ }+ await expect(state.recovery.recoverAll()).resolves.toBeUndefined()+ await expect(state.recovery.recover(pending)).rejects.toThrow(+ 'storage unavailable'+ )+ expect(state.quarantines).toEqual([])+ expect(state.phases).toEqual([])+ })++ it.skipIf(process.platform === 'win32')(+ 'defers a native stale mount error without discarding its journal',+ async () => {+ const pending = record('prepared')+ const state = fixture({}, { recoverable: [pending] })+ state.fs.identity = async () => {+ throw new FinalizeFsError('io_error', 'stale mount', {+ osError: constants.errno.ESTALE,+ })+ }+ await expect(state.recovery.recoverAll()).resolves.toBeUndefined()+ expect(state.phases).toEqual([])+ }+ )++ it.each(['EIO', 'EACCES', 'EBADF', 'SQLITE_IOERR'])(+ 'does not hide unrelated %s failures during startup',+ async (code) => {+ const pending = record('prepared')+ const state = fixture({}, { recoverable: [pending] })+ state.fs.identity = async () => {+ throw Object.assign(new Error('real failure'), { code })+ }+ await expect(state.recovery.recoverAll()).rejects.toThrow(+ 'one or more finalize journals failed'+ )+ }+ )++ it.each([+ 'prepared',+ 'target_staged',+ 'target_installed',+ 'db_committed',+ ] as const)(+ 'keeps %s retryable while all artifacts are unavailable',+ async (phase) => {+ const pending = record(phase)+ pending.publicationMode = 'move'+ const state = fixture({}, { recoverable: [pending] })+ await expect(state.recovery.recover(pending)).rejects.toThrow(+ 'unavailable'+ )+ await expect(state.recovery.recoverAll()).resolves.toBeUndefined()+ expect(state.quarantines).toEqual([])+ expect(state.phases).toEqual([])+ }+ )++ it('resumes committed cleanup when its surviving target returns', async () => {+ const pending = record('db_committed')+ pending.removalIntent = {+ artifactPath: '/save/source',+ quarantinePath: '/save/.remove',+ identity: sourceIdentity,+ }+ const state = fixture({ '/save/source': sourceIdentity })+ await expect(state.recovery.recover(pending)).rejects.toThrow(+ 'survivor is unavailable'+ )+ expect(state.quarantines).toEqual([])+ expect(state.artifacts.get('/save/source')).toBe(sourceIdentity)+ state.artifacts.set('/save/target', targetIdentity)+ await state.recovery.recover(pending)+ expect([...state.artifacts.keys()]).toEqual(['/save/target'])+ expect(state.phases).toEqual(['cleaned'])+ })++ function reservedRecord(): FinalizeJournalRecord {+ const pending = record('prepared')+ pending.plan.sourcePath = '/save/target.motrix'+ pending.publicationMode = 'move'+ pending.targetIdentity = undefined+ pending.publicationIntent = {+ version: 3,+ method: 'reserved_rename',+ sourcePath: pending.plan.sourcePath,+ identity:+ sourceIdentity as import('./artifact-identity').FileArtifactIdentity,+ ownership: { volumeId: 'a'.repeat(32), token: 'b'.repeat(64) },+ }+ return pending+ }++ it.each([null, 'f'.repeat(32)])(+ 'defers an unavailable or different reserved volume (%s)',+ async (volume) => {+ const pending = reservedRecord()+ const state = fixture({ '/save/target': targetIdentity })+ state.fs.reservedVolumeIdentity = async () => volume+ const identity = vi.spyOn(state.fs, 'identity')+ await state.recovery.recover(pending)+ expect(identity).not.toHaveBeenCalled()+ expect(state.quarantines).toEqual([])+ expect(state.phases).toEqual([])+ }+ )++ it('does not quarantine a volume detached between the probe and file reads', async () => {+ const state = fixture({})+ state.fs.reservedVolumeIdentity = vi+ .fn()+ .mockResolvedValueOnce('a'.repeat(32))+ .mockResolvedValue(null)+ await state.recovery.recover(reservedRecord())+ expect(state.quarantines).toEqual([])+ expect(state.phases).toEqual([])+ })++ it('accepts a changed mount device only with the same volume, inode and content', async () => {+ const pending = reservedRecord()+ const current = { ...sourceIdentity, platformFileId: '9:1' }+ const state = fixture({ '/save/target': current })+ state.fs.reservedVolumeIdentity = async () => 'a'.repeat(32)+ await state.recovery.recover(pending)+ expect(state.quarantines).toEqual([])+ expect(pending.targetIdentity).toEqual(current)+ expect(state.phases).toEqual([+ 'target_installed',+ 'db_committed',+ 'cleaned',+ ])+ })++ it.each([+ { ...sourceIdentity, platformFileId: '9:2' },+ { ...sourceIdentity, platformFileId: '9:1', sha256: 'c'.repeat(64) },+ ])(+ 'quarantines a foreign installed file on the expected volume: %j',+ async (foreign) => {+ const state = fixture({ '/save/target': foreign })+ state.fs.reservedVolumeIdentity = async () => 'a'.repeat(32)+ await expect(state.recovery.recover(reservedRecord())).rejects.toThrow(+ 'quarantined'+ )+ expect(state.artifacts.get('/save/target')).toEqual(foreign)+ expect(state.phases).toEqual([])+ }+ )+it('finishes the atomic DB transaction from a verified installed target', async () => {const state = fixture({'/save/source': sourceIdentity,@@ -261,7 +424,9 @@ describe('FinalizeRecovery', () => {staged.privateTargetIdentity = targetIdentityconst state = fixture(source ? { '/save/source': source } : {})await expect(state.recovery.recover(staged)).rejects.toThrow(- 'source changed before install recovery'+ source+ ? 'source changed before install recovery'+ : 'artifacts are unavailable')expect(state.phases).not.toContain('cleaned')if (source) expect(state.artifacts.get('/save/source')).toBe(source)diff --git a/src/core/plugin/finalize/finalize-recovery.ts b/src/core/plugin/finalize/finalize-recovery.tsindex c9c7ef47..68ce0a71 100644--- a/src/core/plugin/finalize/finalize-recovery.ts+++ b/src/core/plugin/finalize/finalize-recovery.ts@@ -1,3 +1,5 @@+import path from 'node:path'+import { getLogger } from '@core/logger'import type {ArtifactMutationLease,ArtifactMutationLeaseCoordinator,@@ -9,12 +11,20 @@ import {FinalizeQuarantinedError,finalizePathsEquivalent,prepareRemovalIntent,+ publishReserved,} from './finalize-committer'-+import {+ FinalizeRecoveryDeferredError,+ isUnavailableArtifactError,+} from './finalize-recovery-errors'import {linkPublicationConfirmed,selectRemovalSurvivor,} from './finalize-removal-safety'+import {+ reservationMatches,+ reservedArtifactMatches,+} from './reserved-identity'export interface FinalizeRecoveryOptions {repository: FinalizeJournalRepository@@ -40,6 +50,13 @@ export class FinalizeRecovery {try {await this.recover(record)} catch (error) {+ if (isUnavailableArtifactError(error)) {+ getLogger('finalize').warn(+ { journalId: record.journalId, err: error },+ 'finalize recovery deferred until artifacts are available'+ )+ continue+ }if (!(error instanceof FinalizeQuarantinedError)) failures.push(error)}}@@ -86,6 +103,10 @@ export class FinalizeRecovery {await this.options.repository.resumeQuarantined(record)record.quarantineReason = undefined}+ if (record.publicationIntent?.method === 'reserved_rename') {+ await this.recoverReserved(record)+ return+ }await this.resumeRemovalIntent(record)const selected =record.plan.replacement?.identity ?? record.plan.sourceIdentity@@ -102,7 +123,18 @@ export class FinalizeRecovery {? await this.options.fs.identity(record.plan.replacement.stagedPath): null- const linked = record.publicationIntent+ // An unmounted disk or unavailable share can look exactly like ENOENT.+ // Absence alone is not evidence of a conflicting identity. Keep the+ // durable checkpoint so reconnecting the storage can resume recovery.+ if (!source && !target && !rollback && !privateTarget)+ throw new FinalizeRecoveryDeferredError(+ 'finalize artifacts are unavailable; retry recovery'+ )++ const linked =+ record.publicationIntent?.method === 'hard_link'+ ? record.publicationIntent+ : undefinedif (linked && target && !linkPublicationConfirmed(record)) {await this.quarantine(record,@@ -135,7 +167,11 @@ export class FinalizeRecovery {}if (record.phase === 'db_committed') {- if (!target || !this.options.exactIdentity(target, installed)) {+ if (!target)+ throw new FinalizeRecoveryDeferredError(+ 'committed target is unavailable; retry recovery'+ )+ if (!this.options.exactIdentity(target, installed)) {await this.quarantine(record, 'committed target identity mismatch')}await this.cleanup(record, source, rollback, privateTarget, replacement)@@ -269,6 +305,103 @@ export class FinalizeRecovery {}}+ private async recoverReserved(record: FinalizeJournalRecord): Promise<void> {+ let intent = record.publicationIntent+ if (intent?.method !== 'reserved_rename')+ throw new Error('invalid reserved journal')+ const ownership = intent.ownership+ const sourceDirectory = path.dirname(intent.sourcePath)+ const volumeAvailable = async () => {+ if (!this.options.fs.reservedVolumeIdentity) return !ownership+ const id = await this.options.fs.reservedVolumeIdentity(sourceDirectory)+ return ownership ? id === ownership.volumeId : id !== null+ }+ if (!(await volumeAvailable())) return+ const quarantine = async (reason: string) => {+ // Recheck after IO: detaching between the volume probe and stat is retryable.+ if (await volumeAvailable()) await this.quarantine(record, reason)+ }+ const matches: FinalizeRecoveryIdentityComparator = ownership+ ? (actual, expected) =>+ reservedArtifactMatches(actual, expected, ownership)+ : this.options.exactIdentity+ const source = await this.options.fs.identity(intent.sourcePath)+ let target = await this.options.fs.identity(record.plan.targetPath)+ if (source) {+ if (record.phase !== 'prepared' || !matches(source, intent.identity))+ return quarantine('reserved source identity or phase mismatch')+ if (+ target &&+ (ownership+ ? !reservationMatches(target, ownership.token)+ : !intent.reservationIdentity ||+ !this.options.exactIdentity(target, intent.reservationIdentity))+ )+ return quarantine('reserved target ownership is unconfirmed')+ // Startup has no task/effects commit boundary. Preserve both names until+ // explicit retry enters SessionManager's serialized terminal transaction.+ if (this.options.rollForwardTargetInstalled === false) return+ if (!target && intent.reservationIdentity) {+ intent = { ...intent, reservationIdentity: undefined }+ await this.options.repository.checkpoint(record.journalId, {+ publicationIntent: intent,+ })+ record.publicationIntent = intent+ }+ target = await publishReserved(+ record,+ this.options.fs,+ this.options.repository+ )+ } else if (+ !target ||+ !matches(target, record.targetIdentity ?? intent.identity)+ ) {+ // An empty exFAT file may acquire a new ID. Without an acknowledged+ // identity transition, an equal empty digest cannot establish ownership.+ return quarantine('reserved installed target identity is unconfirmed')+ }+ if (!target) return quarantine('reserved target is missing')+ if (+ record.targetIdentity &&+ !this.options.exactIdentity(target, record.targetIdentity)+ ) {+ await this.options.repository.checkpoint(record.journalId, {+ targetIdentity: target,+ })+ record.targetIdentity = target+ }+ await this.options.fs.makeDurable(record.plan.targetPath)+ const verifyInstalled = async () => {+ const current = await this.options.fs.identity(record.plan.targetPath)+ if (!current || !this.options.exactIdentity(current, target)) {+ if (!(await volumeAvailable()))+ throw new Error('reserved volume is unavailable')+ await this.quarantine(record, 'reserved target changed before commit')+ }+ }+ await verifyInstalled()+ if (record.phase === 'prepared') {+ await this.options.repository.advance(+ record.journalId,+ 'target_installed',+ { targetIdentity: target }+ )+ record.targetIdentity = target+ record.phase = 'target_installed'+ }+ if (record.phase === 'target_installed') {+ if (this.options.rollForwardTargetInstalled === false) return+ await verifyInstalled()+ await this.options.repository.commitTerminal(record)+ record.phase = 'db_committed'+ }+ if (record.phase === 'db_committed') {+ await this.options.repository.advance(record.journalId, 'cleaned')+ record.phase = 'cleaned'+ }+ }+private async restore(record: FinalizeJournalRecord,target: Awaited<ReturnType<FinalizeArtifactOperations['identity']>>,@@ -339,7 +472,7 @@ export class FinalizeRecovery {if (record.publicationMode === 'move' &&source &&- !record.publicationIntent+ record.publicationIntent?.method !== 'hard_link') {await this.quarantine(record,@@ -347,7 +480,8 @@ export class FinalizeRecovery {)}if (- (record.publicationMode !== 'move' || record.publicationIntent) &&+ (record.publicationMode !== 'move' ||+ record.publicationIntent?.method === 'hard_link') &&source &&!finalizePathsEquivalent(record.plan.sourcePath, record.plan.targetPath)) {@@ -408,7 +542,7 @@ export class FinalizeRecovery {if (source &&target &&- record.publicationIntent &&+ record.publicationIntent?.method === 'hard_link' &&this.options.exactIdentity(source, record.plan.sourceIdentity) &&this.options.exactIdentity(target, record.publicationIntent.identity)) {diff --git a/src/core/plugin/finalize/finalize-removal-safety.ts b/src/core/plugin/finalize/finalize-removal-safety.tsindex 2c1f3c0e..3b0c88ef 100644--- a/src/core/plugin/finalize/finalize-removal-safety.ts+++ b/src/core/plugin/finalize/finalize-removal-safety.ts@@ -6,6 +6,7 @@ import type {FinalizeRemovalSurvivor,} from './finalize-committer'import { finalizePathsEquivalent } from './finalize-committer'+import { FinalizeRecoveryDeferredError } from './finalize-recovery-errors'/** A recorded intention cannot establish ownership of a public hard link. */export function linkPublicationConfirmed(@@ -29,7 +30,7 @@ export async function selectRemovalSurvivor(finalizePathsEquivalent(candidate, intent.artifactPath) ||finalizePathsEquivalent(candidate, intent.quarantinePath)if (- record.publicationIntent &&+ record.publicationIntent?.method === 'hard_link' &&removes(record.plan.targetPath) &&!linkPublicationConfirmed(record))@@ -61,14 +62,26 @@ export async function selectRemovalSurvivor(]: []),]+ let observedConflict = false+ let checkedSurvivor = falsefor (const candidate of candidates) {if (removes(candidate.path)) continue+ checkedSurvivor = trueconst before = await fs.identity(candidate.path)- if (!before || !exactIdentity(before, candidate.identity)) continue+ if (!before) continue+ if (!exactIdentity(before, candidate.identity)) {+ observedConflict = true+ continue+ }await fs.makeDurable(candidate.path)const after = await fs.identity(candidate.path)if (after && exactIdentity(after, candidate.identity)) return candidate+ if (after) observedConflict = true}+ if (checkedSurvivor && !observedConflict)+ throw new FinalizeRecoveryDeferredError(+ 'removal survivor is unavailable; retry recovery'+ )return committed? 'committed target identity mismatch': 'rollback survivor is missing or changed'diff --git a/src/core/plugin/finalize/hook-plan.ts b/src/core/plugin/finalize/hook-plan.tsindex 311d3875..08efe7ad 100644--- a/src/core/plugin/finalize/hook-plan.ts+++ b/src/core/plugin/finalize/hook-plan.ts@@ -28,6 +28,18 @@ export interface HookPlan {contributors: readonly string[]}+/** The exFAT compatibility contract is limited to unmodified download names. */+export function isOrdinarySuffixRemoval(plan: HookPlan): boolean {+ return (+ plan.sourceIdentity.kind === 'file' &&+ !plan.replacement &&+ plan.contributors.length === 0 &&+ plan.metadataOps.length === 0 &&+ plan.sourcePath === `${plan.targetPath}.motrix` &&+ path.dirname(plan.sourcePath) === path.dirname(plan.targetPath)+ )+}+export function assertFinalizePaths(saveDir: string,sourcePath: string,diff --git a/src/core/plugin/finalize/native-artifact-operations.ts b/src/core/plugin/finalize/native-artifact-operations.tsindex 751e50de..0f165e8e 100644--- a/src/core/plugin/finalize/native-artifact-operations.ts+++ b/src/core/plugin/finalize/native-artifact-operations.ts@@ -7,15 +7,24 @@ import {ArtifactIdentityCache,ArtifactIdentityError,artifactIdentityEquals,+ type FileArtifactIdentity,readArtifactIdentity,} from './artifact-identity'-import type { FinalizeFilesystemAdapter } from './filesystem-adapter'+import {+ type FinalizeFilesystemAdapter,+ FinalizeFsError,+ type FinalizeReservationOwnership,+} from './filesystem-adapter'import type {FinalizeArtifactOperations,FinalizeIsolation,FinalizeRemovalIntent,FinalizeRemovalSurvivor,} from './finalize-committer'+import {+ reservationMatches,+ reservedArtifactMatches,+} from './reserved-identity'/*** Production artifact operations. No-replace publication is delegated to the@@ -30,6 +39,109 @@ export class NativeFinalizeArtifactOperationsconstructor(private readonly adapter: FinalizeFilesystemAdapter) {}+ async reservedRenameSupported(): Promise<boolean> {+ const capabilities = await this.adapter.capabilities()+ return (+ capabilities.platform === 'macos' &&+ capabilities.reservedExfatRename === true &&+ capabilities.tokenExfatReservation === true &&+ this.adapter.exfatVolumeIdentity !== undefined &&+ this.adapter.reserveExfatTarget !== undefined &&+ this.adapter.renameOpenedReserved !== undefined+ )+ }++ async reservedVolumeIdentity(directoryPath: string): Promise<string | null> {+ if (!this.adapter.exfatVolumeIdentity) return null+ let root:+ | Awaited<ReturnType<FinalizeFilesystemAdapter['openRoot']>>+ | undefined+ try {+ root = await this.adapter.openRoot(directoryPath)+ return await this.adapter.exfatVolumeIdentity(root)+ } catch (error) {+ if (error instanceof FinalizeFsError && error.code === 'not_found')+ return null+ throw error+ } finally {+ if (root) await this.adapter.close(root).catch(() => undefined)+ }+ }++ async publishReserved(+ sourcePath: string,+ expected: FileArtifactIdentity,+ targetPath: string,+ checkpoint: (reservation: FileArtifactIdentity) => Promise<void>,+ reservation?: FileArtifactIdentity,+ ownership?: FinalizeReservationOwnership+ ): Promise<FileArtifactIdentity> {+ if (+ !(await this.reservedRenameSupported()) ||+ !this.adapter.reserveExfatTarget ||+ !this.adapter.renameOpenedReserved+ )+ throw new Error('reserved exFAT publication is unsupported')+ const root = await this.adapter.openRoot(path.dirname(sourcePath))+ let source:+ | Awaited<ReturnType<FinalizeFilesystemAdapter['openArtifact']>>+ | undefined+ let reserved:+ | Awaited<ReturnType<FinalizeFilesystemAdapter['openArtifact']>>+ | undefined+ try {+ if (+ ownership &&+ (await this.adapter.exfatVolumeIdentity?.(root)) !== ownership.volumeId+ )+ throw new Error('reserved volume is unavailable')+ const requireSource = async () => {+ const current = await this.identity(sourcePath)+ if (!current || !reservedArtifactMatches(current, expected, ownership))+ throw new Error('reserved source identity changed')+ }+ await requireSource()+ if (path.dirname(sourcePath) !== path.dirname(targetPath))+ throw new Error('reserved publication requires the same directory')+ source = await this.adapter.openArtifact(+ root,+ path.basename(sourcePath),+ 'rename'+ )+ await requireSource()+ if (reservation && !ownership)+ await this.requireIdentity(targetPath, reservation)+ const created = await this.adapter.reserveExfatTarget(+ source,+ root,+ path.basename(targetPath),+ reservation?.platformFileId,+ ownership+ )+ reserved = created.handle+ const reservedIdentity = await this.identity(targetPath)+ if (+ reservedIdentity?.kind !== 'file' ||+ (ownership+ ? !reservationMatches(reservedIdentity, ownership.token)+ : reservedIdentity.size !== 0) ||+ reservedIdentity.platformFileId !== created.platformFileId+ )+ throw new Error(+ `reservation identity mismatch: ${reservedIdentity?.platformFileId} != ${created.platformFileId}`+ )+ await checkpoint(reservedIdentity)+ const result = await this.adapter.renameOpenedReserved(source, reserved)+ const installed = { ...expected, platformFileId: result.platformFileId }+ await this.requireIdentity(targetPath, installed)+ return installed+ } finally {+ if (reserved) await this.adapter.close(reserved).catch(() => undefined)+ if (source) await this.adapter.close(source).catch(() => undefined)+ await this.adapter.close(root).catch(() => undefined)+ }+ }+async assertSupported(): Promise<void> {const capabilities = await this.adapter.capabilities()if (diff --git a/src/core/plugin/finalize/reserved-identity.ts b/src/core/plugin/finalize/reserved-identity.tsnew file mode 100644index 00000000..e7011e1f--- /dev/null+++ b/src/core/plugin/finalize/reserved-identity.ts@@ -0,0 +1,45 @@+import { createHash } from 'node:crypto'+import {+ type ArtifactIdentity,+ artifactContentEquals,+ artifactIdentityEquals,+} from './artifact-identity'+import type { FinalizeReservationOwnership } from './filesystem-adapter'++export function reservationMarker(token: string): Buffer {+ return Buffer.from(`motrix-reservation-v1:${token}\n`)+}++export function reservationMatches(+ actual: ArtifactIdentity,+ token: string+): boolean {+ const marker = reservationMarker(token)+ return (+ actual.kind === 'file' &&+ actual.size === marker.length &&+ actual.sha256 === createHash('sha256').update(marker).digest('hex')+ )+}++/** Call only after verifying the persisted volume UUID against the held root. */+export function reservedArtifactMatches(+ actual: ArtifactIdentity,+ expected: ArtifactIdentity,+ ownership?: FinalizeReservationOwnership+): boolean {+ if (artifactIdentityEquals(actual, expected)) return true+ // Nonempty exFAT files have cluster-based IDs; st_dev is mount-specific.+ // Empty payloads still require exact identity: an empty digest proves no ownership.+ return (+ Boolean(ownership) &&+ actual.kind === 'file' &&+ expected.kind === 'file' &&+ actual.size > 0 &&+ artifactContentEquals(actual, expected) &&+ /^\d+:-?\d+$/.test(actual.platformFileId) &&+ /^\d+:-?\d+$/.test(expected.platformFileId) &&+ actual.platformFileId.split(':')[1] ===+ expected.platformFileId.split(':')[1]+ )+}diff --git a/src/core/session/durable-finalize-runtime.ts b/src/core/session/durable-finalize-runtime.tsindex dab79e01..7ff3592f 100644--- a/src/core/session/durable-finalize-runtime.ts+++ b/src/core/session/durable-finalize-runtime.ts@@ -17,6 +17,7 @@ import { FinalizeRecovery } from '@core/plugin/finalize/finalize-recovery'import {assertFinalizePaths,freezeHookPlan,+ isOrdinarySuffixRemoval,} from '@core/plugin/finalize/hook-plan'import type { StagedMetadataOp } from '@core/plugin/hooks/staged-effects'import type { PostDeliveryAdmission } from '@core/plugin/post/delivery-types'@@ -96,26 +97,43 @@ export class DurableFinalizeRuntime {const lease = await this.leases.acquire(input.task.id)try {await this.createRecovery().recoverTask(input.task.id, lease)+ const pending = (+ await this.createRepository().listRecoverable(input.task.id)+ ).find((record) => record.publicationIntent?.method === 'reserved_rename')+ if (+ pending &&+ (!isOrdinarySuffixRemoval(pending.plan) ||+ pending.plan.sourcePath !== input.sourcePath ||+ pending.plan.targetPath !== targetPath ||+ input.replacement ||+ input.contributors.length > 0 ||+ input.metadataOps.length > 0)+ )+ throw new Error('pending reserved publication does not match the retry')// H8: identity capture is inside the mutation lease, after every// engine/Host writer has successfully quiesced.- const sourceIdentity = await this.captureIdentity(input.sourcePath)+ const sourceIdentity =+ pending?.plan.sourceIdentity ??+ (await this.captureIdentity(input.sourcePath))const replacement = input.replacement? {...input.replacement,identity: await this.captureIdentity(input.replacement.stagedPath),}: undefined- const plan = freezeHookPlan({- planId: randomUUID(),- taskId: input.task.id,- saveDir: input.task.saveDir,- sourcePath: input.sourcePath,- targetPath,- sourceIdentity,- replacement,- metadataOps: input.metadataOps,- contributors: input.contributors,- })+ const plan =+ pending?.plan ??+ freezeHookPlan({+ planId: randomUUID(),+ taskId: input.task.id,+ saveDir: input.task.saveDir,+ sourcePath: input.sourcePath,+ targetPath,+ sourceIdentity,+ replacement,+ metadataOps: input.metadataOps,+ contributors: input.contributors,+ })// Rebase paths must follow the sanitized final component when the// requested target named the same file.@@ -151,6 +169,35 @@ export class DurableFinalizeRuntime {},})+ if (pending) {+ input.beforeCommit?.()+ try {+ await new FinalizeRecovery({+ repository,+ leases: this.leases,+ fs: this.options.fs,+ exactIdentity: artifactIdentityEquals,+ sameContent: artifactContentEquals,+ }).recover(pending, lease)+ } catch (error) {+ // Match live publication: a cleanup failure cannot undo the+ // already committed task. Startup will close the journal later.+ if (pending.phase !== 'db_committed') throw error+ }+ if (+ !pending.targetIdentity ||+ (pending.phase !== 'cleaned' && pending.phase !== 'db_committed')+ )+ throw new Error('reserved publication recovery did not commit')+ return {+ journalId: pending.journalId,+ targetPath: pending.plan.targetPath,+ targetIdentity: pending.targetIdentity,+ ...(pending.phase === 'db_committed'+ ? { cleanupPending: true }+ : {}),+ }+ }const committer = new FinalizeCommitter({leases: this.leases,repository,@@ -187,22 +234,25 @@ export class DurableFinalizeRuntime {return identity}- /** Recover before task restore: committed rows clean up; uncommitted targets roll back. */+ /** Strict moves roll back; reserved targets wait for the task's commit boundary. */async recoverAll(): Promise<void> {await this.createRecovery().recoverAll()}- private createRecovery(): FinalizeRecovery {- const repository = new SqliteFinalizeJournalRepository(this.options.db, {- now: this.now,- commitTerminalBoundary: () => {- throw new Error(- 'startup recovery is configured to roll back uncommitted targets'+ /** A filesystem-only recovery decision cannot override an unfinished journal. */+ async hasPendingFinalization(taskId: string): Promise<boolean> {+ return (+ this.options.db+ .prepare(+ "SELECT 1 FROM plugin_finalize_journals WHERE task_id=? AND phase <> 'cleaned'")- },- })+ .get(taskId) !== undefined+ )+ }++ private createRecovery(): FinalizeRecovery {return new FinalizeRecovery({- repository,+ repository: this.createRepository(),leases: this.leases,fs: this.options.fs,exactIdentity: artifactIdentityEquals,@@ -210,4 +260,15 @@ export class DurableFinalizeRuntime {rollForwardTargetInstalled: false,})}++ private createRepository(): SqliteFinalizeJournalRepository {+ return new SqliteFinalizeJournalRepository(this.options.db, {+ now: this.now,+ commitTerminalBoundary: () => {+ throw new Error(+ 'startup recovery is configured to roll back uncommitted targets'+ )+ },+ })+ }}diff --git a/src/core/session/finalize-journal-repository.test.ts b/src/core/session/finalize-journal-repository.test.tsindex fbe31ef5..d00237a4 100644--- a/src/core/session/finalize-journal-repository.test.ts+++ b/src/core/session/finalize-journal-repository.test.ts@@ -1,4 +1,6 @@+import { createHash } from 'node:crypto'import type { FinalizeJournalRecord } from '@core/plugin/finalize/finalize-committer'+import { reservationMarker } from '@core/plugin/finalize/reserved-identity'import Database from 'better-sqlite3'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { SqliteFinalizeJournalRepository } from './finalize-journal-repository'@@ -14,6 +16,215 @@ describe('SqliteFinalizeJournalRepository', () => {afterEach(() => db.close())+ it('persists a prepared move-to-copy switch and rejects switching after mutation', async () => {+ const repository = new SqliteFinalizeJournalRepository(db, {+ commitTerminalBoundary: vi.fn(),+ })+ const record = { ...makeRecord(), publicationMode: 'move' as const }+ await repository.prepare(record)+ await repository.checkpoint(record.journalId, { publicationMode: 'copy' })+ expect((await repository.listRecoverable())[0].publicationMode).toBe('copy')+ await expect(+ repository.checkpoint(record.journalId, { publicationMode: 'move' })+ ).rejects.toThrow('after mutation')+ })++ it.each(['target_staged', 'target_installed', 'db_committed'] as const)(+ 'rejects a mode switch in %s',+ async (phase) => {+ const repository = new SqliteFinalizeJournalRepository(db, {+ commitTerminalBoundary: vi.fn(),+ })+ const record = { ...makeRecord(), publicationMode: 'move' as const }+ await repository.prepare(record)+ db.prepare(+ 'UPDATE plugin_finalize_journals SET phase=?, plan_json=?'+ ).run(phase, JSON.stringify({ ...record, phase }))+ await expect(+ repository.checkpoint(record.journalId, { publicationMode: 'copy' })+ ).rejects.toThrow('after mutation')+ }+ )++ it('syncs critical journal writes and restores the connection setting after a failed commit', async () => {+ db.pragma('synchronous = NORMAL')+ db.pragma('fullfsync = OFF')+ const flushes: number[] = []+ db.function('observe_fullfsync', (level) => {+ flushes.push(level as number)+ return 1+ })+ const writes: number[] = []+ db.function('observe_sync', (level) => {+ writes.push(level as number)+ return 1+ })+ db.exec(`+ CREATE TRIGGER observe_insert BEFORE INSERT ON plugin_finalize_journals BEGIN SELECT observe_sync(synchronous) FROM pragma_synchronous; SELECT observe_fullfsync(fullfsync) FROM pragma_fullfsync; END;+ CREATE TRIGGER observe_update BEFORE UPDATE ON plugin_finalize_journals BEGIN SELECT observe_sync(synchronous) FROM pragma_synchronous; SELECT observe_fullfsync(fullfsync) FROM pragma_fullfsync; END;+ `)+ const repository = new SqliteFinalizeJournalRepository(db, {+ commitTerminalBoundary: () => {+ expect(db.pragma('synchronous', { simple: true })).toBe(2)+ expect(db.pragma('fullfsync', { simple: true })).toBe(+ process.platform === 'darwin' ? 1 : 0+ )+ throw new Error('terminal transaction failed')+ },+ })+ const record = { ...makeRecord(), publicationMode: 'move' as const }+ await repository.prepare(record)+ await repository.checkpoint(record.journalId, {+ targetIdentity: record.plan.sourceIdentity,+ })+ await repository.advance(record.journalId, 'target_installed')+ await expect(repository.commitTerminal(record)).rejects.toThrow(+ 'terminal transaction failed'+ )+ expect(writes).toEqual([2, 2, 2])+ expect(flushes).toEqual(+ Array(3).fill(process.platform === 'darwin' ? 1 : 0)+ )+ expect(db.pragma('fullfsync', { simple: true })).toBe(0)+ expect(db.pragma('synchronous', { simple: true })).toBe(1)+ expect((await repository.listRecoverable())[0].phase).toBe(+ 'target_installed'+ )+ })++ it('preserves stronger caller durability settings', async () => {+ db.pragma('synchronous = EXTRA')+ db.pragma('fullfsync = ON')+ const repository = new SqliteFinalizeJournalRepository(db, {+ commitTerminalBoundary: vi.fn(),+ })+ await repository.prepare(makeRecord())+ expect(db.pragma('synchronous', { simple: true })).toBe(3)+ expect(db.pragma('fullfsync', { simple: true })).toBe(1)+ })++ it('does not claim a durable checkpoint inside a caller-owned transaction', async () => {+ const repository = new SqliteFinalizeJournalRepository(db, {+ commitTerminalBoundary: vi.fn(),+ })+ db.exec('BEGIN')+ try {+ await expect(repository.prepare(makeRecord())).rejects.toThrow(+ 'outermost transaction'+ )+ } finally {+ db.exec('ROLLBACK')+ }+ expect(await repository.listRecoverable()).toEqual([])+ })++ it('validates reserved publication scope and the exact empty placeholder contract', async () => {+ const repository = new SqliteFinalizeJournalRepository(db, {+ commitTerminalBoundary: vi.fn(),+ })+ const record = { ...makeRecord(), publicationMode: 'move' as const }+ record.plan.sourcePath = `${record.plan.targetPath}.motrix`+ const identity = {+ kind: 'file' as const,+ size: 4,+ sha256: 'a'.repeat(64),+ platformFileId: '1:1',+ }+ record.plan.sourceIdentity = identity+ await repository.prepare(record)+ const publicationIntent = {+ version: 2 as const,+ method: 'reserved_rename' as const,+ sourcePath: record.plan.sourcePath,+ identity,+ }+ await repository.checkpoint(record.journalId, { publicationIntent })+ const reservationIdentity = {+ ...identity,+ size: 0,+ platformFileId: '1:2',+ sha256:+ 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',+ }+ await repository.checkpoint(record.journalId, {+ publicationIntent: { ...publicationIntent, reservationIdentity },+ })+ expect((await repository.listRecoverable())[0].publicationIntent).toEqual({+ ...publicationIntent,+ reservationIdentity,+ })+ await expect(+ repository.checkpoint(record.journalId, {+ publicationIntent: {+ ...publicationIntent,+ reservationIdentity: identity,+ },+ })+ ).rejects.toThrow()+ await expect(+ repository.checkpoint(record.journalId, {+ privateTargetPath: '/downloads/private',+ })+ ).rejects.toThrow('ordinary suffix removal')+ })++ it('persists token ownership before reservation creation and rejects unrelated markers', async () => {+ const repository = new SqliteFinalizeJournalRepository(db, {+ commitTerminalBoundary: vi.fn(),+ })+ const record = { ...makeRecord(), publicationMode: 'move' as const }+ record.plan.sourcePath = `${record.plan.targetPath}.motrix`+ const identity = {+ kind: 'file' as const,+ size: 4,+ sha256: 'a'.repeat(64),+ platformFileId: '1:1',+ }+ record.plan.sourceIdentity = identity+ await repository.prepare(record)+ const ownership = { volumeId: 'c'.repeat(32), token: 'd'.repeat(64) }+ const publicationIntent = {+ version: 3 as const,+ method: 'reserved_rename' as const,+ sourcePath: record.plan.sourcePath,+ identity,+ ownership,+ }+ await repository.checkpoint(record.journalId, { publicationIntent })+ expect((await repository.listRecoverable())[0].publicationIntent).toEqual(+ publicationIntent+ )+ const marker = reservationMarker(ownership.token)+ const reservationIdentity = {+ ...identity,+ platformFileId: '1:2',+ size: marker.length,+ sha256: createHash('sha256').update(marker).digest('hex'),+ }+ await repository.checkpoint(record.journalId, {+ publicationIntent: { ...publicationIntent, reservationIdentity },+ })+ await expect(+ repository.checkpoint(record.journalId, {+ publicationIntent: {+ ...publicationIntent,+ reservationIdentity: {+ ...reservationIdentity,+ sha256: '0'.repeat(64),+ },+ },+ })+ ).rejects.toThrow('persisted token')+ await repository.checkpoint(record.journalId, {+ targetIdentity: { ...identity, platformFileId: '9:1' },+ })+ await expect(+ repository.checkpoint(record.journalId, {+ targetIdentity: { ...identity, platformFileId: '9:2' },+ })+ ).rejects.toThrow('downloaded content')+ })+it('persists and validates the installation source of a hard-link intent', async () => {const repository = new SqliteFinalizeJournalRepository(db, {commitTerminalBoundary: vi.fn(),diff --git a/src/core/session/finalize-journal-repository.ts b/src/core/session/finalize-journal-repository.tsindex d7fc3c7c..e30b2b74 100644--- a/src/core/session/finalize-journal-repository.ts+++ b/src/core/session/finalize-journal-repository.ts@@ -7,7 +7,14 @@ import type {} 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 {+ assertValidHookPlan,+ isOrdinarySuffixRemoval,+} from '@core/plugin/finalize/hook-plan'+import {+ reservationMatches,+ reservedArtifactMatches,+} from '@core/plugin/finalize/reserved-identity'import type Database from 'better-sqlite3'import { z } from 'zod'@@ -50,11 +57,12 @@ export class SqliteFinalizeJournalRepositorythrow new Error('new finalize journal must start prepared')}assertValidHookPlan(record.plan)+ validateIntents(record)if (record.journalId !== record.plan.planId) {throw new Error('finalize journal id must match plan id')}const now = Math.max(1, this.now())- this.db.transaction(() => {+ this.durableTransaction(() => {const prior = this.db.prepare(`SELECT plan_id, phase FROM plugin_finalize_journals WHERE task_id=?`@@ -90,7 +98,7 @@ export class SqliteFinalizeJournalRepositorynow,now)- })()+ })}async checkpoint(@@ -98,6 +106,7 @@ export class SqliteFinalizeJournalRepositorypatch: Partial<Pick<FinalizeJournalRecord,+ | 'publicationMode'| 'privateTargetPath'| 'privateTargetIdentity'| 'targetIdentity'@@ -107,11 +116,23 @@ export class SqliteFinalizeJournalRepository>>): Promise<void> {- this.db.transaction(() => {+ this.durableTransaction(() => {const current = this.requireRecord(journalId)if (current.phase === 'cleaned') {throw new Error(`cannot checkpoint terminal finalize journal`)}+ if (+ patch.publicationMode !== undefined &&+ (patch.publicationMode !== 'copy' ||+ current.publicationMode !== 'move' ||+ current.phase !== 'prepared' ||+ current.publicationIntent ||+ current.privateTargetPath ||+ current.rollbackPath ||+ current.targetIdentity ||+ current.removalIntent)+ )+ throw new Error('cannot change publication mode after mutation')const next: FinalizeJournalRecord = { ...current, ...patch }validateIntents(next)const changed = this.db@@ -128,7 +149,7 @@ export class SqliteFinalizeJournalRepositorycurrent.phase).changesif (changed !== 1) throw new Error('finalize journal checkpoint lost CAS')- })()+ })}async advance(@@ -145,7 +166,7 @@ export class SqliteFinalizeJournalRepository>> = {}): Promise<void> {- this.db.transaction(() => {+ this.durableTransaction(() => {const current = this.requireRecord(journalId)if (current.phase === phase) returnif (!transitionAllowed(current, phase)) {@@ -154,6 +175,7 @@ export class SqliteFinalizeJournalRepository)}const next: FinalizeJournalRecord = { ...current, ...patch, phase }+ validateIntents(next)const changed = this.db.prepare(`UPDATE plugin_finalize_journals@@ -169,11 +191,11 @@ export class SqliteFinalizeJournalRepositorycurrent.phase).changesif (changed !== 1) throw new Error('finalize journal transition lost CAS')- })()+ })}async commitTerminal(record: FinalizeJournalRecord): Promise<void> {- this.db.transaction(() => {+ this.durableTransaction(() => {const durable = this.requireRecord(record.journalId)if (durable.phase === 'db_committed') returnif (durable.phase !== 'target_installed') {@@ -186,7 +208,7 @@ export class SqliteFinalizeJournalRepository'terminal boundary returned without atomically committing journal')}- })()+ })}async quarantine(journalId: string, reason: string): Promise<void> {@@ -236,7 +258,7 @@ export class SqliteFinalizeJournalRepository}async resumeQuarantined(record: FinalizeJournalRecord): Promise<void> {- this.db.transaction(() => {+ this.durableTransaction(() => {const raw = this.readRaw(record.journalId)const candidate = raw && parseQuarantinedMove(raw)if (!candidate || JSON.stringify(candidate) !== JSON.stringify(record)) {@@ -248,7 +270,30 @@ export class SqliteFinalizeJournalRepositoryWHERE plan_id=? AND phase='quarantined'`).run(candidate.phase, Math.max(1, this.now()), candidate.journalId)- })()+ })+ }++ /** Critical filesystem intents must reach the WAL before native mutation. */+ private durableTransaction<T>(run: () => T): T {+ if (this.db.inTransaction)+ throw new Error('finalize durability requires an outermost transaction')+ const previous = this.db.pragma('synchronous', { simple: true }) as number+ // Keep stronger caller settings; change this connection only, outside a+ // transaction. No awaits or unrelated writes can enter this sync boundary.+ const previousFull =+ process.platform === 'darwin'+ ? (this.db.pragma('fullfsync', { simple: true }) as number)+ : undefined+ try {+ // SQLite's FULL synchronous level alone uses fsync on macOS. The WAL+ // must reach stable storage before a mutation on a separate download disk.+ if (previousFull === 0) this.db.pragma('fullfsync = ON')+ if (previous < 2) this.db.pragma('synchronous = FULL')+ return this.db.transaction(run)()+ } finally {+ if (previous < 2) this.db.pragma(`synchronous = ${previous}`)+ if (previousFull === 0) this.db.pragma('fullfsync = OFF')+ }}private requireRecord(journalId: string): FinalizeJournalRecord {@@ -342,7 +387,7 @@ const fileIdentitySchema = z.object({sha256: z.string().regex(/^[a-f0-9]{64}$/),platformFileId: z.string().min(1),})-const publicationIntentSchema = z+const linkIntentSchema = z.object({version: z.literal(1),method: z.literal('hard_link'),@@ -351,6 +396,37 @@ const publicationIntentSchema = zidentity: fileIdentitySchema,}).strict()+const reservedIntentSchema = z+ .object({+ version: z.literal(2),+ method: z.literal('reserved_rename'),+ sourcePath: z.string(),+ identity: fileIdentitySchema,+ reservationIdentity: fileIdentitySchema+ .extend({+ size: z.literal(0),+ sha256: z.literal(+ 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'+ ),+ })+ .optional(),+ })+ .strict()+const tokenReservedIntentSchema = reservedIntentSchema.extend({+ version: z.literal(3),+ ownership: z+ .object({+ token: z.string().regex(/^[a-f0-9]{64}$/),+ volumeId: z.string().regex(/^[a-f0-9]{32}$/),+ })+ .strict(),+ reservationIdentity: fileIdentitySchema.optional(),+})+const publicationIntentSchema = z.union([+ linkIntentSchema,+ reservedIntentSchema,+ tokenReservedIntentSchema,+])const isolationSchema = z.object({directory: z.string(),@@ -361,6 +437,46 @@ const isolationSchema = zfunction validateIntents(record: FinalizeJournalRecord): void {if (record.publicationIntent !== undefined) {const intent = publicationIntentSchema.parse(record.publicationIntent)+ if (+ intent.method === 'reserved_rename' &&+ intent.version === 3 &&+ intent.reservationIdentity &&+ !reservationMatches(intent.reservationIdentity, intent.ownership.token)+ )+ throw new TypeError('reservation does not match its persisted token')+ if (intent.method === 'reserved_rename' && record.targetIdentity) {+ const installed = record.targetIdentity+ if (+ installed.kind !== 'file' ||+ installed.size !== intent.identity.size ||+ installed.sha256 !== intent.identity.sha256 ||+ (installed.size !== 0 &&+ !reservedArtifactMatches(+ installed,+ intent.identity,+ intent.version === 3 ? intent.ownership : undefined+ ))+ )+ throw new TypeError(+ 'reserved target identity does not match the downloaded content'+ )+ }+ if (+ intent.method === 'reserved_rename' &&+ (record.publicationMode !== 'move' ||+ !isOrdinarySuffixRemoval(record.plan) ||+ record.privateTargetPath !== undefined ||+ record.privateTargetIdentity !== undefined ||+ record.rollbackPath !== undefined ||+ record.removalIntent !== undefined ||+ (record.phase !== 'prepared' &&+ record.phase !== 'target_installed' &&+ record.phase !== 'db_committed' &&+ record.phase !== 'cleaned'))+ )+ throw new TypeError(+ 'reserved publication requires an ordinary suffix removal'+ )const expectedPath =record.publicationMode === 'move'? record.plan.sourcePathdiff --git a/src/core/task/task-recovery-service.test.ts b/src/core/task/task-recovery-service.test.tsindex 392c6d4e..068619be 100644--- a/src/core/task/task-recovery-service.test.ts+++ b/src/core/task/task-recovery-service.test.ts@@ -164,6 +164,50 @@ function makeDeps(overrides: Partial<RecoveryDeps> = {}): RecoveryDeps {}describe('TaskRecoveryServiceImpl.recoverOnStartup', () => {+ it.each(['both', 'final-only'])(+ 'routes a journaled %s output through the durable finalizer',+ async (state) => {+ const task = makeTask({ type: TaskType.Http })+ const deps = makeDeps({+ taskManager: { getAll: () => [task], persist: vi.fn() },+ fs: makeFs(+ new Set(+ state === 'both'+ ? [task.diskPath, task.finalPath]+ : [task.finalPath]+ )+ ),+ hasPendingFinalization: vi.fn(async () => true),+ })+ const report = await new TaskRecoveryServiceImpl(deps).recoverOnStartup()+ expect(deps.finalizeTask).toHaveBeenCalledExactlyOnceWith(task.id)+ expect(deps.fs.pathExists).not.toHaveBeenCalled()+ expect(deps.taskManager.persist).not.toHaveBeenCalled()+ expect(report.errors).toEqual([])+ expect(report.recovered).toEqual([+ { taskId: task.id, action: RecoveryAction.ResumeFromRename },+ ])+ }+ )++ it('does not mark a quarantined journal complete from the final path alone', async () => {+ const task = makeTask({ type: TaskType.Http, status: TaskStatus.Error })+ const deps = makeDeps({+ taskManager: { getAll: () => [task], persist: vi.fn() },+ fs: makeFs(new Set([task.finalPath])),+ hasPendingFinalization: async () => true,+ finalizeTask: vi.fn(async () => {+ throw new Error('publication ownership is unconfirmed')+ }),+ })+ const report = await new TaskRecoveryServiceImpl(deps).recoverTaskById(+ task.id+ )+ expect(report.recovered).toEqual([])+ expect(report.errors).toHaveLength(1)+ expect(task.status).toBe(TaskStatus.Error)+ expect(deps.taskManager.persist).not.toHaveBeenCalled()+ })it.each([TransitionPhase.Idle, TransitionPhase.Renaming])('finishes direct BT completion in place after restart from %s',async (phase) => {diff --git a/src/core/task/task-recovery-service.ts b/src/core/task/task-recovery-service.tsindex e61f0ce8..fdd1374e 100644--- a/src/core/task/task-recovery-service.ts+++ b/src/core/task/task-recovery-service.ts@@ -130,6 +130,8 @@ export interface RecoveryDeps {fs: RecoveryFsactivityRecorder: TaskActivityRecorderfinalizeTask: (taskId: string) => Promise<void>+ /** Defer ownership and completion to the journal before interpreting path existence. */+ hasPendingFinalization?: (taskId: string) => Promise<boolean>/*** Persist a task and (when non-null) its terminal occurrence in a single* durable transaction — used INSTEAD OF `taskManager.persist` whenever a@@ -337,6 +339,18 @@ export class TaskRecoveryServiceImpl implements TaskRecoveryService {taskIdsByInfoHash: Map<string, Set<string>>,report: RecoveryReport): Promise<void> {+ if (+ task.transitionPhase === TransitionPhase.Renaming &&+ !isMediaKind(task.kind) &&+ (await this.deps.hasPendingFinalization?.(task.id))+ ) {+ await this.deps.finalizeTask(task.id)+ report.recovered.push({+ taskId: task.id,+ action: RecoveryAction.ResumeFromRename,+ })+ return+ }const fsState = await this.inspectFs(task)const matchingGid = this.selectMatchingGid(task,diff --git a/src/main/index.ts b/src/main/index.tsindex 460e7d24..f7caac43 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1403,6 +1403,8 @@ async function startEngineAndRestore(// flowing. See design spec §6.6.const finalizeDepsFactory = () => buildFinalizeDeps(adapter)recoveryService = new TaskRecoveryServiceImpl({+ hasPendingFinalization: async (taskId) =>+ (await durableFinalizeRuntime?.hasPendingFinalization(taskId)) ?? false,taskManager: {getAll: () => taskManager.getAll(),set: (id: string, task: DownloadTask) => taskManager.set(id, task),diff --git a/src/server/index.ts b/src/server/index.tsindex 9054336f..205b5161 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -1608,6 +1608,8 @@ async function main() {// open so the renderer observes a self-healed state. See design// spec §6.6.recoveryService = new TaskRecoveryServiceImpl({+ hasPendingFinalization: (taskId) =>+ durableFinalizeRuntime.hasPendingFinalization(taskId),taskManager: {getAll: () => taskManager.getAll(),set: (id: string, task: DownloadTask) => taskManager.set(id, task),diff --git a/src/test-utils/finalize-crash-child.ts b/src/test-utils/finalize-crash-child.tsnew file mode 100644index 00000000..a8ae8a68--- /dev/null+++ b/src/test-utils/finalize-crash-child.ts@@ -0,0 +1,68 @@+// Runs in a disposable test process. Its parent sends SIGKILL at a real IO cut.+import { writeSync } from 'node:fs'+import {+ FinalizeFsError,+ NativeFinalizeFilesystemAdapter,+} from '@core/plugin/finalize/filesystem-adapter'+import { NativeFinalizeArtifactOperations } from '@core/plugin/finalize/native-artifact-operations'+import {+ type DurableFinalizeArtifactInput,+ DurableFinalizeRuntime,+} from '@core/session/durable-finalize-runtime'+import Database from 'better-sqlite3'++const [dbPath, binary, cut, inputJson] = process.argv.slice(2)+const db = new Database(dbPath)+db.pragma('journal_mode = WAL')+db.pragma('synchronous = NORMAL')+const adapter = new NativeFinalizeFilesystemAdapter(binary)+const stop = (): never => {+ writeSync(1, 'FINALIZE_CRASH_CUT\n')+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0)+ throw new Error('crash cut unexpectedly resumed')+}+adapter.renameOpenedNoReplace = async () => {+ throw new FinalizeFsError(+ 'rename_unsupported',+ 'exercise exFAT compatibility',+ {+ operation: 'rename_opened_no_replace',+ osError: 45,+ mutation: 'not_attempted',+ }+ )+}+if (cut === 'reservation-created') {+ const reserve = adapter.reserveExfatTarget.bind(adapter)+ adapter.reserveExfatTarget = async (...args) => {+ await reserve(...args)+ return stop()+ }+}+if (cut === 'target-installed') {+ const rename = adapter.renameOpenedReserved.bind(adapter)+ adapter.renameOpenedReserved = async (...args) => {+ await rename(...args)+ return stop()+ }+}+const runtime = new DurableFinalizeRuntime({+ db,+ fs: new NativeFinalizeArtifactOperations(adapter),+ session: {+ persistFinalizedArtifact: async (_task, _occurrence, _effects, install) =>+ install(() => {+ if (cut === 'before-terminal-commit') stop()+ throw new Error('missed requested crash cut')+ }),+ },+})+void runtime+ .commit(JSON.parse(inputJson) as DurableFinalizeArtifactInput)+ .then(() => {+ throw new Error('unexpected completion')+ })+ .catch((error) => {+ console.error(error)+ process.exit(1)+ })