This one is about a small piece of a reading app of mine, which moves some books’ files out of the folder the Files app can see and into a private folder on the same storage (the app’s local container, or its iCloud container). Most of the time that’s a plain coordinated move, but sometimes the private folder already holds a copy with the same bytes, and then there’s nothing to move, so the app should just delete the copy in the visible folder. That sounds like the easiest case of the whole feature, and it’s the one we got wrong twice before it was right, so I’m writing down what the final version looks like and why.
Compare, then delete, is a race
The first version did what you’d probably write too. Hash both files, take a metadata snapshot of each before and after hashing, and if everything matches, delete the shelf copy (that’s what the app calls the copy in the visible folder). To make the delete safe it went through NSFileCoordinator, renamed the shelf file into a scratch folder in a coordinated block, and deleted the scratch file later, with a sweep on startup to clean up anything a crash left there.
The problem is that the files aren’t only ours. The visible folder is visible because the user can open the book from the Files app, and an app that edits the file in place does an ordinary save, and on iCloud the sync daemon can replace or remove either copy whenever a change arrives from another device. So the sequence “hash, compare, then later delete” has a gap between the compare and the delete, and in that gap the shelf file can get new bytes, or the private copy can disappear. If either happens, we delete the only current copy of the user’s file. Two reviewers on the pull request found that from reading the code (it never shipped and nothing was lost), each from a different direction, and the shared cause was that the coordinated block only covered the shelf and scratch URLs. It never held the copy we were keeping, and it never checked that the shelf file was still the version we had compared.
The first fix re-checked both files at the rename into scratch. That’s better, but reading NSFilePresenter.h again showed that it still left a gap, because a file presenter follows a coordinated move. When we rename the shelf file into scratch, any presenter on it gets presentedItemDidMoveToURL: with the scratch URL, updates its presentedItemURL, and can save newer bytes there before our cleanup runs. And the startup sweep, which deletes scratch files by name, has no proof at all of what bytes it’s removing. So the scratch folder was moving the race somewhere else, not removing it, and we dropped it.
Coordinate both files, re-check inside the block
What holds up is to put both files into one coordinated operation, with a deleting intent on the file we remove and a metadata-reading intent on the file we keep, and do the last check inside the accessor, right before the unlink:
func unlink(at source: URL, keeping survivor: URL,
validate: @escaping (URL, URL) throws -> Void) async throws {
let intents = [
NSFileAccessIntent.writingIntent(with: source, options: .forDeleting),
NSFileAccessIntent.readingIntent(with: survivor, options: .immediatelyAvailableMetadataOnly),
]
try await coordinate(intents) { urls in
try validate(urls[0], urls[1])
guard Darwin.unlink(urls[0].path) == 0 else {
throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno))
}
}
}
The validate closure resolves both paths again and compares each file’s current version with the one we recorded when we hashed it. If anything is different, missing, or can’t be read, it throws, and both files stay where they are. The coordinator makes other coordinated writers wait while we’re in the block, so a save from the Files app or a sync write lands either before the check (and the check fails) or after the unlink (and there’s nothing left to overwrite). Since the shelf entry is unlinked directly, there’s no scratch file, no move for a presenter to follow, and nothing for a startup sweep to reap.
The long part, hashing the bytes, still happens outside coordination. Holding a coordinated read on a book while hashing hundreds of megabytes would block the reader and every sync write for that long. The block only has to answer “is this still the version I hashed?”, which is cheap.
For iCloud there’s one more thing to check, and it goes before coordination starts. The kept copy has to show that its current version has finished uploading, otherwise we could delete the shelf copy that’s already in the account and keep a private copy that only exists on this device. If the upload evidence isn’t there, we skip the delete and try again on a later pass.
Which version stamp to compare
The obvious stamp is size plus modification date, and it’s what Apple’s own header suggests for a presenter that wants to know whether it should re-read a file. It doesn’t work here, because a save can keep the size the same, and anything can set the modification date back (FileManager.setAttributes will do it in one line, and so will tools that preserve timestamps). We have a test that does exactly that, writing different bytes of the same size to the shelf file and resetting its modification date between our hash and our delete, and the size-and-date check would have let the delete go through.
What we ended up comparing is the device, the inode, the size, and the generation count from getattrlist, all read through one open descriptor:
let fd = open(url.path, O_EVTONLY | O_NONBLOCK | O_NOFOLLOW | O_CLOEXEC)
guard fd >= 0 else { return nil }
var info = stat()
guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG else { return nil }
var request = attrlist()
request.bitmapcount = UInt16(ATTR_BIT_MAP_COUNT)
request.commonattr = attrgroup_t(ATTR_CMN_GEN_COUNT)
var result = (length: UInt32(0), generation: UInt32(0))
guard fgetattrlist(fd, &request, &result, MemoryLayout.size(ofValue: result),
UInt32(FSOPT_ATTR_CMN_EXTENDED)) == 0,
result.generation != 0 else { return nil }
// keep fd open until the delete is done
let stamp = (info.st_dev, info.st_ino, result.generation, info.st_size)
The getattrlist(2) man page describes ATTR_CMN_GEN_COUNT as a count of how many times the object’s data was modified, which can be compared with an earlier value for the same object, and an unchanged count means the data is identical. The “same object” part is what the device and inode are for, and the open descriptor is what makes them trustworthy, because the filesystem can’t reuse an inode number while something still has the file open. Without it, a file deleted and recreated between our two reads could, in theory, come back with the same inode and a fresh count. O_EVTONLY opens the file only for event notifications, so the descriptor doesn’t count as the file being in use for things like unmounting, and O_NOFOLLOW keeps a symlink from standing in for the real file.
A generation count of 0 proves nothing. The man page says 0 is invalid, and that it’s what you get while the file is memory-mapped, which is exactly when someone might be writing to it. So a 0 counts as “can’t verify”, and we keep both files.
The same stamp covers the other direction too. A second test replaces the private copy atomically (a new inode at the same path) between hash and delete, and the delete refuses, because the device and inode no longer match the version we hashed. We also checked that both tests can fail, by disabling each of the two final version checks in turn and watching the matching test go red.
Summary
If a file can be written by anything other than your own code, “check, then act” isn’t safe just because the act goes through NSFileCoordinator. The coordinated block has to hold every file the decision depends on, including the one you’re keeping, and it has to re-check that each is still the exact version you verified, using something that changes when the bytes change (device, inode, getattrlist generation count, with a descriptor held open), not size and modification date. And don’t move a file somewhere temporary to delete it later, because a coordinated move is something presenters follow, so the file is just as exposed in the scratch folder as it was before, and a cleanup that deletes by name has no idea what it’s deleting.