Files
magpie/internal/update/install_rollback_windows_test.go
T
yetone 40dee51751 update: on Windows a download an antivirus holds is waited for up to 30s, and a restart tried again doesn't trial-start it again (白菜 on Discord)
白菜 (Discord #general, 10-19): with magpie on the Desktop, every click
on Update says it is restarting and then offers the update again;
clicking again never gets it in, only a fresh download from the site
does.

Cause, as far as could be shown: the install starts the download
suspended first (canStart, #894). An antivirus that checks a program as
it starts holds the file a while after, and the move into place gave up
after asideWaits' ~3s (#2272's fix). The swap failed, the old exe was
put back, the state stayed ready and the pill said 更新失败, with the
reason only in its tooltip. A click again ran the trial start again, so
the antivirus held the same file again and it failed the same way every
time.

Change:
- moveIn and moveAside go on trying, at the last pause (1.5s), while
  Windows says the file is held open (errors 32/33), up to heldFor (30s)
  from the first try. Other errors still stop after the short pauses.
- InstallBinaryAside trial-starts a download once: the same path, size
  and mtime that passed isn't started again on a retry. A new download
  is.
- A download still held after that says so ("another program still has
  the download open (often an antivirus checking it): let magpie through
  it…"), without the paths, in the version row and the pill's tooltip.
  It still unwraps to the *os.LinkError and the sharing violation.

Tests:
- TestMoveAsideWaitsOutALongHold (all OSes): 10 held tries then success.
  A permission error still stops at 4.
- TestInstallBinaryWaitsOutALongHold (Windows): a real handle holds the
  download for 600ms against 2 short pauses.
- TestInstallBinaryTrialsADownloadOnce (Windows): one trial for a retried
  download, a second for a new one, and the new error text.
- Existing tests that hold a file for good set heldFor to 0.

What was run:
- Broken by hand (no wait past asideWaits, trial on every try): all
  three new tests red on the Windows box. TestMoveAsideWaitsOutALongHold
  is red on macOS too. Restored: green.
- Windows box (10.0.26200, Defender on), cross-compiled update.test.exe
  in a sandbox USERPROFILE/APPDATA/TEMP: the whole internal/update
  package PASS (41 tests).
- Real GUI on the box: a production build (v0.1.9000) at
  C:\Users\yeton\Desktop\magpie-windows-amd64.exe, a sandbox home, a
  local feed offering v0.1.9001. The .new was held open from PowerShell
  (FileShare Read) for 12s, then POST /api/update/install {when:now}:
  - origin/main's build: install failed, "rename … being used by another
    process", state ready, old process ran on;
  - this build: the new version started 1s after the hold was let go,
    and the Desktop exe's hash is 9001's.
- The same setup without a hold, origin/main's build, worked: plain
  Desktop, and a Desktop folder named 白菜 测试 with "(1)" in the exe
  name. A non-ASCII path or the Desktop alone is not the cause.
- gofmt clean. go vet ./... clean for darwin, linux -tags nogui and
  windows.
- HOME=<sandbox> go test -timeout 45m ./... at load ~260-290: every
  package ok except these.
  - internal/agent and internal/gateway timed out at 45m. Already filed
    as #2544 and #2870.
  - internal/gui's TestSetAnswersWhileDevinAndProvidersHang (19.8s set
    under load) is filed as #1375. Rerun alone with the update, restart,
    install and relaunch tests: ok.
  - internal/update was rerun separately, because its source was swapped
    to origin/main's for ~1 min mid-run to build the comparison exe: ok.

Not tried:
- A real third-party antivirus (360, Huorong). The hold is injected. The
  user's version, antivirus and exact error are still unknown, and were
  asked for on Discord.
- A OneDrive-redirected Desktop.
2026-10-20 01:16:38 +08:00

151 lines
4.6 KiB
Go

package update
import (
"errors"
"os"
"path/filepath"
"strings"
"sync"
"syscall"
"testing"
"time"
)
func rollbackFiles(t *testing.T) (string, string) {
t.Helper()
exe := filepath.Join(t.TempDir(), "magpie.exe")
staged := exe + ".new"
for path, content := range map[string]string{exe: "old version", staged: "new version"} {
if err := os.WriteFile(path, []byte(content), 0o755); err != nil {
t.Fatal(err)
}
}
return exe, staged
}
// shortWaits has moveIn and moveAside give up on a file held for good
// at once.
func shortWaits(t *testing.T) {
was, held := asideWaits, heldFor
asideWaits, heldFor = []time.Duration{time.Millisecond}, 0
t.Cleanup(func() { asideWaits, heldFor = was, held })
}
func holdForRollbackTest(t *testing.T, path string) func() {
t.Helper()
h := holdOpen(t, path)
close := sync.OnceFunc(func() {
if err := syscall.CloseHandle(h); err != nil {
t.Error("close held file:", err)
}
})
t.Cleanup(close)
return close
}
func wantInstallFile(t *testing.T, path, content string) {
t.Helper()
if got, err := os.ReadFile(path); err != nil || string(got) != content {
t.Errorf("%s = %q (%v), want %q", filepath.Base(path), got, err, content)
}
}
// A scanner holding the download must not leave the installed path missing.
// An earlier update's held .old means the actual backup is .old-2 instead.
func TestInstallBinaryRestoresAfterStagedRenameFails(t *testing.T) {
for _, heldOld := range []bool{false, true} {
name := "first update"
if heldOld {
name = "earlier old still held"
}
t.Run(name, func(t *testing.T) {
shortWaits(t)
exe, staged := rollbackFiles(t)
aside := exe + ".old"
if heldOld {
if err := os.WriteFile(aside, []byte("earlier version"), 0o755); err != nil {
t.Fatal(err)
}
holdForRollbackTest(t, aside)
if err := os.Remove(aside); !errors.Is(err, errSharingViolation) {
t.Fatalf("fixture: removing held .old = %v, want sharing violation", err)
}
aside = exe + ".old-2"
}
closeStaged := holdForRollbackTest(t, staged)
if err := os.Rename(staged, staged+".probe"); !errors.Is(err, errSharingViolation) {
t.Fatalf("fixture: renaming held download = %v, want sharing violation", err)
}
err := InstallBinary(staged, exe)
var renameErr *os.LinkError
if !errors.Is(err, errSharingViolation) || !errors.As(err, &renameErr) || renameErr.Old != staged || renameErr.New != exe {
t.Fatalf("InstallBinary = %v, want held staged-to-exe rename failure", err)
}
wantInstallFile(t, exe, "old version")
wantInstallFile(t, staged, "new version")
if _, err := os.Stat(aside); !os.IsNotExist(err) {
t.Errorf("restored backup remains at %s: %v", filepath.Base(aside), err)
}
if heldOld {
wantInstallFile(t, exe+".old", "earlier version")
}
closeStaged()
if err := InstallBinary(staged, exe); err != nil {
t.Fatal("retry after the scanner closes:", err)
}
wantInstallFile(t, exe, "new version")
wantInstallFile(t, aside, "old version")
if _, err := os.Stat(staged); !os.IsNotExist(err) {
t.Errorf("download remains after successful retry: %v", err)
}
if heldOld {
wantInstallFile(t, exe+".old", "earlier version")
}
})
}
}
// If a scanner takes the old file just after it moves aside, restoration
// can fail too. Report both failures and keep both versions for recovery.
func TestInstallBinaryReportsFailedRestore(t *testing.T) {
shortWaits(t)
exe, staged := rollbackFiles(t)
holdForRollbackTest(t, staged)
rename := renameFile
t.Cleanup(func() { renameFile = rename })
var aside string
renameFile = func(from, to string) error {
err := os.Rename(from, to)
if err == nil && from == exe {
aside = to
holdForRollbackTest(t, aside)
}
return err
}
err := InstallBinary(staged, exe)
if err == nil || aside == "" {
t.Fatalf("fixture did not reach the second rename: %v, backup %q", err, aside)
}
wantInstallFile(t, aside, "old version")
wantInstallFile(t, staged, "new version")
if !strings.Contains(err.Error(), "restore") {
t.Errorf("failure does not explain that restoring the executable failed: %v", err)
}
var both interface{ Unwrap() []error }
if !errors.As(err, &both) {
t.Fatalf("failure does not retain both causes: %v", err)
}
var installFailed, restoreFailed bool
for _, cause := range both.Unwrap() {
var linkErr *os.LinkError
if errors.As(cause, &linkErr) && errors.Is(cause, errSharingViolation) {
installFailed = installFailed || linkErr.Old == staged && linkErr.New == exe
restoreFailed = restoreFailed || linkErr.Old == aside && linkErr.New == exe
}
}
if !installFailed || !restoreFailed {
t.Errorf("missing typed install/restore failure: %v", err)
}
}