From c6f3752c82644e6ce5fc00837942287d5e22f2be Mon Sep 17 00:00:00 2001 From: Interlap Date: Mon, 16 Nov 2026 16:57:32 +0100 Subject: [PATCH 1/2] fix(watch): cancel a boot's slim when the device shuts down, add watch --json A device shut down mid-pass and booted again kept its old after-boot pass running: forget() dropped the claim but not the pass, so its retries ran into the new boot and disabled services a wrapper had enabled after the new boot's pass finished. Each pass now has its own cancel, called on shutdown or deletion, and a superseded pass reports stopped instead of slimmed or clearing the newer boot's claim. watch --json prints one WatchEvent per line on stdout (slimming, slimmed, failed, stopped, slimmed_before_boot), a stable signal for wrappers that wait for a boot's slim before calling enable. Fixes #71 --- CLAUDE.md | 4 ++ README.md | 16 ++++++ cmd/simslim/app.go | 1 + cmd/simslim/main.go | 14 +++++ watch.go | 123 ++++++++++++++++++++++++++++++++---------- watch_test.go | 127 +++++++++++++++++++++++++++++++++++++++++--- 6 files changed, 251 insertions(+), 34 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 9d735e9..d7432d7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -117,6 +117,10 @@ missing) seeds a new device from its `device.plist` in its own goroutine (`seedNew`), since a `simctl list` on a loaded host takes longer than a script waits between `simctl create` and boot. A boot that starts first is logged and caught by the no-reboot slim at boot, which stays as the read-back and fallback. +Each boot's after-boot pass has its own cancel (`slimPass`), called when the +device shuts down or is deleted, so a pass never retries into the next boot; a +superseded pass reports `stopped`, never `slimmed`. `WatchWithEvents` emits +`WatchEvent`s, which `watch --json` prints one per line as a stable contract. **Live enable/disable.** `live.go` holds `EnableServices`/`DisableServices` (`simslim enable`/`disable`), which act on a booted simulator only and keep no diff --git a/README.md b/README.md index add3199..6666f14 100644 --- a/README.md +++ b/README.md @@ -364,6 +364,22 @@ It takes the same `--profile`/`--except`/`--keep` selection as `on`, and scans the default and `testing` sets plus any passed with `--set`. Point `--set` at a custom parallel-testing device set if your Xcode uses one. It runs until Ctrl-C. +A wrapper that turns services on per run with `simslim enable` should wait for +watch to finish with the boot first, or watch may switch them off again. +`simslim watch --json` prints one JSON object per line on stdout, a stable +interface unlike the log lines: + +```json +{"event":"slimmed","udid":"…","set":"default"} +``` + +`event` is `slimming` (a boot's pass started), `slimmed` (it finished; watch +leaves the device alone until it shuts down), `failed` (with `error`; the next +scan retries), `stopped` (the device shut down mid-pass, so the pass was +cancelled), or `slimmed_before_boot` (with `services`, the disables written into +a shut-down device's store). Boot the device, wait for its `slimmed` (or +`failed`), then call `enable`. + ## Disk cleanup Disk cleanup is permanent and separate from service slimming. `disk-plan` is diff --git a/cmd/simslim/app.go b/cmd/simslim/app.go index 05b1b97..1ec4f5d 100644 --- a/cmd/simslim/app.go +++ b/cmd/simslim/app.go @@ -75,6 +75,7 @@ func newApp() *cli.Command { &cli.StringFlag{Name: "save", Usage: "also remove the services from this profile file, creating it if needed"}, }, Action: cmdDisable}, {Name: "watch", Flags: []cli.Flag{ + &cli.BoolFlag{Name: "json", Usage: "print one JSON object per event on stdout (slimming, slimmed, failed, stopped, slimmed_before_boot) instead of log lines"}, &cli.StringFlag{Name: "profile", Usage: "apply a JSON profile file (mutually exclusive with --except/--keep)"}, &cli.StringFlag{Name: "except", Usage: "comma-separated category IDs to leave fully enabled (see `simslim profiles`)"}, &cli.StringFlag{Name: "keep", Usage: "comma-separated launchd labels to keep running"}, diff --git a/cmd/simslim/main.go b/cmd/simslim/main.go index d908399..12641f4 100644 --- a/cmd/simslim/main.go +++ b/cmd/simslim/main.go @@ -11,6 +11,7 @@ import ( "runtime" "sort" "strings" + "sync" "github.com/mattn/go-isatty" "github.com/mobai-app/simslim" @@ -843,6 +844,16 @@ func cmdWatch(ctx context.Context, cmd *cli.Command) error { if err != nil { return err } + if cmd.Bool("json") { + var mu sync.Mutex + encoder := json.NewEncoder(os.Stdout) + events := func(e simslim.WatchEvent) { + mu.Lock() + defer mu.Unlock() + _ = encoder.Encode(e) + } + return simslim.WatchWithEvents(ctx, p, cmd.Duration("interval"), nil, events) + } report := simslim.Reporter(func(msg string) { fmt.Fprintln(os.Stderr, msg) }) sets := append([]string{"default", "testing"}, simslim.ExtraDeviceSetTokens()...) fmt.Fprintf(os.Stderr, "Watching device sets [%s]; slimming each simulator before it boots where its runtime allows, and no-reboot as it boots. Ctrl-C to stop.\n", strings.Join(sets, ", ")) @@ -1111,6 +1122,9 @@ COMMANDS --except ids Leave these categories enabled (comma-separated) --keep labels Keep these individual daemons running (comma-separated) --interval dur How often to rescan for booting simulators (default 3s) + --json One JSON object per event on stdout, a stable interface + for wrappers: wait for "slimmed" after a boot before + enabling services on it status Report how slim a booted simulator is --dropped Also list the disabled daemons grouped by category verify Check that a booted simulator's disable overrides still diff --git a/watch.go b/watch.go index 3979599..f27007e 100644 --- a/watch.go +++ b/watch.go @@ -43,14 +43,40 @@ type preslimStrategy func(d Device, p Profile) (int, error) // each booted device in its own goroutine so one slow reconfigure does not delay // catching the next clone, and returns once those goroutines are done. func Watch(ctx context.Context, p Profile, interval time.Duration, report Reporter) error { - return watch(ctx, p, interval, report, EnableSlimNoReboot) + return WatchWithEvents(ctx, p, interval, report, nil) } -func watch(ctx context.Context, p Profile, interval time.Duration, report Reporter, slim slimStrategy) error { +// The WatchEvent kinds. A wrapper that boots a device and then changes its +// services waits for WatchSlimmed (or WatchFailed): after it, the watcher does +// not touch that device again until the device shuts down. +const ( + WatchSlimming = "slimming" // an after-boot pass started + WatchSlimmed = "slimmed" // the pass for the current boot finished + WatchFailed = "failed" // the pass failed; the next scan retries it + WatchStopped = "stopped" // the device shut down, so its pass was cancelled + WatchSlimmedBeforeBoot = "slimmed_before_boot" // disables were written into a shut-down device's store +) + +// WatchEvent is the stable, machine-readable form of a watcher log line. +type WatchEvent struct { + Event string `json:"event"` + UDID string `json:"udid"` + Set string `json:"set"` + Services int `json:"services,omitempty"` // disables written, for slimmed_before_boot + Error string `json:"error,omitempty"` // for failed +} + +// WatchWithEvents is Watch that also hands every WatchEvent to events, which +// may be called from several goroutines at once. A nil events behaves as Watch. +func WatchWithEvents(ctx context.Context, p Profile, interval time.Duration, report Reporter, events func(WatchEvent)) error { + return watch(ctx, p, interval, report, events, EnableSlimNoReboot) +} + +func watch(ctx context.Context, p Profile, interval time.Duration, report Reporter, events func(WatchEvent), slim slimStrategy) error { if interval <= 0 { interval = DefaultWatchInterval } - w := &watcher{p: p, report: report, slim: slim, preslim: preslimDevice, seen: map[string]bool{}, seeded: map[string]bool{}} + w := &watcher{p: p, report: report, events: events, slim: slim, preslim: preslimDevice, passes: map[string]*slimPass{}, seeded: map[string]bool{}} // The CLI exits right after this returns, but an importer keeps running, so // no slim may outlive the call. A cancelled ctx aborts an in-flight slim // inside its next simctl call, which keeps the wait short. @@ -204,20 +230,34 @@ func (w *watcher) seedNew(ctx context.Context, dir deviceDir) { w.seed(d) } -// watcher holds the UDIDs already slimmed or in flight, and in seeded the -// shut-down UDIDs whose store already holds the profile. The scan loop, the -// slim goroutines and the seed goroutines all touch them, so mu guards both. +// watcher holds in passes the booted UDIDs already slimmed or in flight, and in +// seeded the shut-down UDIDs whose store already holds the profile. The scan +// loop, the slim goroutines and the seed goroutines all touch them, so mu +// guards both. type watcher struct { p Profile report Reporter + events func(WatchEvent) slim slimStrategy preslim preslimStrategy wg sync.WaitGroup mu sync.Mutex - seen map[string]bool + passes map[string]*slimPass seeded map[string]bool } +// slimPass is one boot's after-boot slim. Its cancel stops it once that boot +// ends, so it cannot keep retrying into the device's next boot. +type slimPass struct { + cancel context.CancelFunc +} + +func (w *watcher) emit(e WatchEvent) { + if w.events != nil { + w.events(e) + } +} + func (w *watcher) scan(ctx context.Context) { devices, err := ListDevices(ctx) if err != nil { @@ -240,22 +280,18 @@ func (w *watcher) scan(ctx context.Context) { w.mu.Lock() delete(w.seeded, d.UDID) w.mu.Unlock() - if !w.claim(d.UDID) { + pctx, pass := w.claim(ctx, d.UDID) + if pass == nil { continue } w.wg.Add(1) go func(d Device) { defer w.wg.Done() + defer pass.cancel() w.report.report(fmt.Sprintf("watch: slimming %s (set %s)", d.UDID, d.Set)) - if _, err := w.slim(ctx, d.Set, d.UDID, w.p, prefixed(w.report, d.UDID)); err != nil { - w.report.report(fmt.Sprintf("watch: %s: %v", d.UDID, err)) - // A transient launchctl failure would otherwise leave this clone - // stock for the whole test run. The next scan retries it, and a - // torn-down clone drops out of simctl list, so this does not loop. - w.forget(d.UDID) - return - } - w.report.report(fmt.Sprintf("watch: slimmed %s", d.UDID)) + w.emit(WatchEvent{Event: WatchSlimming, UDID: d.UDID, Set: d.Set}) + _, err := w.slim(pctx, d.Set, d.UDID, w.p, prefixed(w.report, d.UDID)) + w.finish(d, pass, err) }(d) } } @@ -288,22 +324,47 @@ func (w *watcher) seed(d Device) { return } w.report.report(fmt.Sprintf("watch: slimmed %s before boot (%d services disabled, set %s)", d.UDID, n, d.Set)) + w.emit(WatchEvent{Event: WatchSlimmedBeforeBoot, UDID: d.UDID, Set: d.Set, Services: n}) } -// claim reserves a UDID for this scan, reporting false when it is already -// slimmed or in flight. -func (w *watcher) claim(udid string) bool { +// finish reports a pass's outcome. It holds mu so a superseded pass, whose boot +// ended, can never announce slimmed after a newer boot's pass has started. +func (w *watcher) finish(d Device, pass *slimPass, err error) { w.mu.Lock() defer w.mu.Unlock() - if w.seen[udid] { - return false + switch { + case w.passes[d.UDID] != pass: + w.report.report(fmt.Sprintf("watch: %s shut down; stopped its slim", d.UDID)) + w.emit(WatchEvent{Event: WatchStopped, UDID: d.UDID, Set: d.Set}) + case err != nil: + // A transient launchctl failure would otherwise leave this clone stock + // for the whole test run. The next scan retries it, and a torn-down + // clone drops out of simctl list, so this does not loop. + delete(w.passes, d.UDID) + w.report.report(fmt.Sprintf("watch: %s: %v", d.UDID, err)) + w.emit(WatchEvent{Event: WatchFailed, UDID: d.UDID, Set: d.Set, Error: err.Error()}) + default: + w.report.report(fmt.Sprintf("watch: slimmed %s", d.UDID)) + w.emit(WatchEvent{Event: WatchSlimmed, UDID: d.UDID, Set: d.Set}) } - w.seen[udid] = true - return true +} + +// claim starts a pass for a booted UDID, returning a nil pass when one is +// already done or in flight for this boot. +func (w *watcher) claim(ctx context.Context, udid string) (context.Context, *slimPass) { + w.mu.Lock() + defer w.mu.Unlock() + if w.passes[udid] != nil { + return nil, nil + } + pctx, cancel := context.WithCancel(ctx) + pass := &slimPass{cancel: cancel} + w.passes[udid] = pass + return pctx, pass } // prune drops the UDIDs of deleted devices, such as finished parallel-testing -// clones, so seen and seeded do not grow by one entry per clone. A device +// clones, so passes and seeded do not grow by one entry per clone. A device // created after the listing started is only seeded again, which is a no-op. func (w *watcher) prune(devices []Device) { listed := make(map[string]bool, len(devices)) @@ -312,9 +373,10 @@ func (w *watcher) prune(devices []Device) { } w.mu.Lock() defer w.mu.Unlock() - for udid := range w.seen { + for udid, pass := range w.passes { if !listed[udid] { - delete(w.seen, udid) + pass.cancel() + delete(w.passes, udid) } } for udid := range w.seeded { @@ -324,9 +386,14 @@ func (w *watcher) prune(devices []Device) { } } +// forget ends a device's boot: its pass, if still running, is cancelled, and +// its next boot gets a pass of its own. func (w *watcher) forget(udid string) { w.mu.Lock() - delete(w.seen, udid) + if pass := w.passes[udid]; pass != nil { + pass.cancel() + delete(w.passes, udid) + } w.mu.Unlock() } diff --git a/watch_test.go b/watch_test.go index eb83a34..fc4764a 100644 --- a/watch_test.go +++ b/watch_test.go @@ -49,7 +49,7 @@ exit 0 } func newTestWatcher(slim slimStrategy, report Reporter) *watcher { - return &watcher{report: report, slim: slim, seen: map[string]bool{}, seeded: map[string]bool{}} + return &watcher{report: report, slim: slim, passes: map[string]*slimPass{}, seeded: map[string]bool{}} } // TestWatchSlimsEachBootedDeviceOnce verifies the scan slims a booted device @@ -189,7 +189,7 @@ func TestWatchWaitsForInFlightSlims(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() returned := make(chan error, 1) - go func() { returned <- watch(ctx, Profile{}, time.Millisecond, nil, fake) }() + go func() { returned <- watch(ctx, Profile{}, time.Millisecond, nil, nil, fake) }() <-started cancel() @@ -382,17 +382,132 @@ func TestSeedNewReadsDevicePlist(t *testing.T) { } // TestWatcherPruneDropsDeletedDevices verifies a deleted device, such as a -// finished parallel-testing clone, leaves neither seen nor seeded. +// finished parallel-testing clone, leaves neither a pass nor seeded, and +// cancels a pass still running for it. func TestWatcherPruneDropsDeletedDevices(t *testing.T) { + gone, cancelGone := context.WithCancel(context.Background()) + keep := &slimPass{cancel: func() {}} w := &watcher{ - seen: map[string]bool{"KEEP": true, "GONE": true}, + passes: map[string]*slimPass{"KEEP": keep, "GONE": {cancel: cancelGone}}, seeded: map[string]bool{"KEEP2": true, "GONE2": true}, } w.prune([]Device{{UDID: "KEEP"}, {UDID: "KEEP2"}}) - if want := map[string]bool{"KEEP": true}; !reflect.DeepEqual(w.seen, want) { - t.Fatalf("seen = %v, want %v", w.seen, want) + if want := map[string]*slimPass{"KEEP": keep}; !reflect.DeepEqual(w.passes, want) { + t.Fatalf("passes = %v, want %v", w.passes, want) + } + if gone.Err() == nil { + t.Fatal("a deleted device's pass was not cancelled") } if want := map[string]bool{"KEEP2": true}; !reflect.DeepEqual(w.seeded, want) { t.Fatalf("seeded = %v, want %v", w.seeded, want) } } + +// eventLog collects watcher events; the watcher calls it from several goroutines. +type eventLog struct { + mu sync.Mutex + events []string +} + +func (l *eventLog) add(e WatchEvent) { + l.mu.Lock() + l.events = append(l.events, e.Event+" "+e.UDID) + l.mu.Unlock() +} + +func (l *eventLog) list() []string { + l.mu.Lock() + defer l.mu.Unlock() + return slices.Clone(l.events) +} + +// TestWatchCancelsPassWhenDeviceShutsDown covers a device shut down mid-pass and +// booted again: the old pass must stop instead of retrying into the new boot, +// where it would disable services a wrapper enabled after the new pass. +func TestWatchCancelsPassWhenDeviceShutsDown(t *testing.T) { + rewrite := fakeDeviceList(t, bootedClone) + + started := make(chan struct{}) + var mu sync.Mutex + calls := 0 + fake := func(ctx context.Context, _, _ string, _ Profile, _ Reporter) (bool, error) { + mu.Lock() + calls++ + first := calls == 1 + mu.Unlock() + if first { + close(started) + <-ctx.Done() // a slow first pass, like one retrying launchctl + return false, ctx.Err() + } + return true, nil + } + + var log eventLog + w := newTestWatcher(fake, nil) + w.events = log.add + w.scan(context.Background()) + <-started + rewrite(shutdownClone) + w.scan(context.Background()) + w.wg.Wait() // returns only because the shutdown cancelled the first pass + rewrite(bootedClone) + w.scan(context.Background()) + w.wg.Wait() + + want := []string{"slimming AAAA", "stopped AAAA", "slimming AAAA", "slimmed AAAA"} + if got := log.list(); !reflect.DeepEqual(got, want) { + t.Fatalf("events = %q, want %q", got, want) + } +} + +// TestWatchStalePassKeepsNewBootClaimed verifies a pass that outlived its boot +// and then fails neither reports failed nor drops the newer boot's claim, which +// would start a third pass on a device the newer pass already slimmed. +func TestWatchStalePassKeepsNewBootClaimed(t *testing.T) { + rewrite := fakeDeviceList(t, bootedClone) + + started := make(chan struct{}) + release := make(chan struct{}) + var mu sync.Mutex + calls := 0 + fake := func(_ context.Context, _, _ string, _ Profile, _ Reporter) (bool, error) { + mu.Lock() + calls++ + first := calls == 1 + mu.Unlock() + if first { + close(started) + <-release // ignores its cancel until a spawn returns + return false, errors.New("launchctl disable failed") + } + return true, nil + } + + var log eventLog + w := newTestWatcher(fake, nil) + w.events = log.add + w.scan(context.Background()) + <-started + rewrite(shutdownClone) + w.scan(context.Background()) + rewrite(bootedClone) + w.scan(context.Background()) + for !slices.Contains(log.list(), "slimmed AAAA") { + time.Sleep(time.Millisecond) + } + close(release) + w.wg.Wait() + w.scan(context.Background()) + w.wg.Wait() + + mu.Lock() + defer mu.Unlock() + if calls != 2 { + t.Fatalf("slim ran %d times, want 2 (one per boot)", calls) + } + want := []string{"slimming AAAA", "slimming AAAA", "slimmed AAAA", "stopped AAAA"} + if got := log.list(); !reflect.DeepEqual(got, want) { + t.Fatalf("events = %q, want %q", got, want) + } +} From 6706d86ae16283e601a227a41f6be4b55d286def Mon Sep 17 00:00:00 2001 From: Interlap Date: Tue, 17 Nov 2026 07:53:03 +0100 Subject: [PATCH 2/2] fix(watch): seed a device scanned mid-shutdown once it reads Shutdown seed() marked a Shutting Down device as seeded although preslimDevice writes nothing until Shutdown, so that shutdown was never seeded and services enabled during the boot carried into the next one. --- watch.go | 4 ++++ watch_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/watch.go b/watch.go index f27007e..4c6afe8 100644 --- a/watch.go +++ b/watch.go @@ -303,6 +303,10 @@ func (w *watcher) seed(d Device) { if w.preslim == nil { return } + // A device caught Shutting Down or Booting is seeded once it reads Shutdown. + if d.State != "Shutdown" { + return + } w.mu.Lock() defer w.mu.Unlock() // serializes the store writes of seedNew and scan if w.seeded[d.UDID] { diff --git a/watch_test.go b/watch_test.go index fc4764a..f46a255 100644 --- a/watch_test.go +++ b/watch_test.go @@ -7,6 +7,7 @@ import ( "path/filepath" "reflect" "slices" + "strings" "sync" "testing" "time" @@ -511,3 +512,30 @@ func TestWatchStalePassKeepsNewBootClaimed(t *testing.T) { t.Fatalf("events = %q, want %q", got, want) } } + +// TestWatchSeedsDeviceScannedMidShutdown covers a scan that lands while +// `simctl shutdown` is still running: the device is not seeded yet, so the next +// scan, which sees it Shutdown, must seed it instead of skipping it. +func TestWatchSeedsDeviceScannedMidShutdown(t *testing.T) { + rewrite := fakeDeviceList(t, strings.Replace(shutdownClone, `"Shutdown"`, `"Shutting Down"`, 1)) + + var mu sync.Mutex + var states []string + w := newTestWatcher(nil, nil) + w.preslim = func(d Device, _ Profile) (int, error) { + mu.Lock() + states = append(states, d.State) + mu.Unlock() + return 1, nil + } + w.scan(context.Background()) + rewrite(shutdownClone) + w.scan(context.Background()) + w.scan(context.Background()) + + mu.Lock() + defer mu.Unlock() + if want := []string{"Shutdown"}; !reflect.DeepEqual(states, want) { + t.Fatalf("seeded in states %q, want %q (once, after the shutdown finished)", states, want) + } +}