Files
magpie/internal/provider/zeroed_1505_test.go
T
yetoneandggbdpq 89271cd4e8 provider, plugin, settings: accounts left all zero by a crash are read from their last good copy, and every state file is flushed before it is renamed in (#1505, Zhangwier)
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>
2026-10-10 22:54:09 +08:00

149 lines
4.8 KiB
Go

package provider
import (
"bytes"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/lastgood"
"github.com/yetone/magpie/internal/steady"
)
// #1505: a Windows machine that went down mid-write left logins.json at
// its full length, 10,783 bytes, every one 0x00, and magpie started with
// no accounts. Its last good generation, kept beside it, is read instead,
// and the user told.
func TestZeroedLoginsReadFromBackup(t *testing.T) {
googleSandbox(t, &fakeGoogle{})
lastgood.Reset()
t.Cleanup(lastgood.Reset)
for _, u := range []string{"a@x.com", "b@x.com", "c@x.com"} {
if err := addGoogleLogin("antigravity", u, "", googleAuth{RefreshToken: "1//" + u, Project: "p"}); err != nil {
t.Fatal(err)
}
}
p := loginsPath()
if _, err := os.Stat(lastgood.Bak(p)); err != nil {
t.Fatalf("no last good generation kept: %v", err)
}
// the crash: the file as Zhangwier found it, and magpie starting anew
if err := os.WriteFile(p, make([]byte, 10783), 0o600); err != nil {
t.Fatal(err)
}
lastLoginsMu.Lock()
lastLogins, loginsKnown = nil, false
lastLoginsMu.Unlock()
users := func() string {
var us []string
for _, l := range readLogins() {
us = append(us, l.User)
}
return strings.Join(us, ",")
}
// the backup lags one write: it holds a and b, the write of c is the
// one the crash took
if got := users(); got != "a@x.com,b@x.com" {
t.Fatalf("a zeroed logins.json read as %q", got)
}
if n := lastgood.Recovered(); len(n) != 1 || n[0].File != "logins.json" || !strings.Contains(n[0].Why, "10783 bytes") {
t.Fatalf("the user isn't told: %+v", n)
}
// the next account added keeps them, and the zeroed file aside
if err := addGoogleLogin("antigravity", "d@x.com", "", googleAuth{RefreshToken: "1//d", Project: "p"}); err != nil {
t.Fatal(err)
}
if got := users(); got != "a@x.com,b@x.com,d@x.com" {
t.Fatalf("after an account added: %q", got)
}
kept, _ := filepath.Glob(p + ".bad-*")
if len(kept) != 1 {
t.Fatalf("the zeroed file not kept aside: %v", kept)
}
if b, _ := os.ReadFile(kept[0]); !bytes.Equal(b, make([]byte, 10783)) {
t.Fatalf("kept %d bytes", len(b))
}
}
// With no backup, a zeroed logins.json is copied aside before an account
// added writes over it.
func TestZeroedLoginsWithoutBackupKeptAside(t *testing.T) {
googleSandbox(t, &fakeGoogle{})
lastgood.Reset()
t.Cleanup(lastgood.Reset)
p := loginsPath()
os.MkdirAll(filepath.Dir(p), 0o700)
os.WriteFile(p, make([]byte, 10783), 0o600)
lastLoginsMu.Lock()
lastLogins, loginsKnown = nil, false
lastLoginsMu.Unlock()
if err := addGoogleLogin("antigravity", "new@x.com", "", googleAuth{RefreshToken: "1//n", Project: "p"}); err != nil {
t.Fatal(err)
}
if kept, _ := filepath.Glob(p + ".bad-*"); len(kept) != 1 {
t.Fatalf("the zeroed file not kept aside: %v", kept)
}
if _, err := os.Stat(lastgood.Bak(p)); err == nil {
t.Fatal("a zeroed file kept as the last good generation")
}
}
// migrations.json says which subscriptions moved onto their plugins; one
// zeroed by the crash is not "nothing moved".
func TestZeroedMigrationsReadFromBackup(t *testing.T) {
googleSandbox(t, &fakeGoogle{})
lastgood.Reset()
t.Cleanup(lastgood.Reset)
for _, id := range []string{"zed", "kiro"} {
if err := setMigration(id, func(m *Migration) { m.State = MovePlugin }); err != nil {
t.Fatal(err)
}
}
p := migrationsPath()
os.WriteFile(p, make([]byte, 4096), 0o600)
if !Moved("zed") {
t.Fatal("a zeroed migrations.json read as zed not moved")
}
if len(lastgood.Recovered()) != 1 {
t.Fatalf("not noted: %+v", lastgood.Recovered())
}
}
// providers.json zeroed: its providers are its last good generation's.
func TestZeroedProvidersReadFromBackup(t *testing.T) {
providerFileHome(t)
lastgood.Reset()
t.Cleanup(lastgood.Reset)
writeProviderFile(t, originalProviderFile)
if err := Save(Provider{ID: "new", Name: "New", Chat: "https://new.example.invalid/v1", Key: "synthetic-new"}); err != nil {
t.Fatal(err)
}
os.WriteFile(Path(), make([]byte, 2048), 0o600)
if err := FileError(); err != nil {
t.Fatalf("a zeroed providers.json with a backup: %v", err)
}
ps := load().Providers
if len(ps) != 1 || ps[0].ID != "original" {
t.Fatalf("providers = %+v, want the backup's", ps)
}
}
// writePrivate, which writes logins.json, migrations.json and
// providers.json, flushes the new file before the rename; one that fails
// to flush leaves the old file.
func TestWritePrivateSyncsBeforeRename(t *testing.T) {
p := filepath.Join(t.TempDir(), "logins.json")
os.WriteFile(p, []byte(`["old"]`), 0o600)
defer func() { steady.Sync = (*os.File).Sync }()
steady.Sync = func(*os.File) error { return errors.New("the disk went away") }
if err := writePrivate(p, []byte(`["new"]`)); err == nil {
t.Fatal("written without a flush")
}
if b, _ := os.ReadFile(p); string(b) != `["old"]` {
t.Fatalf("a failed flush left %q", b)
}
}