Skip to content

all: Prevent directory undeletion on macOS 14.3+ when syncXattrs is enabled (fixes #9371) - #9424

Closed
luckman212 wants to merge 1 commit into
syncthing:mainfrom
luckman212:macos-patch-for-9371
Closed

luckman212 wants to merge 1 commit into
syncthing:mainfrom
luckman212:macos-patch-for-9371

Conversation

@luckman212

Copy link
Copy Markdown
Contributor

Purpose

This is my attempt at fixing (fix may be a strong word, more of a workaround) the "deleted folder snapback" issue described in great lengths at #9371. I have limited experience with the Syncthing codebase, and with Go in general, so this really needs some more 👀 !

I believe the root cause of this "bug" is either:

  • macOS is not permitting the syncthing binary to properly set the folder modification timestamps (even when granted Full Disk Access TCC/PPPC permissions)
    —or—
  • macOS is delaying or queueing writes related to xattrs / timestamps. The timestamp that gets recorded in Syncthing's db is offset by some unknown amount due to this.

The result is the directory inode modtimes in the db become "out of sync" with what later gets read back from the filesystem. This causes hysteresis when a folder is deleted: the receiving side thinks it's been changed and forces a rescan, defers the deletion, which is then picked up by the sender, and the folder is "put back" (sans all contained files however...)

Testing

I tried to take a conservative approach—this only targets macOS for now (not sure if this issue is confirmed to occur on other platforms). I added a bit of debug logging.

Tested on:

  • my 2 Macs (M1 Mini/M2 MacBook Air) both running 14.4 dev beta 3 (23E5196e)
  • Syncthing macOS bundle v1.27.3
  • custom-compiled syncthing binary replacing the one from the app bundle (based on 1.27.4-rc1 + 3e8ec95)
  • Compiled with go1.22.0

In addition to many hours of manual testing, I ran the following simple shell script, which repeatedly creates a folder, dumps some files into it, and then deletes the folder—over and over. Before this patch, the xyzzy folder would almost immediately snap back on Mac-A.

#!/usr/bin/env bash

DELAY=10
TESTDIR="$HOME/Sync/xyzzy"
while true; do
  echo "creating dir: $TESTDIR"
  mkdir -p "$TESTDIR"
  cd "$TESTDIR" || exit 1
  echo "creating files"
  for n in {1..20}; do echo $n >$n.txt; done
  cd
  echo "sleeping ${DELAY}s"
  sleep $DELAY
  echo
  echo "deleting $TESTDIR"
  rm -r "${TESTDIR:?}"
  echo "sleeping ${DELAY}s"
  sleep $DELAY
  echo
done

When run with the STTRACE env var set e.g. STTRACE=all, you will see log entries like the one below when this code path is hit:

[AL47A] 2024/02/18 01:07:37.138658 bep_extensions.go:259: DEBUG: isEquivalent: skipping modtime check due to platform bug

@er-pa

er-pa commented Feb 18, 2024 •

Copy link
Copy Markdown
Member

I'm personally not convinced it's either of the named root issues. As the main issue seems to be, from what I see in logs, that the modification time adjusts right before we want to delete the directory involved on the receiving side -> every time at the same moment it seems, a bit too coincidental. Followed, later on, by a propagation of this directory as deleted: false -> the sending side recreates this directory again.

[MRIW7] 2024/02/17 21:50:13.541092 folder_sendrecv.go:863: DEBUG: sendreceive/aqwsu-knzyf@0x14001084008 Deleting file randomdir/somefile
[MRIW7] 2024/02/17 21:50:13.541174 logfs.go:61: DEBUG: traversessymlink.go:51 basic /Users/ericp/syncthing-test/321 Lstat randomdir {0x140011a6750} <nil>
[MRIW7] 2024/02/17 21:50:13.541209 logfs.go:61: DEBUG: folder_sendrecv.go:2113 basic /Users/ericp/syncthing-test/321 Lstat randomdir/somefile {0x140011a6820} <nil>
[MRIW7] 2024/02/17 21:50:13.541217 events.go:335: DEBUG: log 74 ItemStarted map[action:delete folder:aqwsu-knzyf item:randomdir/somefile type:file]
[MRIW7] 2024/02/17 21:50:13.541257 logfs.go:115: DEBUG: util.go:24 basic /Users/ericp/syncthing-test/321 Stat randomdir {0x140011a68f0} <nil>
[MRIW7] 2024/02/17 21:50:13.541442 logfs.go:97: DEBUG: util.go:59 basic /Users/ericp/syncthing-test/321 Remove randomdir/somefile <nil>
[MRIW7] 2024/02/17 21:50:13.541467 folder_sendrecv.go:553: DEBUG: sendreceive/aqwsu-knzyf@0x14001084008 Deleting dir randomdir
[MRIW7] 2024/02/17 21:50:13.541478 set.go:268: DEBUG: aqwsu-knzyf Get(randomdir)
[MRIW7] 2024/02/17 21:50:13.541547 events.go:335: DEBUG: log 75 ItemFinished map[action:delete error:<nil> folder:aqwsu-knzyf item:randomdir/somefile type:file]
[MRIW7] 2024/02/17 21:50:13.541579 events.go:335: DEBUG: log 76 ItemStarted map[action:delete folder:aqwsu-knzyf item:randomdir type:dir]
[MRIW7] 2024/02/17 21:50:13.541889 logfs.go:61: DEBUG: folder_sendrecv.go:2113 basic /Users/ericp/syncthing-test/321 Lstat randomdir {0x140011a6a90} <nil>
[MRIW7] 2024/02/17 21:50:13.542111 folder_sendrecv.go:1910: DEBUG: sendreceive/aqwsu-knzyf@0x14001084008 new error for randomdir: delete dir: file modified but not rescanned; will try again later

And the walker later on (please note the mod time/inode change time);

[MRIW7] 2024/02/17 21:50:13.547070 walk.go:462: DEBUG: walker/aqwsu-knzyf@0x1400015b550 checking: Directory{Name:"randomdir", Sequence:0, Permissions:0755, ModTime:2024-02-17 21:50:13.541375665 +0100 CET, Version:{[{I6KAH76 1708202982} {MRIW7OK 1708203013}]}, VersionHash:, Deleted:false, Invalid:false, LocalFlags:0x0, NoPermissions:false, Platform:{<nil> <nil> <nil>  <nil> <nil>}, InodeChangeTime:2024-02-17 21:50:13.541375665 +0100 CET}

The modification time of the local dir changed somewhere between the Stat->Delete logic, it could be some external event - or our xattr-handling (perhaps of the child-files) does something tricky to the directories involved.. Not sure how to figure that part out though.

Edit: actually, deleting a file inside a folder also has effect on the folder's mod/inode time. Which, perhaps, we only really care for when syncing xattrs (as folders tend to be a bit of a special case, they usually don't have too much content to keep in sync), just a thought.

