Skip to content

Commit b61bc2d

Browse files
Merge cursor/run-cancel-signals-971d into cursor/network-failfast-env-971d
Co-authored-by: Ben Schellenberger <bschellenberger2600@users.noreply.github.com>
2 parents 971ef9f + 44ff171 commit b61bc2d

2 files changed

Lines changed: 270 additions & 14 deletions

File tree

‎cmd/default_stream_stall_test.go‎

Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package cmd
33
import (
44
"bytes"
55
"context"
6+
"encoding/json"
67
"fmt"
78
"io"
89
"net"
@@ -169,6 +170,230 @@ func TestRunRainDefaultStream_CancelStopsRemainingRepos(t *testing.T) {
169170
}
170171
}
171172

173+
func TestRunRainDefaultStream_JSONCancelEmitsJSONNotAborted(t *testing.T) {
174+
baseURL, cleanup := startStallTCPListener(t)
175+
defer cleanup()
176+
177+
stallA := testutil.CreateTestRepo(t, testutil.RepoOptions{
178+
Name: "json-stall-a",
179+
Remotes: map[string]string{
180+
"origin": baseURL + "/json-stall-a.git",
181+
},
182+
})
183+
stallB := testutil.CreateTestRepo(t, testutil.RepoOptions{
184+
Name: "json-stall-b",
185+
Remotes: map[string]string{
186+
"origin": baseURL + "/json-stall-b.git",
187+
},
188+
})
189+
190+
prevJSON := rainJSON
191+
rainJSON = true
192+
defer func() { rainJSON = prevJSON }()
193+
194+
cfg := config.DefaultConfig()
195+
cfg.Global.FetchWorkers = 1
196+
cfg.Global.FetchTimeoutSec = 30
197+
cfg.Global.DisableScan = true
198+
199+
opts := git.DefaultScanOptions()
200+
opts.DisableScan = true
201+
opts.KnownPaths = map[string]bool{
202+
stallA: true,
203+
stallB: true,
204+
}
205+
opts.Workers = 1
206+
207+
runCtx, cancel := context.WithCancel(context.Background())
208+
rainOpts := git.RainOptions{
209+
FetchTimeoutSec: 30,
210+
RunCtx: runCtx,
211+
}
212+
213+
oldStdout := os.Stdout
214+
r, w, _ := os.Pipe()
215+
os.Stdout = w
216+
defer func() { os.Stdout = oldStdout }()
217+
218+
done := make(chan error, 1)
219+
go func() {
220+
done <- runRainDefaultStream(&cfg, &registry.Registry{}, "", opts, rainOpts, false)
221+
}()
222+
223+
time.Sleep(300 * time.Millisecond)
224+
cancel()
225+
226+
select {
227+
case err := <-done:
228+
if err == nil {
229+
t.Fatal("expected non-nil error on JSON cancel")
230+
}
231+
if !strings.Contains(err.Error(), "interrupted") {
232+
t.Fatalf("expected interrupted error, got: %v", err)
233+
}
234+
case <-time.After(5 * time.Second):
235+
t.Fatal("runRainDefaultStream did not return after cancel")
236+
}
237+
238+
_ = w.Close()
239+
var out bytes.Buffer
240+
_, _ = io.Copy(&out, r)
241+
body := out.String()
242+
243+
if strings.Contains(body, "Aborted.") {
244+
t.Fatalf("--json cancel must not print Aborted. on stdout, got:\n%s", body)
245+
}
246+
var doc jsonRunDocument
247+
if err := json.Unmarshal([]byte(body), &doc); err != nil {
248+
t.Fatalf("expected schema_version 1 JSON on cancel, decode error: %v\nraw:\n%s", err, body)
249+
}
250+
if doc.SchemaVersion != jsonSchemaVersion {
251+
t.Fatalf("schema_version = %d", doc.SchemaVersion)
252+
}
253+
}
254+
255+
func TestRunRainOnRepos_CancelSkipsRemaining(t *testing.T) {
256+
baseURL, cleanup := startStallTCPListener(t)
257+
defer cleanup()
258+
259+
stallA := testutil.CreateTestRepo(t, testutil.RepoOptions{
260+
Name: "seq-stall-a",
261+
Remotes: map[string]string{
262+
"origin": baseURL + "/seq-stall-a.git",
263+
},
264+
})
265+
stallB := testutil.CreateTestRepo(t, testutil.RepoOptions{
266+
Name: "seq-stall-b",
267+
Remotes: map[string]string{
268+
"origin": baseURL + "/seq-stall-b.git",
269+
},
270+
})
271+
stallC := testutil.CreateTestRepo(t, testutil.RepoOptions{
272+
Name: "seq-stall-c",
273+
Remotes: map[string]string{
274+
"origin": baseURL + "/seq-stall-c.git",
275+
},
276+
})
277+
278+
runCtx, cancel := context.WithCancel(context.Background())
279+
rainOpts := git.RainOptions{
280+
FetchTimeoutSec: 30,
281+
RunCtx: runCtx,
282+
}
283+
repos := []git.Repository{
284+
{Name: "seq-stall-a", Path: stallA, Selected: true},
285+
{Name: "seq-stall-b", Path: stallB, Selected: true},
286+
{Name: "seq-stall-c", Path: stallC, Selected: true},
287+
}
288+
289+
oldStdout := os.Stdout
290+
r, w, _ := os.Pipe()
291+
os.Stdout = w
292+
defer func() { os.Stdout = oldStdout }()
293+
294+
done := make(chan error, 1)
295+
start := time.Now()
296+
go func() {
297+
done <- runRainOnRepos(&registry.Registry{}, repos, rainOpts, false)
298+
}()
299+
300+
time.Sleep(300 * time.Millisecond)
301+
cancel()
302+
303+
select {
304+
case err := <-done:
305+
if err != nil {
306+
t.Fatalf("runRainOnRepos: %v", err)
307+
}
308+
case <-time.After(5 * time.Second):
309+
t.Fatal("runRainOnRepos did not return after cancel")
310+
}
311+
elapsed := time.Since(start)
312+
313+
_ = w.Close()
314+
var out bytes.Buffer
315+
_, _ = io.Copy(&out, r)
316+
body := out.String()
317+
318+
if !strings.Contains(body, "Aborted.") {
319+
t.Fatalf("expected Aborted. after cancel, got:\n%s", body)
320+
}
321+
if strings.Contains(body, "rain delivered") {
322+
t.Fatalf("did not expect completed summary after cancel, got:\n%s", body)
323+
}
324+
if elapsed > 5*time.Second {
325+
t.Fatalf("run took %v after cancel; remaining repos should be skipped", elapsed)
326+
}
327+
frozenLines := strings.Count(body, "❄")
328+
if frozenLines >= 3 {
329+
t.Fatalf("expected remaining repos skipped after cancel, got %d frozen lines:\n%s", frozenLines, body)
330+
}
331+
}
332+
333+
func TestRunDryRun_CancelAborts(t *testing.T) {
334+
runCtx, cancel := context.WithCancel(context.Background())
335+
cancel() // already cancelled before scan
336+
337+
cfg := config.DefaultConfig()
338+
opts := git.DefaultScanOptions()
339+
opts.RootPath = t.TempDir()
340+
opts.DisableScan = false
341+
opts.Workers = 1
342+
343+
oldStdout := os.Stdout
344+
r, w, _ := os.Pipe()
345+
os.Stdout = w
346+
defer func() { os.Stdout = oldStdout }()
347+
348+
err := runDryRun(opts, git.RainOptions{RunCtx: runCtx}, false, &cfg)
349+
_ = w.Close()
350+
var out bytes.Buffer
351+
_, _ = io.Copy(&out, r)
352+
body := out.String()
353+
354+
if err != nil {
355+
t.Fatalf("human dry-run cancel should return nil, got %v", err)
356+
}
357+
if !strings.Contains(body, "Aborted.") {
358+
t.Fatalf("expected Aborted. after dry-run cancel, got:\n%s", body)
359+
}
360+
if strings.Contains(body, "Would run") {
361+
t.Fatalf("did not expect dry-run listing after cancel, got:\n%s", body)
362+
}
363+
}
364+
365+
func TestRunDryRun_JSONCancelReturnsError(t *testing.T) {
366+
runCtx, cancel := context.WithCancel(context.Background())
367+
cancel()
368+
369+
prevJSON := rainJSON
370+
rainJSON = true
371+
defer func() { rainJSON = prevJSON }()
372+
373+
cfg := config.DefaultConfig()
374+
opts := git.DefaultScanOptions()
375+
opts.RootPath = t.TempDir()
376+
opts.Workers = 1
377+
378+
oldStdout := os.Stdout
379+
r, w, _ := os.Pipe()
380+
os.Stdout = w
381+
defer func() { os.Stdout = oldStdout }()
382+
383+
err := runDryRun(opts, git.RainOptions{RunCtx: runCtx}, false, &cfg)
384+
_ = w.Close()
385+
var out bytes.Buffer
386+
_, _ = io.Copy(&out, r)
387+
body := out.String()
388+
389+
if err == nil || !strings.Contains(err.Error(), "interrupted") {
390+
t.Fatalf("expected interrupted error, got %v", err)
391+
}
392+
if strings.Contains(body, "Aborted.") {
393+
t.Fatalf("--json dry-run cancel must not print Aborted., got:\n%s", body)
394+
}
395+
}
396+
172397
func startStallTCPListener(t *testing.T) (baseURL string, cleanup func()) {
173398
t.Helper()
174399
ln, err := net.Listen("tcp", "127.0.0.1:0")

‎cmd/root.go‎

Lines changed: 45 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -363,10 +363,11 @@ func printRainSummary(totals rainTotals, runCtx context.Context) error {
363363
// and accumulates outcome counts. Each repo's output is written as a single block
364364
// directly to stdout. Used for the --rain TUI post-processing path; the default
365365
// CLI run uses runRainDefaultStream for parallel execution.
366+
// Stops starting new repos when RunCtx is cancelled (SIGINT/SIGTERM).
366367
func processRainRepositories(reg *registry.Registry, repos []git.Repository, rainOpts git.RainOptions, fullSync bool, totals *rainTotals, jsonReports *[]jsonRepoResult) {
367368
for i, repo := range repos {
368369
if rainOpts.RunCtx != nil && rainOpts.RunCtx.Err() != nil {
369-
break
370+
return
370371
}
371372
var buf strings.Builder
372373
delta, report := runRainOnRepo(reg, repo, rainOpts, fullSync, i+1, len(repos), &buf, !rainJSON)
@@ -383,6 +384,20 @@ func processRainRepositories(reg *registry.Registry, repos []git.Repository, rai
383384
}
384385
}
385386

387+
// reportRunInterrupted handles SIGINT/SIGTERM after work stops. Human mode prints
388+
// Aborted. and returns nil; --json emits schema_version 1 then a non-zero error so
389+
// agents do not treat cancel as a successful empty run.
390+
func reportRunInterrupted(rainOpts git.RainOptions, fullSync bool, totals rainTotals, reports []jsonRepoResult) error {
391+
if rainJSON {
392+
if err := emitJSONRun(buildJSONRunMeta(rainOpts, fullSync), totals, reports); err != nil {
393+
return err
394+
}
395+
return fmt.Errorf("interrupted")
396+
}
397+
fmt.Println("Aborted.")
398+
return nil
399+
}
400+
386401
// runRainOnRepo runs the rain operation for a single repository, writing its
387402
// entire output block (header + branch lines + trailing blank line) into out.
388403
// totalStr is rendered as "[N/M] reponame"; pass "?" for M when the total is
@@ -546,10 +561,21 @@ func summarizeBranchRun(failed, frozen, updated int, branches []git.RainBranchRe
546561
}
547562

548563
func runDryRun(scanOpts git.ScanOptions, rainOpts git.RainOptions, fullSync bool, cfg *config.Config) error {
564+
// Honor RunCtx so SIGINT/SIGTERM can stop a long scan (NotifyContext owns the signals).
565+
if rainOpts.RunCtx != nil {
566+
scanOpts.Ctx = rainOpts.RunCtx
567+
}
549568
repos, err := git.ScanRepositories(scanOpts)
550569
if err != nil {
551570
return fmt.Errorf("repository scan failed: %w", err)
552571
}
572+
if rainOpts.RunCtx != nil && rainOpts.RunCtx.Err() != nil {
573+
if rainJSON {
574+
return fmt.Errorf("interrupted")
575+
}
576+
fmt.Println("Aborted.")
577+
return nil
578+
}
553579

554580
if rainJSON {
555581
return emitJSONDryRun(buildJSONRunMeta(rainOpts, fullSync), repos)
@@ -617,11 +643,13 @@ func runDryRun(scanOpts git.ScanOptions, rainOpts git.RainOptions, fullSync bool
617643
// The filesystem scan runs concurrently; repos stream into the picker as they
618644
// are discovered. After confirmation, the same default or --sync behavior runs.
619645
func runRainTUIStream(cfg *config.Config, reg *registry.Registry, regPath string, opts git.ScanOptions, rainOpts git.RainOptions, fullSync bool) error {
620-
scanParent := rainOpts.RunCtx
621-
if scanParent == nil {
622-
scanParent = context.Background()
646+
// Derive scan cancellation from RunCtx so SIGINT/SIGTERM stops the walk
647+
// (and in-flight analyze git) instead of only the network process group.
648+
parent := rainOpts.RunCtx
649+
if parent == nil {
650+
parent = context.Background()
623651
}
624-
ctx, cancelScan := context.WithCancel(scanParent)
652+
ctx, cancelScan := context.WithCancel(parent)
625653
defer cancelScan()
626654
opts.Ctx = ctx
627655

@@ -971,9 +999,15 @@ func runRainDefaultStream(cfg *config.Config, reg *registry.Registry, regPath st
971999
printMu.Lock()
9721000
defer printMu.Unlock()
9731001

1002+
totals := rainTotals{
1003+
updated: int(atomic.LoadInt64(&updated)),
1004+
skipped: int(atomic.LoadInt64(&skipped)),
1005+
frozen: int(atomic.LoadInt64(&frozen)),
1006+
failed: int(atomic.LoadInt64(&failed)),
1007+
}
1008+
9741009
if ctx.Err() != nil {
975-
fmt.Println("Aborted.")
976-
return nil
1010+
return reportRunInterrupted(rainOpts, fullSync, totals, jsonReports)
9771011
}
9781012

9791013
if atomic.LoadInt64(&seq) == 0 {
@@ -990,13 +1024,6 @@ func runRainDefaultStream(cfg *config.Config, reg *registry.Registry, regPath st
9901024
return nil
9911025
}
9921026

993-
totals := rainTotals{
994-
updated: int(atomic.LoadInt64(&updated)),
995-
skipped: int(atomic.LoadInt64(&skipped)),
996-
frozen: int(atomic.LoadInt64(&frozen)),
997-
failed: int(atomic.LoadInt64(&failed)),
998-
}
999-
10001027
if rainJSON {
10011028
if err := emitJSONRun(buildJSONRunMeta(rainOpts, fullSync), totals, jsonReports); err != nil {
10021029
return err
@@ -1037,6 +1064,10 @@ func runRainOnRepos(reg *registry.Registry, repos []git.Repository, opts git.Rai
10371064
var jsonReports []jsonRepoResult
10381065
processRainRepositories(reg, repos, opts, fullSync, &totals, &jsonReports)
10391066

1067+
if opts.RunCtx != nil && opts.RunCtx.Err() != nil {
1068+
return reportRunInterrupted(opts, fullSync, totals, jsonReports)
1069+
}
1070+
10401071
if rainJSON {
10411072
if err := emitJSONRun(buildJSONRunMeta(opts, fullSync), totals, jsonReports); err != nil {
10421073
return err

0 commit comments

Comments
 (0)