Zhangwier's Windows machine went down hard, and logins.json (10783 bytes)
and plugin-auth.json (29926 bytes) came back at full length with every byte
0x00. Every account was gone. The rename had reached the disk before the
data. magpie then read "no accounts", and its next write would have made
that final.
What changed:
- Flushed before rename: steady.WriteFile writes a temp file, fsyncs it,
then renames it in. A failed write or flush removes the temp file and
leaves the old file as it was. edit.WriteAtomic, Kiro's writer, the
Codex session rewrite and the plugin host's writeDurable (host.js)
flush the same way. So do writePrivate (providers, logins, migrations),
settings, profiles, plugins.json, plugin-auth.json and mcp-signins.json.
- A last good generation: before each write, lastgood.Keep keeps the
valid file there as <file>.bak. A file that isn't valid is copied aside
as <file>.bad-<time>, with -2, -3 when two land in one second (O_EXCL),
and is never overwritten before that copy exists. The .bak lags one
write behind on purpose, since a crash zeroes the latest write.
- A failed read is unknown, never empty. On a cold start, logins.json,
providers.json, migrations.json, settings.json, profiles.json,
plugins.json, plugin-auth.json (Go and the host) and mcp-signins.json
are read from their .bak when they don't read. The recovery is logged
and listed in /api/state's recovered, and the window says it once in
every language. With no good .bak, a sign-out leaves plugin-auth.json
and mcp-signins.json as they are (the host's changeAuth no longer
writes {} over them). magpie's own sign-out returns the error, and a
sign-in copies the bad file aside before writing.
- caller-keys.json is flushed but never read from a .bak. A key revoked
in the last write would come back, so a store that doesn't read still
refuses every key, as its tests require.
ggbdpq's patch (f230bcae) is where the fsync-before-rename in
writePrivate, writeWhole and writeAuth came from. This change puts it in
one shared helper and reaches every other writer of magpie's state. The
JS write cleans up its temp file. The .bak recovery, the .bad copies and
the GUI notice are added here.
What was run:
- New tests, built from the literal case (10783 and 29926 zero bytes):
- internal/lastgood
- provider: TestZeroedLogins*, TestZeroedMigrations*,
TestZeroedProviders*, TestWritePrivateSyncsBeforeRename
- plugin: TestZeroedPluginAuth* against the real bun host,
TestPluginAuthSyncedBeforeRename with a plugin that makes fsync fail,
TestZeroedPluginList*
- TestZeroedSettings*, TestZeroedProfiles*, TestZeroedMCPSignIns*
- steady TestWriteFileSyncsBeforeRename, edit
TestWriteAtomicSyncsBeforeRename
- gui recovered-file.test.cjs (en/zh/zh-TW/ja/de, Chromium and WebKit)
- Broken by hand, each going red:
- Without the sync: the steady, edit, writePrivate and host fsync tests.
- Without the .bak fallback: every TestZeroed* test.
- The old changeAuth writes "{}\n" over the zeros.
- The old readLogins default.
- KeepBad without suffixes fails the one-second test.
- Without recoveredOnce, the GUI test fails 5/5.
- macOS: go test -tags nogui ./... in a sandbox HOME. The only failures
were the two access tests (then fixed by not recovering caller keys) and
TestProvidersCmdSaysUnreadable, which now removes the .bak to test the
no-backup case. Both packages were rerun and pass. gofmt -l prints
nothing. go vet, and GOOS=linux and GOOS=windows go vet -tags nogui, are
clean on the touched packages.
- GUI: recovered-file, whats-new, click-scroll, gui-de, gui-ja,
gui-zh-tw and i18n-keys pass.
- Windows box (cross-compiled test exes, sandboxed USERPROFILE/APPDATA):
lastgood, steady, provider, plugin (real bun host), settings, mcpauth,
edit and access pass. In profile, TestProfileSwitchesModelList and
TestOldProfileKeepsModelList fail the same on origin/main (filed as
#1517).
Reported-by: Zhangwier
Co-authored-by: ggbdpq <ggbdpq@gmail.com>
134 lines
3.7 KiB
Go
134 lines
3.7 KiB
Go
// Package steady reads and replaces files that another process may be
|
|
// replacing at that moment. On Windows a file being renamed over refuses
|
|
// to open, and one held open refuses to be renamed over, both for a
|
|
// moment ("Access is denied"): read as none, a file of accounts is no
|
|
// accounts, and the next write leaves them out. A file being renamed over
|
|
// is also, for a moment (two milliseconds seen), not there at all, to
|
|
// another process or thread: Stat and ReadThere wait that out for a file
|
|
// that was there. Elsewhere a rename is atomic and these are os.Stat,
|
|
// os.ReadFile and os.Rename.
|
|
package steady
|
|
|
|
import (
|
|
"errors"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"runtime"
|
|
"time"
|
|
)
|
|
|
|
// tries and pause bound the wait to half a second: what holds the file is
|
|
// another read or rename, done in milliseconds.
|
|
const (
|
|
tries = 50
|
|
pause = 10 * time.Millisecond
|
|
)
|
|
|
|
// goneTries and gonePause bound the wait on a file not there to 15ms or
|
|
// so: the moment a rename over it leaves is a couple of milliseconds, and
|
|
// a file that is really not there is waited on that long.
|
|
const (
|
|
goneTries = 15
|
|
gonePause = time.Millisecond
|
|
)
|
|
|
|
// windows is whether files behave as Windows' do; a test sets it.
|
|
var windows = runtime.GOOS == "windows"
|
|
|
|
// stat and readFile are os.Stat and os.ReadFile; a test stands in for them.
|
|
var (
|
|
stat = os.Stat
|
|
readFile = os.ReadFile
|
|
)
|
|
|
|
func retry(f func() error) error {
|
|
err := f()
|
|
for i := 0; err != nil && windows && !errors.Is(err, fs.ErrNotExist) && i < tries; i++ {
|
|
time.Sleep(pause)
|
|
err = f()
|
|
}
|
|
return err
|
|
}
|
|
|
|
// retryGone is retry, waiting out a moment of the file not there too.
|
|
func retryGone(f func() error) error {
|
|
err := retry(f)
|
|
for i := 0; err != nil && windows && errors.Is(err, fs.ErrNotExist) && i < goneTries; i++ {
|
|
time.Sleep(gonePause)
|
|
err = retry(f)
|
|
}
|
|
return err
|
|
}
|
|
|
|
// Stat is os.Stat of a file that was there: one being replaced is waited
|
|
// for, so it isn't taken for gone. A file not there costs the wait, so a
|
|
// caller asking again remembers it gone (filememo does).
|
|
func Stat(p string) (fs.FileInfo, error) {
|
|
var fi fs.FileInfo
|
|
err := retryGone(func() (err error) {
|
|
fi, err = stat(p)
|
|
return err
|
|
})
|
|
return fi, err
|
|
}
|
|
|
|
// ReadThere is ReadFile of a file just found there (Stat): not there now is
|
|
// it being replaced, waited out.
|
|
func ReadThere(p string) ([]byte, error) {
|
|
var b []byte
|
|
err := retryGone(func() (err error) {
|
|
b, err = readFile(p)
|
|
return err
|
|
})
|
|
return b, err
|
|
}
|
|
|
|
// ReadFile is os.ReadFile, waiting out a file being replaced.
|
|
func ReadFile(p string) ([]byte, error) {
|
|
var b []byte
|
|
err := retry(func() (err error) {
|
|
b, err = readFile(p)
|
|
return err
|
|
})
|
|
return b, err
|
|
}
|
|
|
|
// Rename is os.Rename, waiting out a reader holding newpath open.
|
|
func Rename(oldpath, newpath string) error {
|
|
return retry(func() error { return os.Rename(oldpath, newpath) })
|
|
}
|
|
|
|
// Sync is (*os.File).Sync; a test stands in for it to make a flush fail.
|
|
var Sync = (*os.File).Sync
|
|
|
|
// WriteFile replaces p with b, mode perm, through a temp file beside it
|
|
// that is flushed to the disk before it is renamed over p. A rename reaches
|
|
// the disk on its own schedule and the data behind it later: a Windows
|
|
// machine that went down between the two left logins.json and
|
|
// plugin-auth.json at their full length with every byte zero (#1505). A
|
|
// write or flush that fails removes the temp file and leaves p as it was.
|
|
func WriteFile(p string, b []byte, perm fs.FileMode) error {
|
|
tmp, err := os.CreateTemp(filepath.Dir(p), "."+filepath.Base(p)+".*")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = tmp.Write(b)
|
|
if err == nil {
|
|
err = tmp.Chmod(perm)
|
|
}
|
|
if err == nil {
|
|
err = Sync(tmp)
|
|
}
|
|
if cerr := tmp.Close(); err == nil {
|
|
err = cerr
|
|
}
|
|
if err == nil {
|
|
err = Rename(tmp.Name(), p)
|
|
}
|
|
if err != nil {
|
|
os.Remove(tmp.Name())
|
|
}
|
|
return err
|
|
}
|