@tomasz1986 tomasz1986 changed the title patch to fix #9371 on macOS 14.3+ when xattr sync is enabled all: Prevent directory undeletion on macOS 14.3+ when syncXattrs is enabled (fixes #9371) Feb 18, 2024
@luckman212

luckman212 commented Feb 18, 2024 •

Copy link
Copy Markdown
Contributor Author

Thanks @er-pa. The inode change time of the dir itself getting touched when deleting a child object does seem to correlate with the issue. I don't know why that would only be something new for OS 14.3 though.

I did my best to try to capture low level filesystem events in realtime (most of my notes on that are here) but it didn't lead to anything enlightening.

The workaround proposed here still fits, does it not?

@er-pa

er-pa commented Feb 18, 2024 •

Copy link
Copy Markdown
Member

Well, yes and no. That would mean that it's not a platform bug (just an oversight from our side) and will affect any platform. Why it wasn't detected before is a bit unknown. But I can replicate it with two instances on a single Bookworm host too (non-virtual).

In that case we may just have to conclude that the mod-time and inode-time for directories are relatively useless and we'll just have to rely on detecting differences in either the ownerships or xattrs when figuring out whether they're equal. So practically your approach, just a tiny tweak; a bit more general.

But perhaps a more knowledgeable one can give some input on this as I may oversee something.

