Files
magpie/internal/pii/main_test.go
T
yetone ca87ae9c59 update: an x64 magpie emulated on Windows on Arm updates to the arm64 build (EV_John_Liu on X)
EV_John_Liu on X: "能不能出个windows on arm的版本啊…看到magpie是转译的".
magpie ships magpie-windows-arm64.exe and magpie-cli-windows-arm64.exe,
and the site's Windows button offers it on Arm, but an x64 install on an
Arm64 computer fetched the x64 build on every update and stayed emulated.
update's arch() swapped only an Intel Mac under Rosetta.

- internal/winarm: Emulated() asks IsWow64Process2 (x/sys/windows) once;
  an amd64 build whose nativeMachine is IMAGE_FILE_MACHINE_ARM64 runs
  emulated. A failed call (no IsWow64Process2 before Windows 10 1709)
  means not emulated. false off Windows.
- update: arch() gives arm64 for windows/amd64 when emulated, so
  BinaryAsset picks magpie-windows-arm64.exe (GUI) and
  magpie-cli-windows-arm64.exe (CLI). The swap is the x64 one: canStart
  starts the downloaded exe (it runs natively there), the running exe is
  moved aside, the arm64 one renamed in under the same name, and
  magpie.com is rewritten from the new app's own launcher.
- pii (sibling found on the way): pf-serve has no windows-arm64 build.
  After the switch an arm64 magpie looked for a windows-arm64 pf-serve,
  found none, and left Privacy Filter / AstrLink Guard "not downloaded"
  while on. target() now maps windows-arm64 to the x64 pf-serve Windows 11
  runs emulated; candidates() runs it on the CPU (the x64
  pf-serve-vulkan has no x64 Vulkan driver there), then pf-serve-base
  for an emulation without AVX2. The guard's status says emulated
  (Status.Emulated), and its row reads "On, slowly under x64 emulation:
  the next update installs magpie for Arm" in all five languages, like
  the Rosetta line. app.js's and the core's script budgets grow by its
  66 bytes.
- gui feedback: the diagnostics block's Arch line says
  "amd64 (emulated on arm64)" / "amd64 (under Rosetta on arm64)".

Checked, not changed:
- site/public/index.html: the Windows main button already turns to
  /download/windows-arm64 when userAgentData's architecture is "arm".
  Run in Playwright Chromium and WebKit with a Windows Edge UA and
  injected userAgentData: arm -> windows-arm64; x86 and no
  userAgentData -> windows-amd64.
- telemetry (stats "arch") sends the build's GOARCH; left so, since what
  is sent and the privacy text stay as they are. After the update it is
  arm64 by itself.
- rtk: an arm64 magpie no longer upgrades a standalone x64 rtk.exe
  (rtkArch == "amd64" only), filed as #6896.
- claudecode (win32-arm64) and Bun (windows-aarch64) downloads already
  have arm64 builds.

Run (worktree at origin/main 17da22414):
- mote: go test -count=1 ./internal/winarm ./internal/update
  ./internal/pii ok; ./internal/gui -run Feedback ok.
- mote: go vet ./... ok; GOOS=linux go vet -tags nogui ./... ok;
  GOOS=windows go vet ./... ok; GOOS=windows GOARCH=arm64 go vet of
  winarm, update, pii, gui ok; darwin, windows and linux builds ok;
  gofmt -l clean.
- mote: node --test privacy-model.test.cjs (Chromium and WebKit, five
  languages, two widths) ok; i18n-keys' "a plugin's words are its own"
  is red at this base on claude_image_budget_test.go's ", with an
  image", already #6877.
- xiaomi-gpu (x64 Windows 11, real IsWow64Process2 saying not
  emulated): win-run go test ./internal/winarm, ./internal/update -run
  'WindowsOnArm|Rosetta|Asset|InstallBinary', ./internal/pii -run
  'ArmWindows|GuardNow|Base', ./internal/gui -run Feedback ok.
- magpie-desktop (WSL2): winarm, update, pii ok; gui -tags nogui -run
  Feedback ok.
- mote: go test -count=1 -tags nogui -timeout 45m ./... : every
  package ok but internal/gui's TestCoreScriptBudget (app.js 66 bytes
  over: the new pmSub line). The budgets are raised by those 66 with
  why (pmSub draws every Privacy row, no lazy page to move it to);
  internal/gui then ok in full.
- mote: gui-de, gui-ja, gui-zh-tw, i18n-en-no-cjk and the three other
  privacy-*.test.cjs, in Chromium and WebKit: 28 of 28 each. Not the
  whole GUI suite: the change is one string in one row, no API,
  selector, CSS or layout.

Broken by hand (each red, then restored):
- arch() without the windows clause: TestWindowsOnArmUpdatesToArm64
  (BinaryAsset magpie-windows-amd64.exe) and
  TestWindowsOnArmInstallsArm64Exe (magpie.exe still "2.0 for x64").
- pii target() without the mapping: TestArmWindowsRunsX64Serve
  (target windows-arm64, Supported false); candidates() without the
  Arm branch: its subtests start pf-serve-vulkan.
- Status without Emulated: TestGuardNowSaysEmulated.
- archNote without the emulated case: TestFeedbackArchSaysTranslated.
- app.js without the emulated line: privacy-model's "AstrLink Guard
  says what runs it" red in every language.

Not tried: real Windows on ARM (no such machine); detection is injected
in the tests, and the real call was only seen saying "not emulated" on
x64 Windows.
2026-11-17 04:29:02 +08:00

280 lines
8.7 KiB
Go

