internal/workflow: fix flaky TestParallelism

This is, depressingly, the best idea I had for verifying the tasks run
in parallel that doesn't time out instead of failing. Happy for a better
suggestion.

Fixes golang/go#48158.

Change-Id: I703adf3b9728cd6f9eee2694afaf9c8d258bb6b3
Reviewed-on: https://go-review.googlesource.com/c/build/+/347412
Trust: Heschi Kreinick <heschi@google.com>
Run-TryBot: Heschi Kreinick <heschi@google.com>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Alexander Rakoczy <alex@golang.org>
diff --git a/internal/workflow/workflow_test.go b/internal/workflow/workflow_test.go
index aac7cf5..4cff893 100644
--- a/internal/workflow/workflow_test.go
+++ b/internal/workflow/workflow_test.go
@@ -56,9 +56,27 @@
 }
 
 func TestParallelism(t *testing.T) {
+	// block1 and block2 block until they're both running.
+	chan1, chan2 := make(chan bool, 1), make(chan bool, 1)
+	block1 := func(ctx context.Context) (string, error) {
+		chan1 <- true
+		select {
+		case <-chan2:
+		case <-ctx.Done():
+		}
+		return "", ctx.Err()
+	}
+	block2 := func(ctx context.Context) (string, error) {
+		chan2 <- true
+		select {
+		case <-chan1:
+		case <-ctx.Done():
+		}
+		return "", ctx.Err()
+	}
 	wd := workflow.New()
-	out1 := wd.Task("sleep #1", sleep, wd.Constant(100*time.Millisecond))
-	out2 := wd.Task("sleep #2", sleep, wd.Constant(100*time.Millisecond))
+	out1 := wd.Task("block #1", block1)
+	out2 := wd.Task("block #2", block2)
 	wd.Output("out1", out1)
 	wd.Output("out2", out2)
 
@@ -66,14 +84,12 @@
 	if err != nil {
 		t.Fatal(err)
 	}
-	start := time.Now()
-	_, err = w.Run(context.Background(), loggingListener(t))
+	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+	defer cancel()
+	_, err = w.Run(ctx, loggingListener(t))
 	if err != nil {
 		t.Fatal(err)
 	}
-	if delay := time.Since(start); delay > 150*time.Millisecond {
-		t.Errorf("too much time elapsed: %v", delay)
-	}
 }
 
 func TestParameters(t *testing.T) {
@@ -98,11 +114,6 @@
 	}
 }
 
-func sleep(ctx context.Context, d time.Duration) (struct{}, error) {
-	time.Sleep(d)
-	return struct{}{}, nil
-}
-
 func appendInt(ctx context.Context, s string, i int) (string, error) {
 	return fmt.Sprintf("%v%v", s, i), nil
 }