(p.s., I didn't really check any code (style/..), just what it intends to solve:))

@luckman212

luckman212 commented Feb 18, 2024 •

Copy link
Copy Markdown
Contributor Author

@er-pa Actual code changes were pretty minimal. But I am definitely interested that you were able to replicate this on stock Debian (no macOS involved).

So, perhaps the platform check should be removed altogether and we simply ignore inode modtime changes on dirs altogether. The xattrs still sync during rescans in my testing, with folder colors/labels/and spotlight metadata comments.

edit: I spun up 2 Debian 12.5.0 VMs and installed Syncthing 1.27.3 on both of them. I then created a sync folder test1 with xattr sync enabled, and ran the test. I was able to easily reproduce the issue (same as @er-pa). It seemed to only occur about 80% of the time, vs 100% on macOS. But it was definitely present.

In light of this finding, I'm inclined to revise the PR so it extends to all platforms, but I'm going to pause here and wait for @calmh or @imsodin to weigh in.

@calmh

calmh commented Feb 19, 2024

Copy link
Copy Markdown
Member

Caring about directory modification time while we are processing deletes is certainly a bug, we should expect it to change all the time without any significance for us.

I don't know whether the same goes for the directory inode change time; intuitively I think it should not change due to deleting a child item, but I also don't think it's well defined in any case...

@calmh calmh self-assigned this Feb 19, 2024
@luckman212

luckman212 commented Feb 20, 2024 •

Copy link
Copy Markdown
Contributor Author

Thanks for looking @calmh. Right, as I understand it, ctime (inode change time) is updated with metadata/permission/ownership changes (and apparently with other changes as well), while mtime (dir mod time) typically updates only when child items are added/renamed/deleted. I just ran some tests on my macOS system, and here are the results:

operation ctime (inode) mtime
copy file into the folder ✅ changed ✅ changed
rename a file inside of folder ✅ changed ✅ changed
delete file from folder ✅ changed ✅ changed
change perms (chmod) ✅ changed ❌ unchanged
change owner (chown) ✅ changed ❌ unchanged
change metadata (kMDItemKeywords) ✅ changed ❌ unchanged
rename the folder ✅ changed ❌ unchanged

I agree then, when processing directory deletes, these metadata should not be considered. Are we on the right track with the PR I submitted here? (if we widen the scope to include other OS'es). If not, would these be the areas to focus on?

// Process in reverse order to delete depth first
for i := range dirDeletions {
select {
case <-f.ctx.Done():
return
default:
}
dir := dirDeletions[len(dirDeletions)-i-1]
l.Debugln(f, "Deleting dir", dir.Name)
f.deleteDir(dir, snap, dbUpdateChan, scanChan)
}

// deleteDir attempts to remove a directory that was deleted on a remote
func (f *sendReceiveFolder) deleteDir(file protocol.FileInfo, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
// Used in the defer closure below, updated by the function body. Take
// care not declare another err.
var err error
f.evLogger.Log(events.ItemStarted, map[string]string{
"folder": f.folderID,
"item": file.Name,
"type": "dir",
"action": "delete",
})
defer func() {
if err != nil {
f.newPullError(file.Name, fmt.Errorf("delete dir: %w", err))
}
f.evLogger.Log(events.ItemFinished, map[string]interface{}{
"folder": f.folderID,
"item": file.Name,
"error": events.Error(err),
"type": "dir",
"action": "delete",
})
}()
cur, hasCur := snap.Get(protocol.LocalDeviceID, file.Name)
if err = f.checkToBeDeleted(file, cur, hasCur, scanChan); err != nil {
if fs.IsNotExist(err) || fs.IsErrCaseConflict(err) {
err = nil
dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteDir}
}
return
}
if err = f.deleteDirOnDisk(file.Name, snap, scanChan); err != nil {
return
}
dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteDir}
}

