From aea5cd38635acc33cc164feccd7f96c16e5d43c3 Mon Sep 17 00:00:00 2001 From: pingxin403 <26605276+pingxin403@users.noreply.github.com> Date: Sat, 5 Dec 2026 23:25:20 +0800 Subject: [PATCH] fix: mirrorRemote and preferRemote overwrite newer local files on initial sync During the initial sync, the remote preference strategies (mirrorRemote, preferRemote) selected the container file in the conflict calculation, but the downstream unarchiver still skipped extraction when the local file had a newer mtime because its forceOverride flag was always false. mirrorRemote also deletes local-only files, so this left a partially mirrored directory. Thread the initial sync's force flag into the unarchiver and pass force=true for the initial download of both remote preference strategies. mirrorLocal, preferLocal, preferNewest and keepAll keep protecting local files as before, and later (non-initial) downloads still respect newer local edits. Fixes #3351 Signed-off-by: pingxin403 <26605276+pingxin403@users.noreply.github.com> --- pkg/devspace/sync/downstream.go | 8 +- pkg/devspace/sync/initial.go | 7 +- pkg/devspace/sync/sync_test.go | 290 +++++++++++++++++++++++++------- 3 files changed, 241 insertions(+), 64 deletions(-) diff --git a/pkg/devspace/sync/downstream.go b/pkg/devspace/sync/downstream.go index a0d35a2bbc..61b416a6b1 100644 --- a/pkg/devspace/sync/downstream.go +++ b/pkg/devspace/sync/downstream.go @@ -253,7 +253,7 @@ func (d *downstream) applyChanges(changes []*remote.Change, force bool) error { // Extract downloaded archive if len(download) > 0 { for i := 0; i < syncRetries; i++ { - err := d.initDownload(download) + err := d.initDownload(download, force) if err == nil { break } else if i+1 >= syncRetries { @@ -287,7 +287,7 @@ func (d *downstream) updateDownloadChanges(download []*remote.Change) []*remote. return newChanges } -func (d *downstream) initDownload(download []*remote.Change) error { +func (d *downstream) initDownload(download []*remote.Change, force bool) error { reader, writer := io.Pipe() defer reader.Close() @@ -298,6 +298,10 @@ func (d *downstream) initDownload(download []*remote.Change) error { errorChan <- d.downloadFiles(writer, download) }() + // force also overrides the unarchiver's newer-local-mtime check, so that + // remote preference strategies can overwrite conflicting local files + d.unarchiver.forceOverride = force + // Untaring all downloaded files to the right location // this can be a lengthy process when we downloaded a lot of files err := d.unarchiver.Untar(reader, d.sync.LocalPath) diff --git a/pkg/devspace/sync/initial.go b/pkg/devspace/sync/initial.go index 2f66fef93d..bd8953e3ee 100644 --- a/pkg/devspace/sync/initial.go +++ b/pkg/devspace/sync/initial.go @@ -132,6 +132,11 @@ func (i *initialSyncer) Run(remoteState map[string]*FileInformation, localState // Download local if not mirror local if len(download) > 0 { + // Remote preference strategies resolve conflicts by preferring the container file, + // so a newer local file must be overwritten as well (initial sync only, later + // downloads keep protecting newer local files via the unarchiver's mtime check) + forceDownload := i.o.Strategy == latest.InitialSyncStrategyMirrorRemote || i.o.Strategy == latest.InitialSyncStrategyPreferRemote + if i.o.Strategy == latest.InitialSyncStrategyMirrorLocal { // only apply the ones that match the upstream ignore matcher remoteChanges := make([]*remote.Change, 0, len(download)) @@ -168,7 +173,7 @@ func (i *initialSyncer) Run(remoteState map[string]*FileInformation, localState }) } - err = i.o.ApplyLocal(remoteChanges, false) + err = i.o.ApplyLocal(remoteChanges, forceDownload) if err != nil { return errors.Wrap(err, "apply changes") } diff --git a/pkg/devspace/sync/sync_test.go b/pkg/devspace/sync/sync_test.go index faacf8802a..d2c4487c0f 100644 --- a/pkg/devspace/sync/sync_test.go +++ b/pkg/devspace/sync/sync_test.go @@ -50,13 +50,72 @@ func createTestSyncClient(testLocalPath string, testCases testCaseList) (*Sync, return sync, nil } +// startTestSync starts downstream and upstream servers around the given sync client +func startTestSync(t *testing.T, syncClient *Sync, remote string) { + // Start the downstream server + downClientReader, downClientWriter, _ := os.Pipe() + downServerReader, downServerWriter, _ := os.Pipe() + t.Cleanup(func() { + downClientReader.Close() + downClientWriter.Close() + downServerReader.Close() + downServerWriter.Close() + }) + + // Build exclude paths + excludePaths := []string{} + excludePaths = append(excludePaths, syncClient.Options.ExcludePaths...) + excludePaths = append(excludePaths, syncClient.Options.DownloadExcludePaths...) + + go func() { + err := server.StartDownstreamServer(downServerReader, downClientWriter, &server.DownstreamOptions{ + RemotePath: remote, + ExcludePaths: excludePaths, + ExitOnClose: false, + }) + if err != nil { + panic(err) + } + }() + + // Start downstream client + err := syncClient.InitDownstream(downClientReader, downServerWriter) + if err != nil { + t.Fatal(err) + } + + // Start upstream server + upClientReader, upClientWriter, _ := os.Pipe() + upServerReader, upServerWriter, _ := os.Pipe() + t.Cleanup(func() { + upClientReader.Close() + upClientWriter.Close() + upServerReader.Close() + upServerWriter.Close() + }) + + go func() { + err := server.StartUpstreamServer(upServerReader, upClientWriter, &server.UpstreamOptions{ + UploadPath: remote, + ExludePaths: []string{}, + ExitOnClose: false, + }) + if err != nil { + panic(err) + } + }() + + // Start upstream client + err = syncClient.InitUpstream(upClientReader, upServerWriter) + if err != nil { + t.Fatal(err) + } +} + func TestInitialSync(t *testing.T) { for _, initialSync := range []latest.InitialSyncStrategy{latest.InitialSyncStrategyPreferLocal, latest.InitialSyncStrategyMirrorLocal} { t.Log("InitialSyncStrategy: " + initialSync) remote, local, outside := initTestDirs(t) - defer os.RemoveAll(remote) - defer os.RemoveAll(local) - defer os.RemoveAll(outside) filesToCheck, foldersToCheck := makeBasicTestCases() if initialSync == latest.InitialSyncStrategyMirrorLocal { @@ -76,64 +135,7 @@ func TestInitialSync(t *testing.T) { syncClient.Options.DownstreamLimit = 1024 syncClient.Options.UpstreamLimit = 512 - // Start the downstream server - downClientReader, downClientWriter, _ := os.Pipe() - downServerReader, downServerWriter, _ := os.Pipe() - defer downClientReader.Close() - defer downClientWriter.Close() - defer downServerReader.Close() - defer downServerWriter.Close() - - t.Logf("Exclude paths: %#+v", syncClient.Options.ExcludePaths) - t.Logf("Upload Exclude paths: %#+v", syncClient.Options.UploadExcludePaths) - t.Logf("Download Exclude paths: %#+v", syncClient.Options.DownloadExcludePaths) - - // Build exclude paths - excludePaths := []string{} - excludePaths = append(excludePaths, syncClient.Options.ExcludePaths...) - excludePaths = append(excludePaths, syncClient.Options.DownloadExcludePaths...) - - go func() { - err := server.StartDownstreamServer(downServerReader, downClientWriter, &server.DownstreamOptions{ - RemotePath: remote, - ExcludePaths: excludePaths, - ExitOnClose: false, - }) - if err != nil { - panic(err) - } - }() - - // Start downstream client - err = syncClient.InitDownstream(downClientReader, downServerWriter) - if err != nil { - t.Fatal(err) - } - - // Start upstream server - upClientReader, upClientWriter, _ := os.Pipe() - upServerReader, upServerWriter, _ := os.Pipe() - defer upClientReader.Close() - defer upClientWriter.Close() - defer upServerReader.Close() - defer upServerWriter.Close() - - go func() { - err := server.StartUpstreamServer(upServerReader, upClientWriter, &server.UpstreamOptions{ - UploadPath: remote, - ExludePaths: []string{}, - ExitOnClose: false, - }) - if err != nil { - panic(err) - } - }() - - // Start upstream client - err = syncClient.InitUpstream(upClientReader, upServerWriter) - if err != nil { - t.Fatal(err) - } + startTestSync(t, syncClient, remote) // Create test landscape err = createTestFilesAndFolders(local, remote, outside, filesToCheck, foldersToCheck) @@ -754,3 +756,169 @@ func TestRemoveDirInFileMap(t *testing.T) { t.Fatal("Remove dir in file map failed!") } } + +// TestInitialSyncConflict tests the documented conflict resolution of every initial sync +// strategy when a file exists on both sides with different content, for both mtime orderings. +// Documented semantics (docs/pages/configuration/dev/connections/file-sync.mdx): +// - mirrorLocal / preferLocal: prefer the local file +// - mirrorRemote / preferRemote: prefer the container file, regardless of mtimes +// - preferNewest: prefer the newer file +// - keepAll: keep both, local file stays untouched +func TestInitialSyncConflict(t *testing.T) { + localNewerTime := time.Date(2030, 1, 1, 0, 0, 0, 0, time.UTC) + remoteNewerTime := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) + + const localContent = "local" + const remoteContent = "remote" + + strategies := []latest.InitialSyncStrategy{ + latest.InitialSyncStrategyMirrorLocal, + latest.InitialSyncStrategyPreferLocal, + latest.InitialSyncStrategyMirrorRemote, + latest.InitialSyncStrategyPreferRemote, + latest.InitialSyncStrategyPreferNewest, + latest.InitialSyncStrategyKeepAll, + } + + for _, strategy := range strategies { + for _, tc := range []struct { + name string + localMtime time.Time + remoteMtime time.Time + }{ + {"local_newer", localNewerTime, remoteNewerTime}, + {"remote_newer", remoteNewerTime, localNewerTime}, + } { + t.Run(string(strategy)+"/"+tc.name, func(t *testing.T) { + remote, local, _ := initTestDirs(t) + + localConflict := filepath.Join(local, "conflict.txt") + remoteConflict := filepath.Join(remote, "conflict.txt") + localOnly := filepath.Join(local, "localOnly.txt") + remoteOnly := filepath.Join(remote, "remoteOnly.txt") + + writeTestFileWithMtime(t, localConflict, localContent, tc.localMtime) + writeTestFileWithMtime(t, remoteConflict, remoteContent, tc.remoteMtime) + writeTestFileWithMtime(t, localOnly, localContent, tc.localMtime) + writeTestFileWithMtime(t, remoteOnly, remoteContent, tc.remoteMtime) + + syncClient, err := createTestSyncClient(local, testCaseList{}) + if err != nil { + t.Fatal(err) + } + defer syncClient.Stop(nil) + syncClient.Options.InitialSync = strategy + + startTestSync(t, syncClient, remote) + go syncClient.startUpstream() + + err = syncClient.initialSync(nil, nil) + if err != nil { + t.Fatal(err) + } + + // Which side wins the conflict locally and remotely + preferLocal := strategy == latest.InitialSyncStrategyMirrorLocal || + strategy == latest.InitialSyncStrategyPreferLocal + preferRemote := strategy == latest.InitialSyncStrategyMirrorRemote || + strategy == latest.InitialSyncStrategyPreferRemote + mirrorLocal := strategy == latest.InitialSyncStrategyMirrorLocal + mirrorRemote := strategy == latest.InitialSyncStrategyMirrorRemote + localIsNewer := tc.localMtime.After(tc.remoteMtime) + + var expectedLocalContent, expectedRemoteContent string + switch { + case preferLocal: + expectedLocalContent, expectedRemoteContent = localContent, localContent + case preferRemote: + expectedLocalContent, expectedRemoteContent = remoteContent, remoteContent + case strategy == latest.InitialSyncStrategyPreferNewest: + if localIsNewer { + expectedLocalContent, expectedRemoteContent = localContent, localContent + } else { + expectedLocalContent, expectedRemoteContent = remoteContent, remoteContent + } + default: // keepAll + expectedLocalContent, expectedRemoteContent = localContent, remoteContent + } + + assertTestFileContent(t, localConflict, expectedLocalContent) + + // local-only files are deleted only by mirrorRemote + assertTestFileExistence(t, localOnly, !mirrorRemote) + + // Uploads are applied asynchronously by the upstream, so poll for the remote state + checkTestFileContentEventually(t, remoteConflict, expectedRemoteContent, 10*time.Second) + + // remote-only files are deleted only by mirrorLocal + checkTestFileExistenceEventually(t, filepath.Join(local, "remoteOnly.txt"), !mirrorLocal, 10*time.Second) + checkTestFileExistenceEventually(t, remoteOnly, !mirrorLocal, 10*time.Second) + checkTestFileExistenceEventually(t, filepath.Join(remote, "localOnly.txt"), !mirrorRemote, 10*time.Second) + }) + } + } +} + +func writeTestFileWithMtime(t *testing.T, path string, content string, mtime time.Time) { + t.Helper() + if err := os.WriteFile(path, []byte(content), 0666); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(path, mtime, mtime); err != nil { + t.Fatal(err) + } +} + +func assertTestFileContent(t *testing.T, path string, expected string) { + t.Helper() + content, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if string(content) != expected { + t.Fatalf("unexpected content of %s: expected %q, got %q", path, expected, string(content)) + } +} + +func assertTestFileExistence(t *testing.T, path string, shouldExist bool) { + t.Helper() + _, err := os.Stat(path) + if shouldExist && err != nil { + t.Fatalf("expected %s to exist: %v", path, err) + } else if !shouldExist && err == nil { + t.Fatalf("expected %s to not exist", path) + } +} + +func checkTestFileContentEventually(t *testing.T, path string, expected string, timeout time.Duration) { + t.Helper() + deadline := time.Now().Add(timeout) + for { + content, err := os.ReadFile(path) + if err == nil && string(content) == expected { + return + } + if time.Now().After(deadline) { + if err != nil { + t.Fatalf("expected %s to contain %q, but reading it failed: %v", path, expected, err) + } + t.Fatalf("unexpected content of %s: expected %q, got %q", path, expected, string(content)) + } + time.Sleep(200 * time.Millisecond) + } +} + +func checkTestFileExistenceEventually(t *testing.T, path string, shouldExist bool, timeout time.Duration) { + t.Helper() + deadline := time.Now().Add(timeout) + for { + _, err := os.Stat(path) + if (err == nil) == shouldExist { + return + } + if time.Now().After(deadline) { + t.Fatalf("expected existence of %s to be %v", path, shouldExist) + } + time.Sleep(200 * time.Millisecond) + } +}