package tools import ( "context" "errors" "path/filepath" "slices" "strconv" "strings" "sync" "testing" "testing/synctest" "time" "github.com/devvmhq/devvm/internal/backend" "github.com/devvmhq/devvm/internal/backend/backendtest" "github.com/devvmhq/devvm/internal/leaktest" "github.com/devvmhq/devvm/internal/msg" "github.com/devvmhq/devvm/internal/platform" "github.com/devvmhq/devvm/internal/state" "github.com/devvmhq/devvm/internal/vmname" ) // TestMain fails the tests if a goroutine of theirs outlives them: the // builds side by side included. func TestMain(m *testing.M) { leaktest.Main(m) } // How many tool images build side by side: what the host's memory, less // what devvm's running VMs have, and its CPUs give a build VM of 2 GiB and // 2 CPUs each, beyond 6 GiB and 2 CPUs it keeps, at most 4 and no more // than there are; one alone gets base's size. func TestSlots(t *testing.T) { small := backend.Size{CPUs: 2, MemoryGiB: 2} for _, tc := range []struct { name string gib uint64 cpu int n int running uint64 // GiB want int }{ {"one tool", 64, 32, 1, 0, 1}, {"a Mac mini", 16, 10, 4, 0, 4}, {"a Mac mini, six tools", 16, 10, 6, 0, 4}, {"two tools", 16, 10, 2, 0, 2}, {"8 GiB", 8, 8, 4, 0, 1}, {"10 GiB", 10, 8, 4, 0, 2}, {"four CPUs", 64, 4, 4, 0, 1}, {"six CPUs", 64, 6, 4, 0, 2}, {"a Mac mini, two 8 GiB VMs running", 16, 10, 4, 16, 1}, {"a Mac mini, one 4 GiB VM running", 16, 10, 4, 4, 3}, {"32 GiB, 8 GiB running", 32, 10, 4, 8, 4}, } { t.Run(tc.name, func(t *testing.T) { e := newEnv(t) e.Memory = func() (uint64, error) { return tc.gib << 30, nil } e.CPUs = func() int { return tc.cpu } n, size := e.slots(tc.n, tc.running<<30) wantSize := backend.Size{} if tc.want > 1 { wantSize = small } if n != tc.want || size != wantSize { t.Errorf("slots(%d) = %d, %+v, want %d, %+v", tc.n, n, size, tc.want, wantSize) } }) } e := newEnv(t) e.Memory = func() (uint64, error) { return 0, errors.New("no memory") } e.CPUs = func() int { return 32 } if n, _ := e.slots(4, 0); n != 1 { t.Errorf("slots with no memory read = %d, want 1", n) } } // The builds side by side are as many as the backend's disks have room // for, each build VM counted: fewer on a disk that holds fewer, one when // it holds one; and none side by side when the backend can't say what // its running VMs have. Which slot builds which image is whichever is // free first, so the test checks the slots each build is given, never // how the images fell to them. func TestBuildSlotsFit(t *testing.T) { for _, tc := range []struct { name string freeGiB uint64 listErr bool running []float64 // the memory of devvm's running VMs, in GiB want int // the slots side by side wantErr string }{ {name: "room for four", freeGiB: 100, want: 4}, // 64 GiB less 52.5 is 11.5: two build VMs of 2 GiB after the 6 // kept back, where 52 would leave room for three. {name: "running VMs' memory", freeGiB: 100, running: []float64{50, 2.5}, want: 2}, {name: "room for two", freeGiB: 7, want: 2}, {name: "room for one", freeGiB: 5, want: 1}, {name: "room for none", freeGiB: 3, wantErr: "disk_low"}, {name: "the VMs unread", freeGiB: 100, listErr: true, want: 1}, } { t.Run(tc.name, func(t *testing.T) { e := newEnv(t) e.locked(t, fixture(t)) e.Memory = func() (uint64, error) { return 64 << 30, nil } e.CPUs = func() int { return 32 } e.FreeSpace = func(string) (uint64, error) { return tc.freeGiB << 30, nil } files := e.files(t, "node", "go", "bun", "claude") f := fake() if tc.listErr { f.Errs = map[string]error{"List": errors.New("limactl list failed")} } // A stopped VM's memory is the host's to use. f.Instances["stopped"] = backend.Instance{Name: "stopped", Status: backend.StatusStopped, Size: backend.Size{MemoryGiB: 32}} for i, gib := range tc.running { name := vmname.VM("running-" + strconv.Itoa(i)) f.Instances[name] = backend.Instance{Name: name, Status: backend.StatusRunning, Size: backend.Size{MemoryGiB: gib}} } var mu sync.Mutex var specs []backend.ToolsSpec f.ToolsBuild = func(_ context.Context, spec backend.ToolsSpec) error { mu.Lock() specs = append(specs, spec) mu.Unlock() return writeImage(spec) } b := backendtest.Stored{Fake: f, Dirs: []string{t.TempDir()}, Floor: backend.Floors{Tools: 2 << 30, PerTool: 512 << 20}} err := e.Build(t.Context(), backend.Review{}, b, baseKey, gnuT, files) if msg.IDOf(err) != tc.wantErr && (err != nil || tc.wantErr != "") { t.Fatalf("Build = %v, want %s", msg.NamesOf(err), tc.wantErr) } if want := len(files); tc.wantErr == "" && len(specs) != want { t.Errorf("%d builds, want %d", len(specs), want) } for _, s := range specs { if s.Slots != tc.want || s.Slot < 0 || s.Slot >= tc.want { t.Errorf("a build in slot %d of %d, want one of %d", s.Slot, s.Slots, tc.want) } } }) } } // A failed build's VM is deleted by the run's cleanup once the build has // let go of the share's lock, so each build's spec can take it again // (Hold): the cleanup holds it while it deletes, and gets false while // another devvm's build has the share, whose own build deletes what it // finds in the slots. func TestBuildHoldsShareForCleanup(t *testing.T) { e := newEnv(t) e.locked(t, fixture(t)) files := e.files(t, "node") f := fake() var hold func() (func(), bool) f.ToolsBuild = func(_ context.Context, spec backend.ToolsSpec) error { hold = spec.Hold return errors.New("the build failed") } if err := e.Build(t.Context(), backend.Review{}, f, baseKey, gnuT, files); err == nil { t.Fatal("Build: no error, want the build's") } if hold == nil { t.Fatal("the build's spec has no Hold") } release, ok := hold() if !ok || !e.ShareBusy() { t.Fatalf("Hold with the share free = %v, busy %v: want it held", ok, e.ShareBusy()) } release() // Another devvm's build has the share. other, err := platform.LockFile(t.Context(), e.Dirs.ShareLock(), nil) if err != nil { t.Fatal(err) } defer other() if _, ok := hold(); ok { t.Error("Hold while another devvm holds the share = true, want false") } } // On a host with room, tool images build side by side, each slot in a // build VM of its own and of the small size, each told how many slots // there are, its run log's lines named for its tool; a group status line // covers them. func TestBuildSideBySide(t *testing.T) { e := newEnv(t) e.locked(t, fixture(t)) e.Memory = func() (uint64, error) { return 16 << 30, nil } e.CPUs = func() int { return 10 } var showed msg.Recorder e.Reporter = &msg.Fake{OnStatus: showed.Add} files := e.files(t, "node", "go", "bun", "claude") synctest.Test(t, func(t *testing.T) { f := fake() var ( mu sync.Mutex slots []int tags []string arrived int ) all := make(chan struct{}) f.ToolsBuild = func(ctx context.Context, spec backend.ToolsSpec) error { mu.Lock() slots = append(slots, spec.Slot) tags = append(tags, msg.LogTagOf(ctx)) if spec.Size != (backend.Size{CPUs: 2, MemoryGiB: 2}) || spec.Slots != 4 { t.Errorf("%s's build VM: %+v of %d slots", spec.Name, spec.Size, spec.Slots) } if arrived++; arrived == len(files) { close(all) } mu.Unlock() // Every build is running before any ends: they're side by side. select { case <-all: case <-time.After(time.Hour): return errors.New("the builds didn't all run at once") } return writeImage(spec) } if err := e.Build(t.Context(), backend.Review{}, f, baseKey, gnuT, files); err != nil { t.Fatalf("Build = %v", msg.NamesOf(err)) } slices.Sort(slots) if !slices.Equal(slots, []int{0, 1, 2, 3}) { t.Errorf("slots used: %v, want one each", slots) } slices.Sort(tags) if !slices.Equal(tags, []string{"bun", "claude", "go", "node"}) { t.Errorf("the builds' log tags: %q", tags) } e.checkHashes(t, files) }) if !slices.ContainsFunc(showed.Names(), func(s string) bool { return strings.HasPrefix(s, "building_tools_together ") }) { t.Errorf("status lines: %q, want the group's", showed.Names()) } e.noLeftovers(t) } // A build side by side that fails stops the others, which are cancelled, // and is what Build returns, named for its tool's lines in the run log, // even when a cancelled one fails after it; the share keeps the images // that were built. func TestBuildSideBySideFails(t *testing.T) { e := newEnv(t) e.locked(t, fixture(t)) e.Memory = func() (uint64, error) { return 16 << 30, nil } e.CPUs = func() int { return 10 } files := e.files(t, "node", "go", "bun") synctest.Test(t, func(t *testing.T) { f := fake() var mu sync.Mutex cancelled := map[string]bool{} bunStarted := make(chan struct{}) f.ToolsBuild = func(ctx context.Context, spec backend.ToolsSpec) error { switch spec.Args[0] { case "node": return writeImage(spec) case "go": // It fails once node's image is in the share and bun's // build has started, so the failure cancels a build and // isn't only what stops bun being handed out. <-bunStarted for { if matches, _ := filepath.Glob(filepath.Join(e.Dirs.Tools(), "node-*.erofs")); len(matches) > 0 { return backend.Logged(msg.ToolsBuildFailed()) } time.Sleep(time.Second) } } // bun waits until it's cancelled, then fails as a killed // build does, after go's failure. close(bunStarted) <-ctx.Done() mu.Lock() cancelled[spec.Args[0]] = true mu.Unlock() return backend.Logged(msg.VMCreateFailed(vmname.VM("devvm-tools-build-3"))) } err := e.Build(t.Context(), backend.Review{}, f, baseKey, gnuT, files) le, ok := errors.AsType[*backend.LoggedError](err) if !ok || msg.IDOf(err) != "tools_build_failed" || le.Tag != "go" { t.Errorf("Build = %v, want go's tools_build_failed", err) } if !cancelled["bun"] { t.Error("bun's build wasn't cancelled") } }) if matches, _ := filepath.Glob(filepath.Join(e.Dirs.Tools(), "node-*.erofs")); len(matches) != 1 { t.Errorf("node's image: %q, want it kept", matches) } e.noLeftovers(t) } // writeImage writes the image a build's spec asks for, and its .glibc, // as a build that needs no glibc version would. func writeImage(spec backend.ToolsSpec) error { if err := state.WriteFile(filepath.Join(spec.Out, spec.Args[2]), backendtest.ToolImage(spec.Args[2])); err != nil { return err } return state.WriteFile(filepath.Join(spec.Out, spec.Args[2]+".glibc"), nil) }