// deleteDirOnDisk attempts to delete a directory. It checks for files/dirs inside
// the directory and removes them if possible or returns an error if it fails
func (f *sendReceiveFolder) deleteDirOnDisk(dir string, snap *db.Snapshot, scanChan chan<- string) error {
if err := osutil.TraversesSymlink(f.mtimefs, filepath.Dir(dir)); err != nil {
return err
}
if err := f.deleteDirOnDiskHandleChildren(dir, snap, scanChan); err != nil {
return err
}
err := f.inWritableDir(f.mtimefs.Remove, dir)
if err == nil || fs.IsNotExist(err) {
// It was removed or it doesn't exist to start with
return nil
}
if _, serr := f.mtimefs.Lstat(dir); serr != nil && !fs.IsPermission(serr) {
// We get an error just looking at the directory, and it's not a
// permission problem. Lets assume the error is in fact some variant
// of "file does not exist" (possibly expressed as some parent being a
// file and not a directory etc) and that the delete is handled.
return nil
}
return err
}

@anonhostpi

anonhostpi commented Feb 20, 2024 •

Copy link
Copy Markdown

For someone who doesn't know Go (and iexperienced with the codebase), I do have to say I am impressed with your work in both documenting and still trying a solution. Even if the original solution was inadequate, your work has been more thorough than what I would ever expect from any end user.

I have been following the issue, since you reported it, and I am genuinely impressed.

Documenting a problem, trying a fix in a language you don't even write in, several screen recordings, and multiple days of non-stop work for a project you don't even own or maintain. Well done, sir. 👏

@calmh

calmh commented Feb 22, 2024

Copy link
Copy Markdown
Member

I wonder if we should ever care about a metadata difference when deleting something. The behaviour we have now is designed for files, with the intention that a metadata change (modtime, size, etc) may indicate a change to the actual data, and we don't want to delete a file that's been changed and not synced. For directories this isn't a thing, and I don't think changes to things like xattrs should block a delete either, really. Maybe we just need to special case the delete for directories to ignore changes to metadata even when syncing xattrs...

@luckman212

luckman212 commented Feb 22, 2024 •

Copy link
Copy Markdown
Contributor Author

@calmh I'm fiddling around with this. Would something like this work (basically short circuit IgnoreXattrs making it always TRUE if we're comparing a directory)?

if !cf.IsEquivalentOptional(diskFile, protocol.FileInfoComparison{
	ModTimeWindow:   f.modTimeWindow,
	IgnorePerms:     f.IgnorePerms,
	IgnoreBlocks:    true,
	IgnoreFlags:     protocol.LocalAllFlags,
	IgnoreOwnership: !f.SyncOwnership,
	IgnoreXattrs:    info.IsDir() || !f.SyncXattrs,
}) {

edit: never mind that^^

@luckman212

Copy link
Copy Markdown
Contributor Author

@calmh / @er-pa / @imsodin what do you think of #9430 instead as a proposed patch?

@er-pa

er-pa commented Feb 24, 2024 •

Copy link
Copy Markdown
Member

I'll let others decide over the best approach for the fix as it's not something I know a lot about, yet.

However, I did backtrack it to the change which introduced this behaviour, as it may be good to know:);
#9250 (1.27.1-rc.1)

@luckman212

Copy link
Copy Markdown
Contributor Author

Thanks @er-pa for that find. Still surprised at how little attention this is getting—seems the people who've noticed it can be counted on one hand.

Ok then, seems we are waiting for Jakob to weigh in. Regardless, #9430 is more likely to be an acceptable solution, so this PR should probably be closed and the conversation continued over there.

@tomasz1986 tomasz1986 closed this Feb 26, 2024
@tomasz1986

Copy link
Copy Markdown
Member

Regardless, #9430 is more likely to be an acceptable solution, so this PR should probably be closed and the conversation continued over there.

Closed as requested 🙂.

@st-review st-review added the frozen-due-to-age Issues closed and untouched for a long time, together with being locked for discussion label Apr 9, 2025
@syncthing syncthing locked and limited conversation to collaborators Apr 9, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

frozen-due-to-age Issues closed and untouched for a long time, together with being locked for discussion

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants