Skip to content

A full-featured download manager.

fix(downloads): avoid hashing ordinary windows finalization (#2406)

Dr_rOotd2c33fc65fe8
diff --git a/packages/finalize-fs/Cargo.toml b/packages/finalize-fs/Cargo.toml
index fddf4abd..74d3bd4f 100644
--- a/packages/finalize-fs/Cargo.toml
+++ b/packages/finalize-fs/Cargo.toml
@@ -23,6 +23,7 @@ windows-sys = { version = "0.61.2", features = [
"Win32_Security_Authorization",
"Win32_Storage_FileSystem",
"Win32_System_IO",
+ "Win32_System_Memory",
"Win32_System_SystemServices",
] }
diff --git a/packages/finalize-fs/src/platform/windows/tests.rs b/packages/finalize-fs/src/platform/windows/tests.rs
index 8dbf65cf..df4a32cc 100644
--- a/packages/finalize-fs/src/platform/windows/tests.rs
+++ b/packages/finalize-fs/src/platform/windows/tests.rs
@@ -165,6 +165,126 @@ fn rename_only_handles_use_metadata_and_do_not_authorize_removal() {
assert_eq!(fs::read(scratch.path().join("target")).unwrap(), b"payload");
}
+#[test]
+fn rename_only_file_excludes_writers_until_the_published_handle_closes() {
+ let scratch = Scratch::new("rename-write-exclusion");
+ let source = scratch.path().join("source.motrix");
+ let target = scratch.path().join("source");
+ fs::write(&source, b"payload").unwrap();
+ let root = open_root(scratch.path().to_str().unwrap()).unwrap();
+ let artifact = super::open_artifact_for_rename(&root, "source.motrix").unwrap();
+
+ let error = fs::OpenOptions::new()
+ .write(true)
+ .open(&source)
+ .unwrap_err();
+ assert_eq!(
+ error.raw_os_error(),
+ Some(windows_sys::Win32::Foundation::ERROR_SHARING_VIOLATION as i32)
+ );
+ rename_opened_no_replace(&artifact, &root, "source").unwrap();
+ let error = fs::OpenOptions::new()
+ .write(true)
+ .open(&target)
+ .unwrap_err();
+ assert_eq!(
+ error.raw_os_error(),
+ Some(windows_sys::Win32::Foundation::ERROR_SHARING_VIOLATION as i32)
+ );
+ assert_eq!(fs::read(&target).unwrap(), b"payload");
+
+ drop(artifact);
+ fs::OpenOptions::new().write(true).open(&target).unwrap();
+}
+
+#[test]
+fn rename_admission_rejects_an_existing_writer_even_when_it_shares_delete() {
+ use std::os::windows::fs::OpenOptionsExt;
+ use windows_sys::Win32::Storage::FileSystem::{
+ FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
+ };
+
+ let scratch = Scratch::new("rename-existing-writer");
+ let source = scratch.path().join("source.motrix");
+ fs::write(&source, b"payload").unwrap();
+ let root = open_root(scratch.path().to_str().unwrap()).unwrap();
+ let writer = fs::OpenOptions::new()
+ .write(true)
+ .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
+ .open(&source)
+ .unwrap();
+ let name = super::nt::wide_name("source.motrix").unwrap();
+ // Test one admission attempt; the production rename wrapper retries this
+ // sharing violation without relaxing its deny-write policy.
+ let error = super::nt::open_existing(&root.handle, &name).unwrap_err();
+ assert_eq!(
+ crate::error::os_code(&error),
+ Some(windows_sys::Win32::Foundation::ERROR_SHARING_VIOLATION as i32)
+ );
+ drop(writer);
+ let artifact = super::open_artifact_for_rename(&root, "source.motrix").unwrap();
+ rename_opened_no_replace(&artifact, &root, "source").unwrap();
+ assert_eq!(fs::read(scratch.path().join("source")).unwrap(), b"payload");
+}
+
+#[test]
+fn rename_admission_excludes_a_writable_mapping_after_its_file_handle_closes() {
+ use std::os::windows::fs::OpenOptionsExt;
+ use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
+ use windows_sys::Win32::Storage::FileSystem::{
+ FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
+ };
+ use windows_sys::Win32::System::Memory::{
+ CreateFileMappingW, FILE_MAP_WRITE, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile,
+ PAGE_READWRITE, UnmapViewOfFile,
+ };
+
+ struct View(MEMORY_MAPPED_VIEW_ADDRESS);
+ impl Drop for View {
+ fn drop(&mut self) {
+ unsafe { UnmapViewOfFile(self.0) };
+ }
+ }
+
+ let scratch = Scratch::new("rename-existing-mapping");
+ let source = scratch.path().join("source.motrix");
+ fs::write(&source, b"payload").unwrap();
+ let root = open_root(scratch.path().to_str().unwrap()).unwrap();
+ let writer = fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
+ .open(&source)
+ .unwrap();
+ let raw_mapping = unsafe {
+ CreateFileMappingW(
+ writer.as_raw_handle(),
+ std::ptr::null(),
+ PAGE_READWRITE,
+ 0,
+ 0,
+ std::ptr::null(),
+ )
+ };
+ assert!(!raw_mapping.is_null(), "create writable mapping");
+ let mapping = unsafe { OwnedHandle::from_raw_handle(raw_mapping) };
+ let raw_view = unsafe { MapViewOfFile(mapping.as_raw_handle(), FILE_MAP_WRITE, 0, 0, 0) };
+ assert!(!raw_view.Value.is_null(), "map writable view");
+ let view = View(raw_view);
+ drop(writer);
+
+ let name = super::nt::wide_name("source.motrix").unwrap();
+ assert!(
+ super::nt::open_existing(&root.handle, &name).is_err(),
+ "a surviving writable view must block metadata-only rename admission"
+ );
+ drop(view);
+ drop(mapping);
+ let artifact = super::open_artifact_for_rename(&root, "source.motrix").unwrap();
+ rename_opened_no_replace(&artifact, &root, "source").unwrap();
+ assert_eq!(fs::read(scratch.path().join("source")).unwrap(), b"payload");
+}
+
#[test]
fn classic_delete_finishes_after_the_admitted_handle_closes() {
let scratch = Scratch::new("classic-delete");
diff --git a/packages/finalize-fs/src/protocol.rs b/packages/finalize-fs/src/protocol.rs
index 19df3f0f..81ab21fa 100644
--- a/packages/finalize-fs/src/protocol.rs
+++ b/packages/finalize-fs/src/protocol.rs
@@ -176,6 +176,8 @@ 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) held_file_write_exclusion: 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>,
@@ -213,6 +215,7 @@ impl<'a> Response<'a> {
held_roots: None,
directory_sync: None,
held_artifacts: None,
+ held_file_write_exclusion: None,
reserved_exfat_rename: None,
token_exfat_reservation: None,
volume_id: None,
diff --git a/packages/finalize-fs/src/state.rs b/packages/finalize-fs/src/state.rs
index 2c4deef4..232674c8 100644
--- a/packages/finalize-fs/src/state.rs
+++ b/packages/finalize-fs/src/state.rs
@@ -522,6 +522,7 @@ 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.held_file_write_exclusion = Some(cfg!(windows));
response.reserved_exfat_rename = Some(cfg!(target_os = "macos"));
response.token_exfat_reservation = Some(cfg!(target_os = "macos"));
response
@@ -577,6 +578,7 @@ mod tests {
#[test]
fn capabilities_claim_only_the_implemented_native_boundaries() {
let response = State::new().handle(Request::Capabilities);
+ assert_eq!(response.held_file_write_exclusion, Some(cfg!(windows)));
#[cfg(unix)]
{
assert_eq!(response.held_roots, Some(true));
diff --git a/src/core/plugin/finalize/artifact-identity.test.ts b/src/core/plugin/finalize/artifact-identity.test.ts
index dc52a927..3deccaff 100644
--- a/src/core/plugin/finalize/artifact-identity.test.ts
+++ b/src/core/plugin/finalize/artifact-identity.test.ts
@@ -1,5 +1,13 @@
import { createHash } from 'node:crypto'
-import { mkdir, mkdtemp, symlink, writeFile } from 'node:fs/promises'
+import {
+ mkdir,
+ mkdtemp,
+ rm,
+ stat,
+ symlink,
+ utimes,
+ writeFile,
+} from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -8,6 +16,7 @@ import {
artifactContentEquals,
artifactIdentityEquals,
readArtifactIdentity,
+ readRenameFileIdentity,
} from './artifact-identity'
import * as hashing from './hash-opened-file'
@@ -97,3 +106,73 @@ describe('artifact digest reuse', () => {
})
})
})
+
+describe('rename-only artifact identity', () => {
+ afterEach(() => vi.restoreAllMocks())
+
+ it('captures a complete file stamp without reading payload bytes', async () => {
+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-rename-identity-'))
+ try {
+ const file = path.join(root, 'file.motrix')
+ await writeFile(file, 'payload')
+ const hash = vi.spyOn(hashing, 'hashOpenedFile')
+ const metadata = await stat(file, { bigint: true })
+ const identity = await readRenameFileIdentity(file)
+ expect(identity).toEqual({
+ kind: 'rename-file',
+ size: 7,
+ platformFileId: `${metadata.dev}:${metadata.ino}`,
+ mtimeNs: String(metadata.mtimeNs),
+ ctimeNs: String(metadata.ctimeNs),
+ birthtimeNs: String(metadata.birthtimeNs),
+ })
+ expect(artifactIdentityEquals(identity, { ...identity })).toBe(true)
+ expect(artifactContentEquals(identity, identity)).toBe(false)
+ for (const field of [
+ 'platformFileId',
+ 'mtimeNs',
+ 'ctimeNs',
+ 'birthtimeNs',
+ ] as const) {
+ expect(
+ artifactIdentityEquals(identity, {
+ ...identity,
+ [field]: `${identity[field]}1`,
+ })
+ ).toBe(false)
+ }
+ expect(hash).not.toHaveBeenCalled()
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('detects a same-size write even after the original modification time is restored', async () => {
+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-rename-mutation-'))
+ try {
+ const file = path.join(root, 'file.motrix')
+ await writeFile(file, 'before')
+ await utimes(file, 100, 100)
+ const before = await readRenameFileIdentity(file)
+ expect(BigInt(before.ctimeNs)).toBeGreaterThan(0n)
+ // Retry the edit until the filesystem advances its change-time tick.
+ await expect
+ .poll(
+ async () => {
+ await writeFile(file, 'edited')
+ await utimes(file, 100, 100)
+ return String((await stat(file, { bigint: true })).ctimeNs)
+ },
+ { timeout: 1000, interval: 10 }
+ )
+ .not.toBe(before.ctimeNs)
+ const after = await readRenameFileIdentity(file)
+ expect(after).toEqual({ ...before, ctimeNs: expect.any(String) })
+ expect(BigInt(after.ctimeNs)).toBeGreaterThan(0n)
+ expect(after.ctimeNs).not.toBe(before.ctimeNs)
+ expect(artifactIdentityEquals(before, after)).toBe(false)
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/src/core/plugin/finalize/artifact-identity.ts b/src/core/plugin/finalize/artifact-identity.ts
index 95f68997..475b72b6 100644
--- a/src/core/plugin/finalize/artifact-identity.ts
+++ b/src/core/plugin/finalize/artifact-identity.ts
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto'
import { constants } from 'node:fs'
import { lstat, open, readdir } from 'node:fs/promises'
import path from 'node:path'
+import { z } from 'zod'
import { hashOpenedFile } from './hash-opened-file'
export interface FileArtifactIdentity {
@@ -19,12 +20,109 @@ export interface DirectoryArtifactIdentity {
platformFileId: string
}
-export type ArtifactIdentity = FileArtifactIdentity | DirectoryArtifactIdentity
+/** Metadata authority for a write-excluded, non-destructive Windows rename only. */
+export const renameFileArtifactIdentitySchema = z
+ .object({
+ kind: z.literal('rename-file'),
+ size: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
+ platformFileId: z.string().regex(/^[1-9]\d*:[1-9]\d*$/),
+ mtimeNs: z.string().regex(/^[1-9]\d*$/),
+ ctimeNs: z.string().regex(/^[1-9]\d*$/),
+ birthtimeNs: z.string().regex(/^[1-9]\d*$/),
+ })
+ .strict()
+export type RenameFileArtifactIdentity = z.infer<
+ typeof renameFileArtifactIdentitySchema
+>
+
+export type ArtifactIdentity =
+ | FileArtifactIdentity
+ | DirectoryArtifactIdentity
+ | RenameFileArtifactIdentity
+
+/** Only a held, write-excluded rename may account for a changed ctime. */
+export function renameFileIdentityMatches(
+ left: RenameFileArtifactIdentity,
+ right: RenameFileArtifactIdentity
+): boolean {
+ return (
+ left.size === right.size &&
+ left.platformFileId === right.platformFileId &&
+ left.mtimeNs === right.mtimeNs &&
+ left.birthtimeNs === right.birthtimeNs
+ )
+}
+
+export async function readRenameFileIdentity(
+ artifactPath: string
+): Promise<RenameFileArtifactIdentity> {
+ const named = await lstat(artifactPath, { bigint: true }).catch((error) => {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
+ throw new ArtifactIdentityError(
+ 'artifact_missing',
+ 'rename artifact is missing',
+ { cause: error }
+ )
+ })
+ if (named.isSymbolicLink())
+ throw new ArtifactIdentityError(
+ 'artifact_unsafe_path',
+ 'rename artifact is a symbolic link'
+ )
+ if (!named.isFile())
+ throw new ArtifactIdentityError(
+ 'artifact_special_file',
+ 'rename artifact is not a regular file'
+ )
+ const handle = await open(
+ artifactPath,
+ constants.O_RDONLY | constants.O_NOFOLLOW
+ )
+ try {
+ const opened = await handle.stat({ bigint: true })
+ if (
+ !opened.isFile() ||
+ statKey(named) !== statKey(opened) ||
+ named.birthtimeNs !== opened.birthtimeNs
+ )
+ throw new ArtifactIdentityError(
+ 'artifact_mutated',
+ 'rename artifact changed while opening'
+ )
+ if (opened.size > BigInt(Number.MAX_SAFE_INTEGER))
+ throw new ArtifactIdentityError(
+ 'artifact_too_large',
+ 'rename artifact exceeds the safe identity range'
+ )
+ if (
+ opened.dev <= 0n ||
+ opened.ino <= 0n ||
+ opened.birthtimeNs <= 0n ||
+ opened.mtimeNs <= 0n ||
+ opened.ctimeNs <= 0n
+ )
+ throw new ArtifactIdentityError(
+ 'artifact_identity_unavailable',
+ 'rename artifact lacks stable file metadata'
+ )
+ return renameFileArtifactIdentitySchema.parse({
+ kind: 'rename-file',
+ size: Number(opened.size),
+ platformFileId: fileId(opened),
+ mtimeNs: String(opened.mtimeNs),
+ ctimeNs: String(opened.ctimeNs),
+ birthtimeNs: String(opened.birthtimeNs),
+ })
+ } finally {
+ await handle.close()
+ }
+}
export class ArtifactIdentityError extends Error {
constructor(
readonly code:
| 'artifact_missing'
+ | 'artifact_identity_unavailable'
| 'artifact_mutated'
| 'artifact_special_file'
| 'artifact_too_large'
@@ -295,6 +393,10 @@ export function artifactIdentityEquals(
right: ArtifactIdentity
): boolean {
if (left.kind !== right.kind) return false
+ if (left.kind === 'rename-file' && right.kind === 'rename-file')
+ return (
+ renameFileIdentityMatches(left, right) && left.ctimeNs === right.ctimeNs
+ )
if (left.kind === 'file' && right.kind === 'file') {
return (
left.size === right.size &&
diff --git a/src/core/plugin/finalize/filesystem-adapter.ts b/src/core/plugin/finalize/filesystem-adapter.ts
index 183f7649..a126d380 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: boolean
directorySync: boolean
heldArtifacts: boolean
+ /** Held regular-file handles exclude writers, including writable mappings. */
+ heldFileWriteExclusion?: boolean
reservedExfatRename?: boolean
tokenExfatReservation?: boolean
}
@@ -66,6 +68,7 @@ interface WireResponse {
held_roots?: boolean
directory_sync?: boolean
held_artifacts?: boolean
+ held_file_write_exclusion?: boolean
reserved_exfat_rename?: boolean
token_exfat_reservation?: boolean
volume_id?: string
@@ -248,6 +251,7 @@ export class NativeFinalizeFilesystemAdapter
heldRoots: response.held_roots === true,
directorySync: response.directory_sync === true,
heldArtifacts: response.held_artifacts === true,
+ heldFileWriteExclusion: response.held_file_write_exclusion === true,
reservedExfatRename: response.reserved_exfat_rename === true,
tokenExfatReservation: response.token_exfat_reservation === true,
}
diff --git a/src/core/plugin/finalize/finalize-committer.ts b/src/core/plugin/finalize/finalize-committer.ts
index 67e1d62a..9e2814a9 100644
--- a/src/core/plugin/finalize/finalize-committer.ts
+++ b/src/core/plugin/finalize/finalize-committer.ts
@@ -1,8 +1,11 @@
import { createHash, randomBytes } from 'node:crypto'
import path from 'node:path'
-import type {
- ArtifactIdentity,
- FileArtifactIdentity,
+import {
+ type ArtifactIdentity,
+ type FileArtifactIdentity,
+ type RenameFileArtifactIdentity,
+ renameFileArtifactIdentitySchema,
+ renameFileIdentityMatches,
} from './artifact-identity'
import type {
ArtifactMutationLease,
@@ -38,6 +41,8 @@ export interface FinalizeJournalRecord {
privateTargetIdentity?: ArtifactIdentity
targetIdentity?: ArtifactIdentity
rollbackPath?: string
+ /** Exact stamp after a verified rollback; ctime changes on every rename. */
+ restoredSourceIdentity?: RenameFileArtifactIdentity
publicationIntent?: FinalizePublicationIntent
removalIntent?: FinalizeRemovalIntent
quarantineReason?: string
@@ -99,6 +104,7 @@ export interface FinalizeJournalRepository {
| 'privateTargetIdentity'
| 'targetIdentity'
| 'rollbackPath'
+ | 'restoredSourceIdentity'
| 'removalIntent'
| 'publicationIntent'
>
@@ -114,6 +120,7 @@ export interface FinalizeJournalRepository {
| 'privateTargetIdentity'
| 'targetIdentity'
| 'rollbackPath'
+ | 'restoredSourceIdentity'
| 'quarantineReason'
>
>
@@ -137,7 +144,13 @@ export interface FinalizeArtifactOperations {
): 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>
+ renameIdentity?(
+ artifactPath: string
+ ): Promise<RenameFileArtifactIdentity | null>
+ identity(
+ artifactPath: string,
+ expected?: ArtifactIdentity
+ ): Promise<ArtifactIdentity | null>
sameFilesystem(leftPath: string, rightPath: string): Promise<boolean>
materializePrivate(
sourcePath: string,
@@ -148,7 +161,8 @@ export interface FinalizeArtifactOperations {
sourcePath: string,
expected: ArtifactIdentity,
targetPath: string
- ): Promise<void>
+ // biome-ignore lint/suspicious/noConfusingVoidType: Existing filesystem adapters return Promise<void>.
+ ): Promise<ArtifactIdentity | void>
linkNoReplace?(
sourcePath: string,
expected: ArtifactIdentity,
@@ -278,6 +292,7 @@ export class FinalizeCommitter {
// even when both paths report the same device. Reconcile the names
// before durably switching to the existing private-copy protocol.
if (
+ plan.sourceIdentity.kind === 'rename-file' ||
!(error instanceof FinalizeFsError) ||
error.code !== 'cross_device' ||
error.details?.mutation === 'applied' ||
@@ -296,6 +311,16 @@ export class FinalizeCommitter {
record.publicationMode = 'copy'
return this.commitPrepared(record, _lease)
}
+ if (plan.sourceIdentity.kind === 'rename-file') {
+ if (publishedIdentity?.kind !== 'rename-file')
+ throw new Error('native rename omitted the installed file stamp')
+ // Persist the observed post-rename ctime before any further operation.
+ // A crash before this checkpoint preserves the target but cannot authorize rollback.
+ await this.options.repository.checkpoint(record.journalId, {
+ targetIdentity: publishedIdentity,
+ })
+ record.targetIdentity = publishedIdentity
+ }
await this.options.fs.makeDurable(plan.targetPath)
} else {
if (samePath) {
@@ -446,7 +471,13 @@ export class FinalizeCommitter {
targetPath: string
): Promise<ArtifactIdentity | undefined> {
try {
- await this.options.fs.moveNoReplace(sourcePath, identity, targetPath)
+ return (
+ (await this.options.fs.moveNoReplace(
+ sourcePath,
+ identity,
+ targetPath
+ )) ?? undefined
+ )
} catch (error) {
if (
!(error instanceof FinalizeFsError) ||
@@ -545,12 +576,15 @@ export class FinalizeCommitter {
) {
return 'copy'
}
- return (await this.options.fs.sameFilesystem(
+ const sameFilesystem = await this.options.fs.sameFilesystem(
plan.sourcePath,
plan.targetPath
- ))
- ? 'move'
- : 'copy'
+ )
+ if (!sameFilesystem && plan.sourceIdentity.kind === 'rename-file')
+ throw new Error(
+ 'rename-only identity cannot authorize cross-device copying'
+ )
+ return sameFilesystem ? 'move' : 'copy'
}
private async requireExactIdentity(
@@ -558,7 +592,7 @@ export class FinalizeCommitter {
expected: ArtifactIdentity,
record: FinalizeJournalRecord
): Promise<ArtifactIdentity> {
- const actual = await this.options.fs.identity(artifactPath)
+ const actual = await this.options.fs.identity(artifactPath, expected)
if (!actual || !this.options.exactIdentity(actual, expected)) {
await this.quarantine(record, `identity mismatch at ${artifactPath}`)
}
@@ -642,6 +676,8 @@ export async function prepareRemovalIntent(
artifactPath: string,
identity: ArtifactIdentity
): Promise<FinalizeRemovalIntent> {
+ if (identity.kind === 'rename-file')
+ throw new Error('rename-only identity cannot authorize removal')
const quarantinePath = removalQuarantinePath(journalId, artifactPath)
return fs.prepareRemoval
? fs.prepareRemoval(artifactPath, identity, quarantinePath)
@@ -675,3 +711,52 @@ export function finalizePathsEquivalent(
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
: normalizedLeft === normalizedRight
}
+
+/** Metadata-only authority never extends to content replacement or removal. */
+export function assertRenameFileJournal(record: FinalizeJournalRecord): void {
+ const source = record.plan.sourceIdentity
+ if (source.kind !== 'rename-file') {
+ if (
+ record.targetIdentity?.kind === 'rename-file' ||
+ record.restoredSourceIdentity ||
+ record.privateTargetIdentity?.kind === 'rename-file' ||
+ record.removalIntent?.identity.kind === 'rename-file' ||
+ record.publicationIntent?.identity.kind === 'rename-file'
+ )
+ throw new Error('content journal contains rename-only identity')
+ return
+ }
+ renameFileArtifactIdentitySchema.parse(source)
+ if (
+ !isOrdinarySuffixRemoval(record.plan) ||
+ record.publicationMode !== 'move' ||
+ record.privateTargetPath !== undefined ||
+ record.privateTargetIdentity !== undefined ||
+ record.rollbackPath !== undefined ||
+ record.publicationIntent !== undefined ||
+ record.removalIntent !== undefined ||
+ !['prepared', 'target_installed', 'db_committed', 'cleaned'].includes(
+ record.phase
+ )
+ )
+ throw new Error('invalid rename-only journal')
+ for (const identity of [
+ record.targetIdentity,
+ record.restoredSourceIdentity,
+ ]) {
+ if (identity === undefined) continue
+ const checked = renameFileArtifactIdentitySchema.parse(identity)
+ if (!renameFileIdentityMatches(checked, source))
+ throw new Error('rename-only journal changed immutable file metadata')
+ }
+ if (
+ (record.phase === 'target_installed' || record.phase === 'db_committed') &&
+ !record.targetIdentity
+ )
+ throw new Error('rename-only journal is missing its installed stamp')
+ if (
+ record.restoredSourceIdentity &&
+ (!record.targetIdentity || record.phase === 'db_committed')
+ )
+ throw new Error('rename-only rollback is missing its installed stamp')
+}
diff --git a/src/core/plugin/finalize/finalize-recovery.test.ts b/src/core/plugin/finalize/finalize-recovery.test.ts
index 24ea397a..28351366 100644
--- a/src/core/plugin/finalize/finalize-recovery.test.ts
+++ b/src/core/plugin/finalize/finalize-recovery.test.ts
@@ -4,6 +4,7 @@ import {
type ArtifactIdentity,
artifactContentEquals,
artifactIdentityEquals,
+ type RenameFileArtifactIdentity,
} from './artifact-identity'
import { ArtifactMutationLeaseCoordinator } from './artifact-mutation-lease'
import { FinalizeFsError } from './filesystem-adapter'
@@ -99,6 +100,148 @@ function fixture(
return { artifacts, phases, quarantines, recovery, fs, repository }
}
+describe('rename-only finalize recovery', () => {
+ const original: RenameFileArtifactIdentity = {
+ kind: 'rename-file',
+ size: 1024 * 1024 * 1024,
+ platformFileId: '1:1',
+ mtimeNs: '100',
+ ctimeNs: '200',
+ birthtimeNs: '50',
+ }
+ const installed: RenameFileArtifactIdentity = { ...original, ctimeNs: '300' }
+ const restored: RenameFileArtifactIdentity = { ...original, ctimeNs: '400' }
+
+ function pendingRecord(
+ phase: FinalizeJournalRecord['phase']
+ ): FinalizeJournalRecord {
+ const pending = record(phase)
+ pending.publicationMode = 'move'
+ pending.plan.sourcePath = `${pending.plan.targetPath}.motrix`
+ pending.plan.sourceIdentity = original
+ pending.targetIdentity = phase === 'prepared' ? undefined : installed
+ return pending
+ }
+
+ it('preserves an installed target whose post-rename stamp was never checkpointed', async () => {
+ const pending = pendingRecord('prepared')
+ const state = fixture(
+ { [pending.plan.targetPath]: installed },
+ { rollForwardTargetInstalled: false }
+ )
+ const move = vi.spyOn(state.fs, 'moveNoReplace')
+ const remove = vi.spyOn(state.fs, 'removeKnown')
+ await expect(state.recovery.recover(pending)).rejects.toThrow('quarantined')
+ expect(state.artifacts.get(pending.plan.targetPath)).toEqual(installed)
+ expect(state.quarantines).toHaveLength(1)
+ expect(state.phases).toEqual([])
+ expect(move).not.toHaveBeenCalled()
+ expect(remove).not.toHaveBeenCalled()
+ })
+
+ it('rolls back a checkpointed target by rename and records the restored stamp', async () => {
+ const pending = pendingRecord('target_installed')
+ const state = fixture(
+ { [pending.plan.targetPath]: installed },
+ { rollForwardTargetInstalled: false }
+ )
+ state.fs.moveNoReplace = vi.fn(async (source, expected, target) => {
+ expect(expected).toEqual(installed)
+ expect(state.artifacts.has(target)).toBe(false)
+ state.artifacts.delete(source)
+ state.artifacts.set(target, restored)
+ return restored
+ })
+ const remove = vi.spyOn(state.fs, 'removeKnown')
+ await state.recovery.recover(pending)
+ expect([...state.artifacts.entries()]).toEqual([
+ [pending.plan.sourcePath, restored],
+ ])
+ expect(state.repository.checkpoint).toHaveBeenCalledWith(
+ pending.journalId,
+ { restoredSourceIdentity: restored }
+ )
+ expect(state.phases).toEqual(['cleaned'])
+ expect(remove).not.toHaveBeenCalled()
+ })
+
+ it('recognizes a checkpointed rollback without renaming or deleting again', async () => {
+ const pending = {
+ ...pendingRecord('target_installed'),
+ restoredSourceIdentity: restored,
+ }
+ const state = fixture(
+ { [pending.plan.sourcePath]: restored },
+ { rollForwardTargetInstalled: false }
+ )
+ const move = vi.spyOn(state.fs, 'moveNoReplace')
+ const remove = vi.spyOn(state.fs, 'removeKnown')
+ await state.recovery.recover(pending)
+ expect(state.phases).toEqual(['cleaned'])
+ expect(move).not.toHaveBeenCalled()
+ expect(remove).not.toHaveBeenCalled()
+ expect(state.artifacts.get(pending.plan.sourcePath)).toEqual(restored)
+ })
+
+ it.each(['target_installed', 'db_committed'] as const)(
+ 'preserves a %s target changed after its persisted stamp',
+ async (phase) => {
+ const pending = pendingRecord(phase)
+ // An in-place edit can retain size, inode and mtime; ctime still matters.
+ const changed = { ...installed, ctimeNs: '999' }
+ const state = fixture(
+ { [pending.plan.targetPath]: changed },
+ { rollForwardTargetInstalled: false }
+ )
+ const move = vi.spyOn(state.fs, 'moveNoReplace')
+ const remove = vi.spyOn(state.fs, 'removeKnown')
+ await expect(state.recovery.recover(pending)).rejects.toThrow(
+ 'quarantined'
+ )
+ expect(state.artifacts.get(pending.plan.targetPath)).toEqual(changed)
+ expect(move).not.toHaveBeenCalled()
+ expect(remove).not.toHaveBeenCalled()
+ expect(state.phases).toEqual([])
+ }
+ )
+
+ it('quarantines two surviving names without deleting either artifact', async () => {
+ const pending = pendingRecord('target_installed')
+ const state = fixture(
+ {
+ [pending.plan.sourcePath]: original,
+ [pending.plan.targetPath]: installed,
+ },
+ { rollForwardTargetInstalled: false }
+ )
+ const move = vi.spyOn(state.fs, 'moveNoReplace')
+ const remove = vi.spyOn(state.fs, 'removeKnown')
+ await expect(state.recovery.recover(pending)).rejects.toThrow('quarantined')
+ expect(state.artifacts.size).toBe(2)
+ expect(move).not.toHaveBeenCalled()
+ expect(remove).not.toHaveBeenCalled()
+ })
+
+ it('cleans a committed rename using only its exact target stamp', async () => {
+ const pending = pendingRecord('db_committed')
+ const state = fixture({ [pending.plan.targetPath]: installed })
+ const remove = vi.spyOn(state.fs, 'removeKnown')
+ const move = vi.spyOn(state.fs, 'moveNoReplace')
+ await state.recovery.recover(pending)
+ expect(state.phases).toEqual(['cleaned'])
+ expect(remove).not.toHaveBeenCalled()
+ expect(move).not.toHaveBeenCalled()
+ })
+
+ it('defers recovery when neither rename name is available', async () => {
+ const pending = pendingRecord('prepared')
+ const state = fixture({})
+ await expect(state.recovery.recover(pending)).rejects.toThrow('unavailable')
+ expect(state.quarantines).toEqual([])
+ expect(state.phases).toEqual([])
+ })
+})
+
describe('FinalizeRecovery', () => {
it.each([
'ENOENT',
diff --git a/src/core/plugin/finalize/finalize-recovery.ts b/src/core/plugin/finalize/finalize-recovery.ts
index 68ce0a71..c88895db 100644
--- a/src/core/plugin/finalize/finalize-recovery.ts
+++ b/src/core/plugin/finalize/finalize-recovery.ts
@@ -5,6 +5,7 @@ import type {
ArtifactMutationLeaseCoordinator,
} from './artifact-mutation-lease'
import {
+ assertRenameFileJournal,
type FinalizeArtifactOperations,
type FinalizeJournalRecord,
type FinalizeJournalRepository,
@@ -83,6 +84,12 @@ export class FinalizeRecovery {
const lease =
existingLease ?? (await this.options.leases.acquire(record.plan.taskId))
try {
+ assertRenameFileJournal(record)
+ if (record.plan.sourceIdentity.kind === 'rename-file') {
+ if (record.quarantineReason) return
+ await this.recoverRenameFile(record)
+ return
+ }
if (record.quarantineReason) {
if (!this.options.repository.resumeQuarantined) return
// Legacy compensation failures can be reopened only for an ordinary
@@ -305,6 +312,87 @@ export class FinalizeRecovery {
}
}
+ /**
+ * Ordinary Windows renames do not read payload bytes. A lost post-rename
+ * checkpoint cannot establish the new ctime, so it preserves/quarantines
+ * the target instead of guessing ownership or moving an uncertain file.
+ */
+ private async recoverRenameFile(
+ record: FinalizeJournalRecord
+ ): Promise<void> {
+ const expectedSource =
+ record.restoredSourceIdentity ?? record.plan.sourceIdentity
+ const source = await this.options.fs.identity(
+ record.plan.sourcePath,
+ expectedSource
+ )
+ const target = await this.options.fs.identity(
+ record.plan.targetPath,
+ record.targetIdentity ?? record.plan.sourceIdentity
+ )
+ if (!source && !target)
+ throw new FinalizeRecoveryDeferredError(
+ 'rename artifacts are unavailable; retry recovery'
+ )
+ if (source && target)
+ return this.quarantine(
+ record,
+ 'source and target both exist during rename recovery'
+ )
+ if (source) {
+ if (
+ record.phase === 'db_committed' ||
+ !this.options.exactIdentity(source, expectedSource)
+ )
+ return this.quarantine(record, 'renamed source stamp changed')
+ await this.options.fs.makeDurable(record.plan.sourcePath)
+ await this.options.repository.advance(record.journalId, 'cleaned')
+ return
+ }
+ const expectedTarget = record.targetIdentity
+ if (
+ !expectedTarget ||
+ !target ||
+ !this.options.exactIdentity(target, expectedTarget)
+ )
+ return this.quarantine(
+ record,
+ 'renamed target has no matching durable stamp'
+ )
+ if (record.phase === 'db_committed') {
+ await this.options.repository.advance(record.journalId, 'cleaned')
+ return
+ }
+ if (
+ record.phase === 'target_installed' &&
+ this.options.rollForwardTargetInstalled !== false
+ ) {
+ await this.options.repository.commitTerminal(record)
+ record.phase = 'db_committed'
+ await this.options.repository.advance(record.journalId, 'cleaned')
+ return
+ }
+ const restored = await this.options.fs.moveNoReplace(
+ record.plan.targetPath,
+ expectedTarget,
+ record.plan.sourcePath
+ )
+ if (restored?.kind !== 'rename-file')
+ return this.quarantine(record, 'rollback omitted the restored file stamp')
+ await this.options.repository.checkpoint(record.journalId, {
+ restoredSourceIdentity: restored,
+ })
+ record.restoredSourceIdentity = restored
+ await this.options.fs.makeDurable(record.plan.sourcePath)
+ const current = await this.options.fs.identity(
+ record.plan.sourcePath,
+ restored
+ )
+ if (!current || !this.options.exactIdentity(current, restored))
+ return this.quarantine(record, 'restored source stamp changed')
+ await this.options.repository.advance(record.journalId, 'cleaned')
+ }
+
private async recoverReserved(record: FinalizeJournalRecord): Promise<void> {
let intent = record.publicationIntent
if (intent?.method !== 'reserved_rename')
diff --git a/src/core/plugin/finalize/hook-plan.ts b/src/core/plugin/finalize/hook-plan.ts
index 08efe7ad..26de5a3d 100644
--- a/src/core/plugin/finalize/hook-plan.ts
+++ b/src/core/plugin/finalize/hook-plan.ts
@@ -31,7 +31,8 @@ export interface HookPlan {
/** The exFAT compatibility contract is limited to unmodified download names. */
export function isOrdinarySuffixRemoval(plan: HookPlan): boolean {
return (
- plan.sourceIdentity.kind === 'file' &&
+ (plan.sourceIdentity.kind === 'file' ||
+ plan.sourceIdentity.kind === 'rename-file') &&
!plan.replacement &&
plan.contributors.length === 0 &&
plan.metadataOps.length === 0 &&
@@ -53,6 +54,13 @@ export function assertFinalizePaths(
export function assertValidHookPlan(plan: HookPlan): void {
assertFinalizePaths(plan.saveDir, plan.sourcePath, plan.targetPath)
+ if (
+ plan.sourceIdentity.kind === 'rename-file' &&
+ !isOrdinarySuffixRemoval(plan)
+ )
+ throw new Error('rename-only identity requires an ordinary suffix removal')
+ if (plan.replacement?.identity.kind === 'rename-file')
+ throw new Error('replacement requires a content identity')
if (
plan.replacement?.identity.kind !== undefined &&
!plan.replacement.pluginId
diff --git a/src/core/plugin/finalize/native-artifact-operations.integration.test.ts b/src/core/plugin/finalize/native-artifact-operations.integration.test.ts
index c856d32d..1d948c17 100644
--- a/src/core/plugin/finalize/native-artifact-operations.integration.test.ts
+++ b/src/core/plugin/finalize/native-artifact-operations.integration.test.ts
@@ -4,12 +4,14 @@ import {
link,
mkdir,
mkdtemp,
+ open,
readFile,
realpath,
rename,
rm,
stat,
symlink,
+ utimes,
writeFile,
} from 'node:fs/promises'
import os from 'node:os'
@@ -18,7 +20,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import {
artifactContentEquals,
artifactIdentityEquals,
+ type RenameFileArtifactIdentity,
readArtifactIdentity,
+ readRenameFileIdentity,
} from './artifact-identity'
import { ArtifactMutationLeaseCoordinator } from './artifact-mutation-lease'
import { NativeFinalizeFilesystemAdapter } from './filesystem-adapter'
@@ -72,6 +76,30 @@ describe.runIf(existsSync(binary))(
return { root, adapter, operations }
}
+ async function writeEditWithDistinctCtime(
+ source: string,
+ before: RenameFileArtifactIdentity
+ ): Promise<RenameFileArtifactIdentity> {
+ expect(BigInt(before.ctimeNs)).toBeGreaterThan(0n)
+ // Filesystems can stamp adjacent writes in the same clock tick. Establish
+ // the changed ctime this fixture needs before testing rename rejection.
+ await expect
+ .poll(
+ async () => {
+ await writeFile(source, 'edited')
+ await utimes(source, 100, 100)
+ return String((await stat(source, { bigint: true })).ctimeNs)
+ },
+ { timeout: 1000, interval: 10 }
+ )
+ .not.toBe(before.ctimeNs)
+ const after = await readRenameFileIdentity(source)
+ expect(after).toEqual({ ...before, ctimeNs: expect.any(String) })
+ expect(BigInt(after.ctimeNs)).toBeGreaterThan(0n)
+ expect(after.ctimeNs).not.toBe(before.ctimeNs)
+ return after
+ }
+
it.each([false, true])(
'syncs rename directories in the native layer, retaining legacy fallback: %s',
async (legacy) => {
@@ -176,6 +204,303 @@ describe.runIf(existsSync(binary))(
}
})
+ it('performs no payload reads or copies for a large suffix rename with simulated Windows exclusion', async () => {
+ const { root, adapter, operations } = await setup()
+ // This exercises the TypeScript protocol on the available helper. Windows
+ // sharing-mode exclusion is verified by the native Windows tests.
+ const capabilities = await adapter.capabilities()
+ vi.spyOn(adapter, 'capabilities').mockResolvedValue({
+ ...capabilities,
+ platform: 'windows',
+ heldFileWriteExclusion: true,
+ })
+ const source = path.join(root, 'archive.zip.motrix')
+ const target = path.join(root, 'archive.zip')
+ const fileSize = 17 * 1024 * 1024
+ const file = await open(source, 'wx')
+ await file.write('completed download')
+ await file.truncate(fileSize)
+ await file.close()
+ const hash = vi.spyOn(hashing, 'hashOpenedFile')
+ const copy = vi.spyOn(adapter, 'copyOpened')
+ const materialize = vi.spyOn(operations, 'materializePrivate')
+ const nativeOpen = vi.spyOn(adapter, 'openArtifact')
+ const commitTerminal = vi.fn()
+ try {
+ const sourceIdentity = await operations.renameIdentity(source)
+ if (!sourceIdentity) throw new Error('missing rename identity')
+ const committer = new FinalizeCommitter({
+ fs: operations,
+ leases: new ArtifactMutationLeaseCoordinator([]),
+ repository: {
+ prepare: vi.fn(),
+ checkpoint: vi.fn(),
+ advance: vi.fn(),
+ commitTerminal,
+ quarantine: vi.fn(),
+ listRecoverable: async () => [],
+ },
+ privatePathFor: () => path.join(root, '.private'),
+ rollbackPathFor: () => path.join(root, '.rollback'),
+ exactIdentity: artifactIdentityEquals,
+ sameContent: artifactContentEquals,
+ })
+ const result = await committer.commit({
+ planId: 'rename-only-plan',
+ taskId: 'rename-only-task',
+ saveDir: root,
+ sourcePath: source,
+ targetPath: target,
+ sourceIdentity,
+ metadataOps: [],
+ contributors: [],
+ })
+ expect(result.targetIdentity).toEqual(
+ await readRenameFileIdentity(target)
+ )
+ expect(hash).not.toHaveBeenCalled()
+ expect(copy).not.toHaveBeenCalled()
+ expect(materialize).not.toHaveBeenCalled()
+ expect(nativeOpen).toHaveBeenCalledWith(
+ expect.anything(),
+ 'archive.zip.motrix',
+ 'rename'
+ )
+ expect(commitTerminal).toHaveBeenCalledOnce()
+ expect(existsSync(source)).toBe(false)
+ expect((await stat(target)).size).toBe(fileSize)
+ const published = await open(target, 'r')
+ try {
+ const buffer = Buffer.alloc(18)
+ await published.read(buffer, 0, buffer.length, 0)
+ expect(buffer.toString()).toBe('completed download')
+ } finally {
+ await published.close()
+ }
+ } finally {
+ await adapter.dispose()
+ }
+ })
+
+ it.each([
+ { platform: 'windows', heldFileWriteExclusion: undefined },
+ { platform: 'windows', heldFileWriteExclusion: false },
+ { platform: 'macos', heldFileWriteExclusion: true },
+ { platform: 'linux', heldFileWriteExclusion: true },
+ ])(
+ 'requires Windows held-file write exclusion for metadata capture: %j',
+ async (unsupported) => {
+ const { root, adapter, operations } = await setup()
+ const capabilities = await adapter.capabilities()
+ vi.spyOn(adapter, 'capabilities').mockResolvedValue({
+ ...capabilities,
+ ...unsupported,
+ })
+ const source = path.join(root, 'download.motrix')
+ await writeFile(source, 'payload')
+ try {
+ expect(await operations.renameIdentity(source)).toBeNull()
+ } finally {
+ await adapter.dispose()
+ }
+ }
+ )
+
+ it('rejects a same-size edit with restored mtime before a metadata-only rename', async () => {
+ const { root, adapter, operations } = await setup()
+ const capabilities = await adapter.capabilities()
+ vi.spyOn(adapter, 'capabilities').mockResolvedValue({
+ ...capabilities,
+ platform: 'windows',
+ heldFileWriteExclusion: true,
+ })
+ const source = path.join(root, 'download.motrix')
+ const target = path.join(root, 'download')
+ await writeFile(source, 'before')
+ await utimes(source, 100, 100)
+ const identity = await readRenameFileIdentity(source)
+ const rename = vi.spyOn(adapter, 'renameOpenedNoReplace')
+ const copy = vi.spyOn(adapter, 'copyOpened')
+ const remove = vi.spyOn(adapter, 'removeOpened')
+ try {
+ await writeEditWithDistinctCtime(source, identity)
+ await expect(
+ operations.moveNoReplace(source, identity, target)
+ ).rejects.toThrow()
+ expect(rename).not.toHaveBeenCalled()
+ expect(copy).not.toHaveBeenCalled()
+ expect(remove).not.toHaveBeenCalled()
+ expect(await readFile(source, 'utf8')).toBe('edited')
+ expect(existsSync(target)).toBe(false)
+ } finally {
+ await adapter.dispose()
+ }
+ })
+
+ it('rejects metadata changes between initial validation and opening the native artifact', async () => {
+ const { root, adapter, operations } = await setup()
+ const capabilities = await adapter.capabilities()
+ vi.spyOn(adapter, 'capabilities').mockResolvedValue({
+ ...capabilities,
+ platform: 'windows',
+ heldFileWriteExclusion: true,
+ })
+ const source = path.join(root, 'download.motrix')
+ const target = path.join(root, 'download')
+ await writeFile(source, 'before')
+ await utimes(source, 100, 100)
+ const identity = await readRenameFileIdentity(source)
+ const openArtifact = adapter.openArtifact.bind(adapter)
+ let editedIdentity: RenameFileArtifactIdentity | undefined
+ vi.spyOn(adapter, 'openArtifact').mockImplementation(async (...args) => {
+ editedIdentity = await writeEditWithDistinctCtime(source, identity)
+ return openArtifact(...args)
+ })
+ const rename = vi.spyOn(adapter, 'renameOpenedNoReplace')
+ const copy = vi.spyOn(adapter, 'copyOpened')
+ const remove = vi.spyOn(adapter, 'removeOpened')
+ try {
+ await expect(
+ operations.moveNoReplace(source, identity, target)
+ ).rejects.toThrow()
+ expect(editedIdentity).toBeDefined()
+ expect(editedIdentity?.ctimeNs).not.toBe(identity.ctimeNs)
+ expect(rename).not.toHaveBeenCalled()
+ expect(copy).not.toHaveBeenCalled()
+ expect(remove).not.toHaveBeenCalled()
+ expect(await readFile(source, 'utf8')).toBe('edited')
+ expect(existsSync(target)).toBe(false)
+ } finally {
+ await adapter.dispose()
+ }
+ })
+
+ it('leaves directory artifacts on the content-verified path', async () => {
+ const { root, adapter, operations } = await setup()
+ const capabilities = await adapter.capabilities()
+ vi.spyOn(adapter, 'capabilities').mockResolvedValue({
+ ...capabilities,
+ platform: 'windows',
+ heldFileWriteExclusion: true,
+ })
+ const source = path.join(root, 'download.motrix')
+ await mkdir(source)
+ await writeFile(path.join(source, 'payload'), 'content')
+ const hash = vi.spyOn(hashing, 'hashOpenedFile')
+ try {
+ expect(await operations.renameIdentity(source)).toBeNull()
+ expect(await operations.identity(source)).toMatchObject({
+ kind: 'directory',
+ entryCount: 1,
+ totalBytes: 7,
+ })
+ expect(hash).toHaveBeenCalledOnce()
+ } finally {
+ await adapter.dispose()
+ }
+ })
+
+ it.each(['native-response', 'target-checkpoint'] as const)(
+ 'preserves a successful rename when its %s is lost',
+ async (failure) => {
+ const { root, adapter, operations } = await setup()
+ const capabilities = await adapter.capabilities()
+ vi.spyOn(adapter, 'capabilities').mockResolvedValue({
+ ...capabilities,
+ platform: 'windows',
+ heldFileWriteExclusion: true,
+ })
+ const source = path.join(root, 'download.motrix')
+ const target = path.join(root, 'download')
+ await writeFile(source, 'complete payload')
+ const sourceIdentity = await readRenameFileIdentity(source)
+ if (failure === 'native-response') {
+ const rename = adapter.renameOpenedNoReplace.bind(adapter)
+ vi.spyOn(adapter, 'renameOpenedNoReplace').mockImplementation(
+ async (...args) => {
+ await rename(...args)
+ throw new Error('rename response lost')
+ }
+ )
+ }
+ const repository = {
+ prepare: vi.fn(),
+ checkpoint: vi.fn(async () => {
+ if (failure === 'target-checkpoint')
+ throw new Error('checkpoint failed')
+ }),
+ advance: vi.fn(),
+ commitTerminal: vi.fn(),
+ quarantine: vi.fn(),
+ listRecoverable: async () => [],
+ }
+ const move = vi.spyOn(operations, 'moveNoReplace')
+ const remove = vi.spyOn(operations, 'removeKnown')
+ const committer = new FinalizeCommitter({
+ fs: operations,
+ leases: new ArtifactMutationLeaseCoordinator([]),
+ repository,
+ privatePathFor: () => path.join(root, '.private'),
+ rollbackPathFor: () => path.join(root, '.rollback'),
+ exactIdentity: artifactIdentityEquals,
+ sameContent: artifactContentEquals,
+ })
+ try {
+ await expect(
+ committer.commit({
+ planId: 'ambiguous-rename',
+ taskId: 'ambiguous-task',
+ saveDir: root,
+ sourcePath: source,
+ targetPath: target,
+ sourceIdentity,
+ metadataOps: [],
+ contributors: [],
+ })
+ ).rejects.toThrow('quarantined')
+ expect(repository.quarantine).toHaveBeenCalledWith(
+ 'ambiguous-rename',
+ 'renamed target has no matching durable stamp'
+ )
+ expect(repository.commitTerminal).not.toHaveBeenCalled()
+ expect(move).toHaveBeenCalledOnce()
+ expect(remove).not.toHaveBeenCalled()
+ expect(existsSync(source)).toBe(false)
+ expect(await readFile(target, 'utf8')).toBe('complete payload')
+ } finally {
+ await adapter.dispose()
+ }
+ }
+ )
+
+ it('never copies, links, or deletes an artifact authorized only for rename', async () => {
+ const { root, adapter, operations } = await setup()
+ const source = path.join(root, 'download.motrix')
+ const target = path.join(root, 'download')
+ await writeFile(source, 'payload')
+ const identity = await readRenameFileIdentity(source)
+ const copy = vi.spyOn(adapter, 'copyOpened')
+ const link = vi.spyOn(adapter, 'linkOpenedNoReplace')
+ const remove = vi.spyOn(adapter, 'removeOpened')
+ try {
+ await expect(
+ operations.materializePrivate(source, identity, target)
+ ).rejects.toThrow()
+ await expect(
+ operations.linkNoReplace(source, identity, target)
+ ).rejects.toThrow()
+ await expect(
+ operations.removeKnown(source, identity, path.join(root, '.remove'))
+ ).rejects.toThrow()
+ expect(copy).not.toHaveBeenCalled()
+ expect(link).not.toHaveBeenCalled()
+ expect(remove).not.toHaveBeenCalled()
+ expect(await readFile(source, 'utf8')).toBe('payload')
+ } finally {
+ await adapter.dispose()
+ }
+ })
+
it.runIf(process.platform !== 'win32')(
'rejects a different held isolation directory identity',
async () => {
diff --git a/src/core/plugin/finalize/native-artifact-operations.ts b/src/core/plugin/finalize/native-artifact-operations.ts
index 0f165e8e..0dbac1fd 100644
--- a/src/core/plugin/finalize/native-artifact-operations.ts
+++ b/src/core/plugin/finalize/native-artifact-operations.ts
@@ -8,7 +8,10 @@ import {
ArtifactIdentityError,
artifactIdentityEquals,
type FileArtifactIdentity,
+ type RenameFileArtifactIdentity,
readArtifactIdentity,
+ readRenameFileIdentity,
+ renameFileIdentityMatches,
} from './artifact-identity'
import {
type FinalizeFilesystemAdapter,
@@ -168,8 +171,39 @@ export class NativeFinalizeArtifactOperations
}
}
- async identity(artifactPath: string): Promise<ArtifactIdentity | null> {
+ async renameIdentity(
+ artifactPath: string
+ ): Promise<RenameFileArtifactIdentity | null> {
+ if (!(await this.supportsRenameIdentity())) return null
try {
+ return await readRenameFileIdentity(artifactPath)
+ } catch (error) {
+ if (
+ error instanceof ArtifactIdentityError &&
+ (error.code === 'artifact_missing' ||
+ error.code === 'artifact_special_file' ||
+ error.code === 'artifact_identity_unavailable')
+ )
+ return null
+ throw error
+ }
+ }
+
+ private async supportsRenameIdentity(): Promise<boolean> {
+ const capabilities = await this.adapter.capabilities()
+ return (
+ capabilities.platform === 'windows' &&
+ capabilities.heldFileWriteExclusion === true
+ )
+ }
+
+ async identity(
+ artifactPath: string,
+ expected?: ArtifactIdentity
+ ): Promise<ArtifactIdentity | null> {
+ try {
+ if (expected?.kind === 'rename-file')
+ return await readRenameFileIdentity(artifactPath)
return await readArtifactIdentity(artifactPath, {
cache: this.identityCache,
})
@@ -195,6 +229,7 @@ export class NativeFinalizeArtifactOperations
expected: ArtifactIdentity,
privateTargetPath: string
): Promise<ArtifactIdentity> {
+ this.requireContentIdentity(expected)
await this.assertSupported()
await this.requireIdentity(sourcePath, expected)
await this.ensureSafeDirectory(path.dirname(privateTargetPath))
@@ -247,7 +282,7 @@ export class NativeFinalizeArtifactOperations
sourcePath: string,
expected: ArtifactIdentity,
targetPath: string
- ): Promise<void> {
+ ): Promise<ArtifactIdentity | undefined> {
return this.publishOpened(sourcePath, expected, targetPath, 'rename')
}
@@ -256,7 +291,8 @@ export class NativeFinalizeArtifactOperations
expected: ArtifactIdentity,
targetPath: string
): Promise<void> {
- return this.publishOpened(sourcePath, expected, targetPath, 'link')
+ this.requireContentIdentity(expected)
+ await this.publishOpened(sourcePath, expected, targetPath, 'link')
}
private async publishOpened(
@@ -264,7 +300,14 @@ export class NativeFinalizeArtifactOperations
expected: ArtifactIdentity,
targetPath: string,
method: 'rename' | 'link'
- ): Promise<void> {
+ ): Promise<ArtifactIdentity | undefined> {
+ if (
+ expected.kind === 'rename-file' &&
+ (method !== 'rename' || !(await this.supportsRenameIdentity()))
+ )
+ throw new Error(
+ 'rename-only identity requires native file write exclusion'
+ )
await this.assertSupported()
await this.requireIdentity(sourcePath, expected)
await this.ensureSafeDirectory(path.dirname(targetPath))
@@ -301,6 +344,17 @@ export class NativeFinalizeArtifactOperations
await this.adapter.syncRoot(sourceRoot)
await this.adapter.syncRoot(targetRoot)
}
+ if (expected.kind === 'rename-file') {
+ // The native regular-file handle still excludes writes here. Only the
+ // ctime changed by this successful rename can be accepted without reading bytes.
+ const installed = await readRenameFileIdentity(targetPath)
+ if (!renameFileIdentityMatches(installed, expected))
+ throw new ArtifactIdentityError(
+ 'artifact_mutated',
+ 'renamed artifact changed'
+ )
+ return installed
+ }
await this.requireIdentity(targetPath, expected)
} finally {
if (artifact) await this.adapter.close(artifact).catch(() => undefined)
@@ -326,6 +380,7 @@ export class NativeFinalizeArtifactOperations
identity: ArtifactIdentity,
quarantinePath: string
): Promise<FinalizeRemovalIntent> {
+ this.requireContentIdentity(identity)
await this.assertSupported()
if (process.platform === 'win32' || identity.kind !== 'file') {
return { artifactPath, identity, quarantinePath }
@@ -492,6 +547,8 @@ export class NativeFinalizeArtifactOperations
isolation?: FinalizeIsolation,
survivor?: FinalizeRemovalSurvivor
): Promise<void> {
+ this.requireContentIdentity(expected)
+ if (survivor) this.requireContentIdentity(survivor.identity)
await this.assertSupported()
if (isolation)
return this.removeIsolated(
@@ -626,13 +683,23 @@ export class NativeFinalizeArtifactOperations
await this.adapter.close(held).catch(() => undefined)
}
+ private requireContentIdentity(identity: ArtifactIdentity): void {
+ if (identity.kind === 'rename-file')
+ throw new Error(
+ 'rename-only identity cannot authorize copying or deletion'
+ )
+ }
+
private async requireIdentity(
artifactPath: string,
expected: ArtifactIdentity
): Promise<void> {
- const actual = await readArtifactIdentity(artifactPath, {
- cache: this.identityCache,
- })
+ const actual =
+ expected.kind === 'rename-file'
+ ? await readRenameFileIdentity(artifactPath)
+ : await readArtifactIdentity(artifactPath, {
+ cache: this.identityCache,
+ })
if (!artifactIdentityEquals(actual, expected)) {
throw new ArtifactIdentityError(
'artifact_mutated',
diff --git a/src/core/session/durable-finalize-runtime.test.ts b/src/core/session/durable-finalize-runtime.test.ts
index 8e82eadd..68467e3e 100644
--- a/src/core/session/durable-finalize-runtime.test.ts
+++ b/src/core/session/durable-finalize-runtime.test.ts
@@ -4,6 +4,7 @@ import os from 'node:os'
import path from 'node:path'
import {
type ArtifactIdentity,
+ type RenameFileArtifactIdentity,
readArtifactIdentity,
} from '@core/plugin/finalize/artifact-identity'
import { ArtifactMutationLeaseCoordinator } from '@core/plugin/finalize/artifact-mutation-lease'
@@ -15,6 +16,15 @@ import Database from 'better-sqlite3'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { DurableFinalizeRuntime } from './durable-finalize-runtime'
+const renameIdentity: RenameFileArtifactIdentity = {
+ kind: 'rename-file',
+ size: 1024 * 1024 * 1024,
+ platformFileId: '1:1',
+ mtimeNs: '100',
+ ctimeNs: '200',
+ birthtimeNs: '50',
+}
+
describe('DurableFinalizeRuntime', () => {
const roots: string[] = []
@@ -163,6 +173,181 @@ describe('DurableFinalizeRuntime', () => {
db.close()
}
})
+
+ it('selects metadata after quiescing writers and persists the installed rename stamp', async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-rename-only-'))
+ roots.push(root)
+ const targetPath = path.join(root, 'archive.zip')
+ const sourcePath = `${targetPath}.motrix`
+ const installedIdentity = { ...renameIdentity, ctimeNs: '300' }
+ const artifacts = new Map<string, ArtifactIdentity>([
+ [sourcePath, renameIdentity],
+ ])
+ const events: string[] = []
+ const fs = {
+ renameIdentity: vi.fn(async () => {
+ events.push('capture')
+ return renameIdentity
+ }),
+ identity: vi.fn(
+ async (artifactPath: string, expected?: ArtifactIdentity) => {
+ expect(expected?.kind).toBe('rename-file')
+ return artifacts.get(artifactPath) ?? null
+ }
+ ),
+ sameFilesystem: async () => true,
+ materializePrivate: vi.fn(),
+ moveNoReplace: vi.fn(
+ async (
+ _source: string,
+ _expected: ArtifactIdentity,
+ target: string
+ ) => {
+ artifacts.delete(sourcePath)
+ artifacts.set(target, installedIdentity)
+ return installedIdentity
+ }
+ ),
+ makeDurable: vi.fn(async () => undefined),
+ removeKnown: vi.fn(),
+ } satisfies FinalizeArtifactOperations
+ const db = new Database(':memory:')
+ migrate(db)
+ const runtime = new DurableFinalizeRuntime({
+ db,
+ fs,
+ leases: new ArtifactMutationLeaseCoordinator([
+ {
+ quiesce: async () => {
+ events.push('quiesce')
+ return () => {
+ events.push('release')
+ }
+ },
+ },
+ ]),
+ session: {
+ persistFinalizedArtifact: async (_task, _occurrence, _input, commit) =>
+ commit((mutation) => {
+ db.prepare(
+ "UPDATE plugin_finalize_journals SET phase='db_committed', plan_json=json_set(plan_json, '$.phase', 'db_committed') WHERE plan_id=?"
+ ).run(mutation.journalId)
+ }),
+ },
+ })
+ try {
+ const result = await runtime.commit({
+ task: makeDownloadTask({ id: 'rename-only', saveDir: root }),
+ occurrence: null,
+ sourcePath,
+ targetPath,
+ metadataOps: [],
+ contributors: [],
+ postDeliveries: [],
+ })
+ expect(result.targetIdentity).toEqual(installedIdentity)
+ expect(events).toEqual(['quiesce', 'capture', 'release'])
+ expect(fs.renameIdentity).toHaveBeenCalledExactlyOnceWith(sourcePath)
+ expect(fs.materializePrivate).not.toHaveBeenCalled()
+ expect(fs.removeKnown).not.toHaveBeenCalled()
+ expect(
+ db
+ .prepare(
+ 'SELECT phase, target_identity_json FROM plugin_finalize_journals'
+ )
+ .get()
+ ).toEqual({
+ phase: 'cleaned',
+ target_identity_json: JSON.stringify(installedIdentity),
+ })
+ } finally {
+ db.close()
+ }
+ })
+
+ it.each([
+ 'unsupported',
+ 'nonordinary-name',
+ 'plugin',
+ 'metadata',
+ 'replacement',
+ ] as const)(
+ 'retains content identities for %s finalization',
+ async (scenario) => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-rename-scope-'))
+ roots.push(root)
+ const targetPath = path.join(root, 'archive.zip')
+ const sourcePath =
+ scenario === 'nonordinary-name'
+ ? `${targetPath}.part`
+ : `${targetPath}.motrix`
+ const fullIdentity: ArtifactIdentity = {
+ kind: 'file',
+ size: 4,
+ platformFileId: '1:1',
+ sha256: 'a'.repeat(64),
+ }
+ const fs = {
+ renameIdentity: vi.fn(async () =>
+ scenario === 'unsupported' ? null : renameIdentity
+ ),
+ identity: vi.fn(async () => fullIdentity),
+ sameFilesystem: vi.fn(),
+ materializePrivate: vi.fn(),
+ moveNoReplace: vi.fn(),
+ makeDurable: vi.fn(),
+ removeKnown: vi.fn(),
+ } satisfies FinalizeArtifactOperations
+ const db = new Database(':memory:')
+ migrate(db)
+ const runtime = new DurableFinalizeRuntime({
+ db,
+ fs,
+ session: {
+ persistFinalizedArtifact: async () => {
+ throw new Error('captured content identity')
+ },
+ },
+ })
+ try {
+ await expect(
+ runtime.commit({
+ task: makeDownloadTask({ id: `scope-${scenario}`, saveDir: root }),
+ occurrence: null,
+ sourcePath,
+ targetPath,
+ metadataOps:
+ scenario === 'metadata'
+ ? [
+ {
+ pluginId: 'example.test',
+ op: 'set',
+ key: 'note',
+ value: 'value',
+ },
+ ]
+ : [],
+ contributors: scenario === 'plugin' ? ['example.test'] : [],
+ replacement:
+ scenario === 'replacement'
+ ? {
+ pluginId: 'example.test',
+ stagedPath: path.join(root, 'replacement'),
+ }
+ : undefined,
+ postDeliveries: [],
+ })
+ ).rejects.toThrow('captured content identity')
+ expect(fs.renameIdentity).toHaveBeenCalledTimes(
+ scenario === 'unsupported' ? 1 : 0
+ )
+ expect(fs.identity).toHaveBeenCalledWith(sourcePath)
+ expect(fs.moveNoReplace).not.toHaveBeenCalled()
+ } finally {
+ db.close()
+ }
+ }
+ )
})
it('rejects an invalid target before acquiring leases or reading file identities', async () => {
diff --git a/src/core/session/durable-finalize-runtime.ts b/src/core/session/durable-finalize-runtime.ts
index 7ff3592f..f6f67c71 100644
--- a/src/core/session/durable-finalize-runtime.ts
+++ b/src/core/session/durable-finalize-runtime.ts
@@ -114,6 +114,13 @@ export class DurableFinalizeRuntime {
// engine/Host writer has successfully quiesced.
const sourceIdentity =
pending?.plan.sourceIdentity ??
+ (!input.replacement &&
+ input.contributors.length === 0 &&
+ input.metadataOps.length === 0 &&
+ input.sourcePath === `${targetPath}.motrix` &&
+ path.dirname(input.sourcePath) === path.dirname(targetPath)
+ ? await this.options.fs.renameIdentity?.(input.sourcePath)
+ : undefined) ??
(await this.captureIdentity(input.sourcePath))
const replacement = input.replacement
? {
diff --git a/src/core/session/finalize-journal-repository.test.ts b/src/core/session/finalize-journal-repository.test.ts
index d00237a4..2f41eabc 100644
--- a/src/core/session/finalize-journal-repository.test.ts
+++ b/src/core/session/finalize-journal-repository.test.ts
@@ -1,4 +1,5 @@
import { createHash } from 'node:crypto'
+import type { RenameFileArtifactIdentity } from '@core/plugin/finalize/artifact-identity'
import type { FinalizeJournalRecord } from '@core/plugin/finalize/finalize-committer'
import { reservationMarker } from '@core/plugin/finalize/reserved-identity'
import Database from 'better-sqlite3'
@@ -16,6 +17,141 @@ describe('SqliteFinalizeJournalRepository', () => {
afterEach(() => db.close())
+ function renameRecord(): FinalizeJournalRecord {
+ const record = makeRecord('rename-only')
+ record.publicationMode = 'move'
+ record.plan.sourcePath = `${record.plan.targetPath}.motrix`
+ record.plan.sourceIdentity = {
+ kind: 'rename-file',
+ size: 1024 * 1024 * 1024,
+ platformFileId: '1:1',
+ mtimeNs: '100',
+ ctimeNs: '200',
+ birthtimeNs: '50',
+ }
+ return record
+ }
+
+ it('round-trips metadata-only identities and the changed stamp after rename', async () => {
+ const repository = new SqliteFinalizeJournalRepository(db, {
+ commitTerminalBoundary: vi.fn(),
+ })
+ const record = renameRecord()
+ await repository.prepare(record)
+ expect(await repository.listRecoverable()).toEqual([record])
+ const installed = {
+ ...(record.plan.sourceIdentity as RenameFileArtifactIdentity),
+ ctimeNs: '300',
+ }
+ await repository.advance(record.journalId, 'target_installed', {
+ targetIdentity: installed,
+ })
+ const restored = { ...installed, ctimeNs: '400' }
+ await repository.checkpoint(record.journalId, {
+ restoredSourceIdentity: restored,
+ })
+ expect(await repository.listRecoverable()).toEqual([
+ {
+ ...record,
+ phase: 'target_installed',
+ targetIdentity: installed,
+ restoredSourceIdentity: restored,
+ },
+ ])
+ })
+
+ it.each([
+ 'copy',
+ 'plugin',
+ 'metadata',
+ 'replacement',
+ 'nonordinary-name',
+ ] as const)(
+ 'rejects metadata-only journal identities outside the rename scope: %s',
+ async (scenario) => {
+ const repository = new SqliteFinalizeJournalRepository(db, {
+ commitTerminalBoundary: vi.fn(),
+ })
+ const record = renameRecord()
+ if (scenario === 'copy') record.publicationMode = 'copy'
+ if (scenario === 'plugin') record.plan.contributors = ['example.test']
+ if (scenario === 'metadata')
+ record.plan.metadataOps = [
+ { pluginId: 'example.test', op: 'set', key: 'note', value: 'value' },
+ ]
+ if (scenario === 'replacement')
+ record.plan.replacement = {
+ pluginId: 'example.test',
+ stagedPath: '/downloads/replacement',
+ identity: fileIdentity('replacement'),
+ }
+ if (scenario === 'nonordinary-name')
+ record.plan.sourcePath = `${record.plan.targetPath}.part`
+ await expect(repository.prepare(record)).rejects.toThrow()
+ expect(await repository.listRecoverable()).toEqual([])
+ }
+ )
+
+ it.each(['size', 'platformFileId', 'mtimeNs', 'birthtimeNs'] as const)(
+ 'rejects a metadata target checkpoint that changes %s',
+ async (field) => {
+ const repository = new SqliteFinalizeJournalRepository(db, {
+ commitTerminalBoundary: vi.fn(),
+ })
+ const record = renameRecord()
+ await repository.prepare(record)
+ const installed = {
+ ...(record.plan.sourceIdentity as RenameFileArtifactIdentity),
+ ctimeNs: '300',
+ }
+ const altered = {
+ ...installed,
+ [field]: field === 'size' ? installed.size + 1 : '999',
+ }
+ await expect(
+ repository.advance(record.journalId, 'target_installed', {
+ targetIdentity: altered,
+ })
+ ).rejects.toThrow()
+ expect((await repository.listRecoverable())[0].phase).toBe('prepared')
+ }
+ )
+
+ it('rejects copy, link and removal intents for metadata-only journals', async () => {
+ const repository = new SqliteFinalizeJournalRepository(db, {
+ commitTerminalBoundary: vi.fn(),
+ })
+ const record = renameRecord()
+ await repository.prepare(record)
+ await expect(
+ repository.checkpoint(record.journalId, { publicationMode: 'copy' })
+ ).rejects.toThrow()
+ await expect(
+ repository.checkpoint(record.journalId, {
+ privateTargetPath: '/downloads/private',
+ })
+ ).rejects.toThrow()
+ await expect(
+ repository.checkpoint(record.journalId, {
+ publicationIntent: {
+ version: 1,
+ method: 'hard_link',
+ sourcePath: record.plan.sourcePath,
+ identity: record.plan.sourceIdentity,
+ },
+ })
+ ).rejects.toThrow()
+ await expect(
+ repository.checkpoint(record.journalId, {
+ removalIntent: {
+ artifactPath: record.plan.sourcePath,
+ quarantinePath: '/downloads/.remove',
+ identity: record.plan.sourceIdentity,
+ },
+ })
+ ).rejects.toThrow()
+ })
+
it('persists a prepared move-to-copy switch and rejects switching after mutation', 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.ts
index e30b2b74..a85a1268 100644
--- a/src/core/session/finalize-journal-repository.ts
+++ b/src/core/session/finalize-journal-repository.ts
@@ -5,7 +5,10 @@ import type {
FinalizeJournalRecord,
FinalizeJournalRepository,
} from '@core/plugin/finalize/finalize-committer'
-import { finalizePathsEquivalent } from '@core/plugin/finalize/finalize-committer'
+import {
+ assertRenameFileJournal,
+ finalizePathsEquivalent,
+} from '@core/plugin/finalize/finalize-committer'
import { isRetryableMoveQuarantine } from '@core/plugin/finalize/finalize-recovery'
import {
assertValidHookPlan,
@@ -111,6 +114,7 @@ export class SqliteFinalizeJournalRepository
| 'privateTargetIdentity'
| 'targetIdentity'
| 'rollbackPath'
+ | 'restoredSourceIdentity'
| 'removalIntent'
| 'publicationIntent'
>
@@ -162,6 +166,7 @@ export class SqliteFinalizeJournalRepository
| 'privateTargetIdentity'
| 'targetIdentity'
| 'rollbackPath'
+ | 'restoredSourceIdentity'
| 'quarantineReason'
>
> = {}
@@ -435,6 +440,7 @@ const isolationSchema = z
.strict()
function validateIntents(record: FinalizeJournalRecord): void {
+ assertRenameFileJournal(record)
if (record.publicationIntent !== undefined) {
const intent = publicationIntentSchema.parse(record.publicationIntent)
if (