package pii
import (
"bufio"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/testenv"
)
// The tests run in a home of their own; the test binary started again
// with fakeVar set is a stand-in pf-serve (fakeServe).
func TestMain(m *testing.M) {
if mode := os.Getenv(fakeVar); mode != "" {
fakeServe(mode)
return
}
testenv.Main(m)
}
const (
fakeVar = "PII_FAKE_SERVE"
// fakeLog is a file the stand-in appends what it did to, a line each
fakeLog = "PII_FAKE_LOG"
)
// fakeServe speaks pf-serve's protocol and finds each "Alice" as a
// person. mode says how else it behaves:
//
// ok as pf-serve does
// gpudies on the GPU, ends at its first request
// hang never answers a request
// loadhang never says the model is loaded
// slow answers each request after 300ms
// noload says it couldn't load the model
// badmodel says it couldn't read the model's file, by the name
// it was given
// novulkan as pf-serve-vulkan, says Vulkan is missing; else ok
// noavx2 as pf-serve, ends at once as on a CPU (or an emulation)
// without AVX2, SIGILL; else ok
// gpuloadhang on the GPU, never says the model is loaded; else ok
// asserts fails a ggml assert at its first request
// gpuhang on the GPU, never answers a request; else ok
// gpuhangonce on the GPU, never answers the first request of the
// test; else ok
// gpudiestwice on the GPU, ends at the first two requests of the
// test; else ok
// gpulostidle on the GPU, answers the first request of the test and
// ends at the second, its device lost as Vulkan's is
// after an idle spell (plugins#853); else ok
//
// Like pf-serve, it first writes ggml's startup lines to stderr.
func fakeServe(mode string) {
name := strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe")
gpu := os.Getenv("PF_DEVICE") != "cpu"
device := "MTL0"
if !gpu {
device = "CPU"
}
logf := func(format string, a ...any) {
if p := os.Getenv(fakeLog); p != "" {
f, err := os.OpenFile(p, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err == nil {
fmt.Fprintf(f, format+"\n", a...)
f.Close()
}
}
}
logf("start %s %s", name, device)
// as ggml_metal writes them on an M2, GPU or CPU alike
fmt.Fprintln(os.Stderr, "ggml_metal_device_init: tensor API disabled for pre-M5 and pre-A19 devices")
fmt.Fprintln(os.Stderr, "ggml_metal_library_init: using embedded metal library")
fmt.Fprintln(os.Stderr, "ggml_metal_device_init: GPU name: MTL0 (Apple M2)")
fmt.Fprintln(os.Stderr, "ggml_metal_device_init: recommendedMaxWorkingSetSize = 12713.12 MB")
logf("path %s", filepath.Base(filepath.Dir(os.Args[0])))
logf("residency %s", os.Getenv("GGML_METAL_NO_RESIDENCY"))
logf("moechunk %s %s", name, os.Getenv("PF_MOE_CHUNK"))
// as pf-serve on Windows, whose argv is in the ANSI code page and
// whose ggml reads it as UTF-8: a model path with a byte outside
// ASCII can't be opened. And it opens the file from where it runs.
model := ""
if len(os.Args) > 1 {
model = os.Args[1]
}
logf("model %s", model)
_, err := os.Stat(model)
if strings.IndexFunc(model, func(r rune) bool { return r > 0x7f }) >= 0 || err != nil || mode == "badmodel" {
json.NewEncoder(os.Stdout).Encode(map[string]string{"error": "failed to read GGUF: " + model})
os.Exit(1)
}
if mode == "noavx2" && name == "pf-serve" {
os.Exit(132)
}
if mode == "noload" || mode == "novulkan" && name == "pf-serve-vulkan" {
json.NewEncoder(os.Stdout).Encode(map[string]string{"error": "can't load " + mode})
os.Exit(1)
}
if mode == "loadhang" || mode == "gpuloadhang" && gpu {
time.Sleep(time.Hour)
}
json.NewEncoder(os.Stdout).Encode(map[string]any{"device": device, "gpu": gpu, "ms": 7})
in := bufio.NewReader(os.Stdin)
out := bufio.NewWriter(os.Stdout)
u32 := func() (uint32, error) {
var b [4]byte
_, err := io.ReadFull(in, b[:])
return binary.LittleEndian.Uint32(b[:]), err
}
put := func(v any) { binary.Write(out, binary.LittleEndian, v) }
for {
n, err := u32()
if err != nil {
os.Exit(0) // stdin ended: magpie let it go
}
texts := make([]string, n)
for i := range texts {
l, _ := u32()
b := make([]byte, l)
io.ReadFull(in, b)
texts[i] = string(b)
}
logf("request %d %q", n, texts)
// nth: which request of the test this is on the GPU, counted
// across the pf-serves the test starts
nth := 0
if p := os.Getenv(fakeLog); p != "" && gpu {
for nth = 1; ; nth++ {
f, err := os.OpenFile(fmt.Sprintf("%s.gpu%d", p, nth), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
if err == nil {
f.Close()
break
}
}
}
once := strings.HasSuffix(mode, "once") && nth == 1
switch {
case mode == "gpudies" && gpu, mode == "gpudiestwice" && gpu && nth <= 2:
fmt.Fprintln(os.Stderr, "ggml_metal: device lost")
os.Exit(3)
case mode == "gpulostidle" && nth == 2:
// as pf-serve-vulkan on Windows (MinGW) ends with it
fmt.Fprintln(os.Stderr, "terminate called after throwing an instance of 'vk::DeviceLostError'")
fmt.Fprintln(os.Stderr, " what(): vk::Device::waitForFences: ErrorDeviceLost")
os.Exit(3)
case mode == "hang", mode == "gpuhang" && gpu, mode == "gpuhangonce" && once:
time.Sleep(time.Hour)
case mode == "asserts":
fmt.Fprintln(os.Stderr, "ggml_metal_library_compile_pipeline: compiling pipeline: base = 'kernel_add_id'")
fmt.Fprintln(os.Stderr, "/ggml/src/ggml-metal/ggml-metal-ops.cpp:1234: GGML_ASSERT(ne00 % 4 == 0) failed")
os.Exit(3)
case mode == "slow":
time.Sleep(300 * time.Millisecond)
}
put(uint32(0))
for _, t := range texts {
var at []int
for i := 0; ; {
j := strings.Index(t[i:], "Alice")
if j < 0 {
break
}
at = append(at, i+j)
i += j + 5
}
put(uint32(len(at)))
for _, a := range at {
put(int32(a))
put(int32(a + 5))
put(float32(0.98))
put(uint8(len("private_person")))
out.WriteString("private_person")
}
}
out.Flush()
}
}
// fakeInstall puts the stand-in where pf-serve goes (and as
// pf-serve-vulkan too, with vulkan), and a model file, in a folder of the
// test's own; it gives the file the stand-in logs to.
func fakeInstall(t *testing.T, mode string, vulkan bool) string {
t.Helper()
return fakeInstallAt(t, mode, vulkan, t.TempDir())
}
// fakeInstallAt is fakeInstall in folder d.
func fakeInstallAt(t *testing.T, mode string, vulkan bool, d string) string {
t.Helper()
upgrades.Wait() // one started before reads dir
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatal(err)
}
was, wasSize, wasIdle := dir, modelSize, idleAfter
dir, modelSize = func() string { return d }, 4
t.Cleanup(func() {
Stop()
// a request Stop failed lets its turn go
turn <- struct{}{}
<-turn
upgrades.Wait()
disk.mu.Lock()
if disk.timer != nil && disk.timer.Stop() {
disk.saves.Done()
}
disk.timer = nil
disk.loaded = ""
disk.mu.Unlock()
disk.saves.Wait() // a write under way reads dir
srv.mu.Lock()
srv.cpu, srv.gpuLost, srv.failed = false, "", ""
srv.gpuFails, srv.gpuAgain = 0, time.Time{}
srv.lastErr, srv.fails, srv.retryAt = nil, 0, time.Time{}
srv.mu.Unlock()
cache.mu.Lock()
cache.ll.Init()
clear(cache.m)
cache.mu.Unlock()
dir, modelSize, idleAfter = was, wasSize, wasIdle
})
if err := os.WriteFile(modelPath(), []byte("gguf"), 0o644); err != nil {
t.Fatal(err)
}
self, err := os.Executable()
if err != nil {
t.Fatal(err)
}
b, err := os.ReadFile(self)
if err != nil {
t.Fatal(err)
}
os.MkdirAll(serveDir(), 0o755)
names := []string{"pf-serve"}
if vulkan {
names = append(names, "pf-serve-vulkan")
}
for _, n := range names {
if err := os.WriteFile(exe(n), b, 0o755); err != nil {
t.Fatal(err)
}
}
log := filepath.Join(d, "fake.log")
t.Setenv(fakeVar, mode)
t.Setenv(fakeLog, log)
return log
}
// gpuInstall is fakeInstall with a GPU's pf-serve to start first:
// macOS's own, which runs on Metal, or elsewhere pf-serve-vulkan, as a
// computer with no Vulkan loader has none (#3741: these tests took
// macOS's for every system, and were red on Linux). It answers the line
// the stand-in logs as it starts there.
func gpuInstall(t *testing.T, mode string) (log, gpuStart string) {
t.Helper()
if runtime.GOOS == "darwin" {
return fakeInstall(t, mode, false), "start pf-serve MTL0"
}
return fakeInstall(t, mode, true), "start pf-serve-vulkan MTL0"
}
// fakeLines are the lines the stand-in logged that start with prefix.
func fakeLines(t *testing.T, log, prefix string) []string {
t.Helper()
b, _ := os.ReadFile(log)
var out []string
for _, l := range strings.Split(string(b), "\n") {
if strings.HasPrefix(l, prefix) {
out = append(out, l)
}
}
return out
}