git » summer » commit 66f223d

walk: Fix deadlock when collecting errors from workers

author Alberto Bertogli
2026-10-30 19:52:33 UTC
committer Alberto Bertogli
2026-10-30 20:01:46 UTC
parent c426c87921cd8818349b8ed50946fe5fa416d46a

walk: Fix deadlock when collecting errors from workers

Today, when walking, we accumulate errors in a channel that has one slot
per worker.

Once the walk is over, the workers continue to run but nothing collects
from the error channel. If they all fail, the last one could end up
blocking on the channel and causing a deadlock.

Because in practice we only need the first error, this commit fixes it
by using a context with cancellation, that has the semantics we need.

errors_test.go +40 -0
walk.go +11 -17

diff --git a/errors_test.go b/errors_test.go
index c62bd4d..d316ffd 100644
--- a/errors_test.go
+++ b/errors_test.go
@@ -4,8 +4,11 @@ import (
 	"errors"
 	"io/fs"
 	"os"
+	"path/filepath"
+	"strconv"
 	"syscall"
 	"testing"
+	"time"
 )
 
 // Tests for errors that are not feasible to cover by the end to end tests.
@@ -60,6 +63,43 @@ func TestOpenAndInfoError(t *testing.T) {
 	}
 }
 
+func TestWalkAllWorkersFail(t *testing.T) {
+	// The walk can hand out one more file than there are workers before it
+	// sees the first error. Test that exact case, where all the files fail
+	// after the walk has finished, which used to cause a deadlock.
+	defer func(p int) { options.parallel = p }(options.parallel)
+
+	// Slow workers, so the walk ends before they return the first error.
+	fn := func(*os.File, fs.FileInfo, *Progress) error {
+		time.Sleep(100 * time.Millisecond)
+		return testErr
+	}
+
+	for _, parallel := range []int{1, 4} {
+		options.parallel = parallel
+
+		dir := t.TempDir()
+		for i := range parallel + 1 {
+			path := filepath.Join(dir, strconv.Itoa(i))
+			if err := os.WriteFile(path, nil, 0o644); err != nil {
+				t.Fatal(err)
+			}
+		}
+
+		done := make(chan error, 1)
+		go func() { done <- walk([]string{dir}, fn) }()
+
+		select {
+		case err := <-done:
+			if !errors.Is(err, testErr) {
+				t.Errorf("parallel=%d: expected testErr, got %v", parallel, err)
+			}
+		case <-time.After(10 * time.Second):
+			t.Fatalf("parallel=%d: walk hung", parallel)
+		}
+	}
+}
+
 type fakeDB struct {
 	hasAttr bool
 	hasErr  error
diff --git a/walk.go b/walk.go
index 87885f1..7541b81 100644
--- a/walk.go
+++ b/walk.go
@@ -1,6 +1,7 @@
 package main
 
 import (
+	"context"
 	"fmt"
 	"io/fs"
 	"os"
@@ -98,18 +99,19 @@ func walk(roots []string, fn walkFn) error {
 	// Launch the workers.
 	wg := sync.WaitGroup{}
 	workC := make(chan walkItem)
-	workerErrs := make(chan error, options.parallel)
+	ctx, cancel := context.WithCancelCause(context.Background())
+	defer cancel(nil)
 	for i := 0; i < options.parallel; i++ {
 		wg.Add(1)
-		go worker(&wg, workC, fn, workerErrs)
+		go worker(&wg, workC, fn, cancel)
 	}
 
 	// Helper function used by filepath.WalkDir to send items to the workers.
 	wfn := func(path string, d fs.DirEntry, err error) error {
 		// On each iteration, check if any of the workers had an error.
 		// If so, return it, which stops the walk immediately.
-		if werr, ok := hasErr(workerErrs); ok {
-			return werr
+		if ctx.Err() != nil {
+			return context.Cause(ctx)
 		}
 
 		// Open the file one by one, because as part of doing so, the function
@@ -136,8 +138,8 @@ func walk(roots []string, fn walkFn) error {
 	wg.Wait()
 
 	// Check for any errors in the last iterations.
-	if werr, ok := hasErr(workerErrs); err == nil && ok {
-		err = werr
+	if err == nil {
+		err = context.Cause(ctx)
 	}
 
 	if p.corrupted > 0 && err == nil {
@@ -146,22 +148,14 @@ func walk(roots []string, fn walkFn) error {
 	return err
 }
 
-func worker(wg *sync.WaitGroup, c chan walkItem, fn walkFn, errc chan error) {
+func worker(wg *sync.WaitGroup, c chan walkItem, fn walkFn, fail context.CancelCauseFunc) {
 	defer wg.Done()
 	for item := range c {
 		err := fn(item.fd, item.info, item.p)
 		item.fd.Close()
 		if err != nil {
-			errc <- fmt.Errorf("error in %q: %w", item.fd.Name(), err)
+			// Only the first call has any effect, and it never blocks.
+			fail(fmt.Errorf("error in %q: %w", item.fd.Name(), err))
 		}
 	}
 }
-
-func hasErr(errc chan error) (error, bool) {
-	select {
-	case err := <-errc:
-		return err, true
-	default:
-		return nil, false
-	}
-}