From ae68d778e276bf7ba7d0172d1d1d3ea879115255 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 6 Nov 2026 09:06:58 +0530 Subject: [PATCH 1/3] feat(woodpecker-agent): build the agent with upstream's retry window fix The v3.20.1 agent counts WOODPECKER_RETRY_TIMEOUT from the moment an RPC began. Wait() stays open for the whole workflow, so the first dropped connection after two minutes gets no retry and the agent cancels every workflow it runs. keploy-ci-woodpecker-agent builds upstream's v3.20.1 with upstream's open fix (woodpecker-ci/woodpecker#7111, author kept) and three tests for the failure as our agents hit it, runs the patched package's tests in the build, and ships upstream's scratch layout. It is published as ghcr.io/keploy/keploy-ci:woodpecker-agent-, amd64 only. Signed-off-by: slayerjain --- .github/workflows/docker-build.yml | 3 + .github/workflows/publish.yml | 5 + README.md | 35 ++ keploy-ci-woodpecker-agent/Dockerfile | 71 ++++ ...the-retry-window-from-the-first-fail.patch | 373 ++++++++++++++++++ ...for-a-dropped-Wait-poll-and-the-retr.patch | 86 ++++ 6 files changed, 573 insertions(+) create mode 100644 keploy-ci-woodpecker-agent/Dockerfile create mode 100644 keploy-ci-woodpecker-agent/patches/0001-fix-agent-count-the-retry-window-from-the-first-fail.patch create mode 100644 keploy-ci-woodpecker-agent/patches/0002-test-agent-rows-for-a-dropped-Wait-poll-and-the-retr.patch diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.yml index 10f836e..93bc53e 100644 --- a/.github/workflows/docker-build.yml +++ b/.github/workflows/docker-build.yml @@ -292,6 +292,9 @@ jobs: tag-prefix: 'ebpf-objects-' arch: amd64 go: true + - context: ./keploy-ci-woodpecker-agent + tag-prefix: 'woodpecker-agent-' + arch: amd64 steps: - name: Checkout repository diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 36562a2..7ac8851 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -123,6 +123,11 @@ jobs: - context: ./keploy-ci-ebpf-objects tag-prefix: 'ebpf-objects-' platforms: linux/amd64 + # Built from upstream's source too, and nothing builds FROM it. + # amd64-only: every Linux Woodpecker agent host is x86_64. + - context: ./keploy-ci-woodpecker-agent + tag-prefix: 'woodpecker-agent-' + platforms: linux/amd64 steps: - name: Checkout repository diff --git a/README.md b/README.md index 86e5b32..4dc7101 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,41 @@ by digest, and it cannot be rebuilt after that window. Tag: `ghcr.io/keploy/keploy-ci:ebpf-objects-`. +### keploy-ci-woodpecker-agent + +The Woodpecker CI agent, built from upstream's source at a pinned tag and +commit with the patches in `keploy-ci-woodpecker-agent/patches/`, for the Linux +agents that run in docker. It takes upstream's `woodpeckerci/woodpecker-agent` +image's place at the same version, with the same settings. + +**Why:** the v3.20.1 agent counts `WOODPECKER_RETRY_TIMEOUT` (2 minutes by +default) from the moment an RPC began, not from its first failure. `Wait()` +stays open for the whole workflow, so when the connection to the server drops +once after that, the agent does not retry: it cancels every workflow it is +running, and every step shows as killed. Patch 0001 is upstream's open fix, +woodpecker-ci/woodpecker#7111 (issue #7110), applied to v3.20.1. Patch 0002 +adds tests for the failure as it happened on our agents: a `Wait()` that +outlived the window and then got the server's `too_many_pings` GOAWAY, and an +agent with no window (`WOODPECKER_RETRY_TIMEOUT=0`) whose retry interval must +keep growing. The build runs the patched package's tests and fails if one +fails. + +**Contents:** the `woodpecker-agent` binary (reporting version +`-keploy.`), CA certificates, timezone data, and upstream's +`/etc/woodpecker` layout, on `scratch`, as upstream's image. amd64 only: every +Linux agent host is x86_64. The macOS and Windows agents run the binary +natively and do not use this image. + +```yaml +# The agent's compose service +image: ghcr.io/keploy/keploy-ci:woodpecker-agent- +``` + +When an upstream release carries the fix, move the agents back to upstream's +image at that release and delete this directory. + +Tag: `ghcr.io/keploy/keploy-ci:woodpecker-agent-`. + ## The CI object store: s3.sh, not `mc` None of these images ships MinIO's `mc` any more. The CI store behind diff --git a/keploy-ci-woodpecker-agent/Dockerfile b/keploy-ci-woodpecker-agent/Dockerfile new file mode 100644 index 0000000..3046a44 --- /dev/null +++ b/keploy-ci-woodpecker-agent/Dockerfile @@ -0,0 +1,71 @@ +# keploy-ci-woodpecker-agent: the Woodpecker CI agent, built from upstream's +# source at WOODPECKER_TAG with the patches in patches/ applied. +# Used by: the Linux Woodpecker agents (docker), in place of +# woodpeckerci/woodpecker-agent at the same version. +# +# Why: the v3.20.1 agent counts WOODPECKER_RETRY_TIMEOUT (2 minutes by default) +# from the moment an RPC began. Wait() stays open for the whole workflow, so +# the first dropped connection after two minutes gets no retry and the agent +# cancels every workflow it is running, with every step marked killed. +# 0001 is woodpecker-ci/woodpecker#7111 (for issue #7110), still open +# upstream, applied to v3.20.1; 0002 adds the tests for the failure as it +# happened here. When an upstream release carries the fix, go back to +# upstream's image and delete this one. +# +# Follows upstream's docker/Dockerfile.agent.multiarch: the agent is built on +# the build platform for the target, and the final image is scratch. +FROM --platform=$BUILDPLATFORM golang:1.27.3-bookworm@sha256:972b4110ba0f47539a975c31e52c64765e1ff19f2d74469ae4a595c6676e80a5 AS build + +ARG WOODPECKER_TAG=v3.20.1 +ARG WOODPECKER_COMMIT=3f1bb0bd0db28e410ad797034d75780116122c91 +# Bump with every change to patches/: the agent reports it as its version. +ARG KEPLOY_BUILD=keploy.1 + +RUN groupadd -g 1000 woodpecker && \ + useradd -u 1000 -g 1000 woodpecker && \ + mkdir -p /etc/woodpecker + +# Upstream's image carries the backward compatible timezone names too +# (US/Eastern, Asia/Calcutta...). Bookworm's tzdata still ships them; trixie, +# which upstream builds on, moved them to tzdata-legacy. +RUN apt-get update && \ + apt-get install -y --no-install-recommends tzdata && \ + test -e /usr/share/zoneinfo/US/Eastern && \ + rm -rf /usr/share/zoneinfo/right /var/lib/apt/lists/* + +# The tag must still name the commit the patches were made against. +RUN git clone --quiet --depth 1 --branch "$WOODPECKER_TAG" \ + https://github.com/woodpecker-ci/woodpecker.git /src && \ + got="$(git -C /src rev-parse HEAD)" && \ + { [ "$got" = "$WOODPECKER_COMMIT" ] || { echo "$WOODPECKER_TAG is $got, not $WOODPECKER_COMMIT" >&2; exit 1; }; } + +WORKDIR /src +COPY patches/ /patches/ +RUN git apply --index /patches/*.patch + +# The patched package's tests, on the build platform, so a patch that no +# longer does what it says fails the build here. +RUN go test -race -count=1 -timeout 120s -tags test ./agent/rpc/ + +ARG TARGETOS TARGETARCH +RUN make build-agent CI_COMMIT_TAG="${WOODPECKER_TAG}-${KEPLOY_BUILD}" CI_COMMIT_SHA="$WOODPECKER_COMMIT" + +FROM scratch AS stage + +COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt +COPY --from=build /usr/share/zoneinfo /usr/share/zoneinfo +COPY --from=build /etc/passwd /etc/passwd +COPY --from=build /etc/group /etc/group +COPY --from=build --chown=woodpecker:woodpecker /etc/woodpecker /etc + +FROM scratch +ENV GODEBUG=netdns=go +# Upstream's internal setting: tells the agent it runs inside a container. +ENV WOODPECKER_IN_CONTAINER=true +EXPOSE 3000 + +COPY --from=stage / / +COPY --from=build /src/dist/woodpecker-agent /bin/ + +HEALTHCHECK CMD ["/bin/woodpecker-agent", "ping"] +ENTRYPOINT ["/bin/woodpecker-agent"] diff --git a/keploy-ci-woodpecker-agent/patches/0001-fix-agent-count-the-retry-window-from-the-first-fail.patch b/keploy-ci-woodpecker-agent/patches/0001-fix-agent-count-the-retry-window-from-the-first-fail.patch new file mode 100644 index 0000000..41cd53c --- /dev/null +++ b/keploy-ci-woodpecker-agent/patches/0001-fix-agent-count-the-retry-window-from-the-first-fail.patch @@ -0,0 +1,373 @@ +From 3ed40d1758afaad91fca0b5c06e1054e3f567428 Mon Sep 17 00:00:00 2001 +From: Thomas Baumeister +Date: Sun, 6 Sep 2026 15:25:36 +0200 +Subject: [PATCH 1/2] fix(agent): count the retry window from the first + failure, not from the start of a long poll + +WOODPECKER_RETRY_TIMEOUT was passed to backoff.WithMaxElapsedTime, which +measures from the moment Retry was called. Next() and Wait() are server-side +long polls that legitimately block for much longer than the window, so the +first transport error after an idle poll (typically a server restart) was +reported as "maximum elapsed time exceeded" without a single retry. For +Next() that is a spurious error log and a 5 s detour through the runner's +retry loop; for Wait() the error cancels the running workflow. + +failureWindowBackOff starts the clock at the first failure of a streak and +stops the policy once the window has elapsed since then. An attempt that +outlived the window (a long poll that reconnected and broke again later) +starts a new streak instead of extending the old one. Which errors mean +"connection lost" is unchanged, and the give-up cause stays +backoff.ErrMaxElapsedTime. +--- + agent/rpc/client_grpc.go | 124 +++++++++++++++++++++----- + agent/rpc/client_grpc_test.go | 159 ++++++++++++++++++++++++++++++++++ + 2 files changed, 260 insertions(+), 23 deletions(-) + +diff --git a/agent/rpc/client_grpc.go b/agent/rpc/client_grpc.go +index 968f400b..d5247a64 100644 +--- a/agent/rpc/client_grpc.go ++++ b/agent/rpc/client_grpc.go +@@ -56,9 +56,10 @@ type client struct { + client proto.WoodpeckerClient + conn *grpc.ClientConn + logs chan *proto.LogEntry +- // connectionRetryTimeout is the maximum time to wait for a connection to be +- // restored before the agent gives up and exits. Zero means infinite. +- // Maps directly onto backoff.WithMaxElapsedTime. ++ // connectionRetryTimeout bounds how long an RPC keeps failing before it ++ // gives up. Zero means infinite. The clock starts at the first failure, not ++ // when the RPC was issued (see failureWindowBackOff). Whether a give-up ++ // ends the agent is decided by the callers (cmd/agent/core/agent.go). + connectionRetryTimeout time.Duration + // logEntryBufferSize sets the buffer size before the log reader is blocking. + // If you have enough memory and log bursts, set it higher. +@@ -111,16 +112,71 @@ func (c *client) IsConnected() bool { + return state == connectivity.Ready || state == connectivity.Idle + } + +-// retryOpts returns the backoff options used for every retry loop in this +-// file. The exponential backoff parameters preserve the original tuning +-// (10 ms initial, 10 s cap), and connectionRetryTimeout is wired straight into +-// WithMaxElapsedTime — when it elapses, backoff.Retry returns the last error, +-// which we translate into ErrConnectionLost in retryRPC. +-func (c *client) retryOpts(op string) []backoff.RetryOption { +- b := backoff.NewExponentialBackOff() +- b.MaxInterval = 10 * time.Second //nolint:mnd +- b.InitialInterval = 10 * time.Millisecond //nolint:mnd ++// failureWindowBackOff wraps the exponential policy and stops it once the ++// operation has been failing for longer than window, counted from the first ++// failure of the current streak. ++// ++// The library's backoff.WithMaxElapsedTime cannot express this: it counts from ++// the moment backoff.Retry was called, but Next and Wait are long polls that ++// legitimately block for far longer than the window before anything goes ++// wrong. Counted from the start of the call, the first transport error after ++// such a poll (typically a server restart) exceeded the window immediately and ++// gave up without a single retry. ++type failureWindowBackOff struct { ++ backoff.BackOff ++ window time.Duration ++ now func() time.Time ++ firstFailure time.Time ++} + ++// newFailureWindowBackOff keeps the original tuning of the exponential policy ++// (10 ms initial, 10 s cap) and bounds a failure streak by window. ++func newFailureWindowBackOff(window time.Duration) *failureWindowBackOff { ++ exp := backoff.NewExponentialBackOff() ++ exp.MaxInterval = 10 * time.Second //nolint:mnd ++ exp.InitialInterval = 10 * time.Millisecond //nolint:mnd ++ return &failureWindowBackOff{BackOff: exp, window: window, now: time.Now} ++} ++ ++// attemptFailed records a failed attempt that began at started. An attempt ++// that stayed alive for longer than the window evidently had a working ++// connection for that long (a long poll that was reconnected and broke again ++// later), so its failure starts a new streak instead of extending one that ++// began before the attempt. ++func (b *failureWindowBackOff) attemptFailed(started time.Time) { ++ now := b.now() ++ if b.window > 0 && now.Sub(started) > b.window { ++ b.Reset() ++ } ++ if b.firstFailure.IsZero() { ++ b.firstFailure = now ++ } ++} ++ ++// NextBackOff returns backoff.Stop once the window has elapsed since the first ++// failure of the current streak. A zero window never stops. ++func (b *failureWindowBackOff) NextBackOff() time.Duration { ++ if b.firstFailure.IsZero() { ++ b.firstFailure = b.now() ++ } ++ next := b.BackOff.NextBackOff() ++ if b.window > 0 && b.now().Sub(b.firstFailure)+next > b.window { ++ return backoff.Stop ++ } ++ return next ++} ++ ++// Reset forgets the current failure streak and resets the wrapped policy. ++func (b *failureWindowBackOff) Reset() { ++ b.firstFailure = time.Time{} ++ b.BackOff.Reset() ++} ++ ++// retryOpts returns the backoff options used for every retry loop in this ++// file. The retry window is enforced by b (a failureWindowBackOff); when it ++// elapses, backoff.Retry returns the last error, which retryRPC translates ++// into ErrConnectionLost if the server was unreachable. ++func (c *client) retryOpts(op string, b backoff.BackOff) []backoff.RetryOption { + notify := func(err error, next time.Duration) { + // The "too_many_pings" GOAWAY is well-known noise; demote to trace. + // See https://github.com/woodpecker-ci/woodpecker/issues/717 +@@ -137,19 +193,24 @@ func (c *client) retryOpts(op string) []backoff.RetryOption { + + return []backoff.RetryOption{ + backoff.WithBackOff(b), +- backoff.WithMaxElapsedTime(c.connectionRetryTimeout), ++ // The window lives in b; 0 disables the library's own limit, which ++ // counts from the start of the call and would otherwise default to ++ // 15 minutes. ++ backoff.WithMaxElapsedTime(0), + backoff.WithNotify(notify), + } + } + + // retryRPC is the workhorse used by every RPC method in this file. It runs op +-// under backoff.Retry with the standard options, and translates the few +-// special outcomes the callers care about: ++// under backoff.Retry with the standard options, tells the retry policy how ++// long each failed attempt lived, and translates the few special outcomes the ++// callers care about: + // +-// - op succeeds -> (result, nil) +-// - ctx canceled -> (zero, nil) same contract as before +-// - MaxElapsedTime hit -> (zero, ErrConnectionLost) +-// - permanent (fatal) -> (zero, underlying err) ++// - op succeeds -> (result, nil) ++// - ctx canceled -> (zero, nil) same contract as before ++// - retry window hit, not connected -> (zero, ErrConnectionLost) ++// - retry window hit, other error -> (zero, err wrapping backoff.ErrMaxElapsedTime) ++// - permanent (fatal) -> (zero, underlying err) + // + // The op closure is responsible for: + // - returning errNotConnected when IsConnected() is false (Retry will sleep +@@ -157,7 +218,17 @@ func (c *client) retryOpts(op string) []backoff.RetryOption { + // - returning backoff.Permanent(err) for unrecoverable gRPC codes + // - returning the raw error for retryable codes (Aborted/DataLoss/...) + func retryRPC[T any](ctx context.Context, c *client, opName string, op backoff.Operation[T]) (T, error) { +- res, err := backoff.Retry(ctx, op, c.retryOpts(opName)...) ++ b := newFailureWindowBackOff(c.connectionRetryTimeout) ++ attempt := func() (T, error) { ++ started := b.now() ++ res, err := op() ++ if err != nil { ++ b.attemptFailed(started) ++ } ++ return res, err ++ } ++ ++ res, err := backoff.Retry(ctx, attempt, c.retryOpts(opName, b)...) + if err == nil { + return res, nil + } +@@ -173,9 +244,16 @@ func retryRPC[T any](ctx context.Context, c *client, opName string, op backoff.O + + re := backoff.AsRetryError(err) + +- // MaxElapsedTime exhausted while we were still in errNotConnected — give up. ++ // The window is enforced by the policy, which Retry reports as ++ // ErrExhausted. Surface it as ErrMaxElapsedTime, the cause callers and log ++ // readers know from before the window moved into the policy. ++ if errors.Is(re.Cause, backoff.ErrExhausted) { ++ err = &backoff.RetryError{LastErr: re.LastErr, Cause: backoff.ErrMaxElapsedTime} ++ } ++ ++ // Retry window exhausted while we were still in errNotConnected — give up. + if errors.Is(re.LastErr, errNotConnected) { +- log.Error().Msg("grpc: connection lost, giving up") ++ log.Error().Msgf("grpc: %s(): connection lost, giving up", opName) + return zero, ErrConnectionLost + } + +@@ -422,7 +500,7 @@ func (c *client) sendLogs(ctx context.Context, entries []*proto.LogEntry) error + + // sendLogs intentionally does not gate on IsConnected — the original code + // didn't either. backoff.Retry will keep trying through transient transport +- // errors until MaxElapsedTime elapses. ++ // errors until the retry window elapses. + _, err := retryRPC(ctx, c, "log", func() (*proto.Empty, error) { + r, err := c.client.Log(ctx, req) + return r, classifyRPCErr(ctx, err) +diff --git a/agent/rpc/client_grpc_test.go b/agent/rpc/client_grpc_test.go +index 52c83b41..d1d03241 100644 +--- a/agent/rpc/client_grpc_test.go ++++ b/agent/rpc/client_grpc_test.go +@@ -174,3 +174,162 @@ func TestProcessLogsFlushesContinuousStream(t *testing.T) { + synctest.Wait() + }) + } ++ ++// fakeClock drives failureWindowBackOff without sleeping. ++type fakeClock struct{ t time.Time } ++ ++func (f *fakeClock) now() time.Time { return f.t } ++func (f *fakeClock) advance(d time.Duration) { f.t = f.t.Add(d) } ++func newFakeWindow(window time.Duration) (*failureWindowBackOff, *fakeClock) { ++ clock := &fakeClock{t: time.Unix(1_700_000_000, 0)} ++ b := &failureWindowBackOff{BackOff: backoff.NewConstantBackOff(time.Millisecond), window: window, now: clock.now} ++ return b, clock ++} ++ ++func TestFailureWindowBackOff(t *testing.T) { ++ t.Parallel() ++ ++ t.Run("delegates until the window elapses since the first failure", func(t *testing.T) { ++ t.Parallel() ++ ++ b, clock := newFakeWindow(time.Minute) ++ b.attemptFailed(clock.now()) ++ assert.Equal(t, time.Millisecond, b.NextBackOff()) ++ clock.advance(59 * time.Second) ++ assert.Equal(t, time.Millisecond, b.NextBackOff()) ++ clock.advance(2 * time.Second) ++ assert.Equal(t, backoff.Stop, b.NextBackOff()) ++ }) ++ ++ t.Run("reset starts over", func(t *testing.T) { ++ t.Parallel() ++ ++ b, clock := newFakeWindow(time.Minute) ++ b.attemptFailed(clock.now()) ++ clock.advance(2 * time.Minute) ++ assert.Equal(t, backoff.Stop, b.NextBackOff()) ++ b.Reset() ++ assert.Equal(t, time.Millisecond, b.NextBackOff()) ++ }) ++ ++ t.Run("an attempt that outlived the window starts a new streak", func(t *testing.T) { ++ t.Parallel() ++ ++ b, clock := newFakeWindow(time.Minute) ++ b.attemptFailed(clock.now()) // quick failure: streak begins ++ clock.advance(3 * time.Hour) // the next attempt reconnected and long-polled ++ b.attemptFailed(clock.now().Add(-3 * time.Hour)) ++ assert.Equal(t, time.Millisecond, b.NextBackOff(), "failure of a long-lived attempt must be retried") ++ ++ clock.advance(30 * time.Second) ++ b.attemptFailed(clock.now().Add(-time.Second)) // quick failure inside the new streak ++ assert.Equal(t, time.Millisecond, b.NextBackOff()) ++ clock.advance(31 * time.Second) ++ b.attemptFailed(clock.now().Add(-time.Second)) ++ assert.Equal(t, backoff.Stop, b.NextBackOff(), "new streak is bounded by the window too") ++ }) ++ ++ t.Run("zero window never stops", func(t *testing.T) { ++ t.Parallel() ++ ++ b, clock := newFakeWindow(0) ++ b.attemptFailed(clock.now()) ++ clock.advance(24 * time.Hour) ++ assert.Equal(t, time.Millisecond, b.NextBackOff()) ++ }) ++} ++ ++func TestRetryRPCWindowStartsAtFirstFailure(t *testing.T) { ++ t.Parallel() ++ ++ // A long poll (Next/Wait) blocks longer than the whole retry window before ++ // it fails for the first time. The failure must still be retried. ++ ctx := context.Background() ++ c := &client{connectionRetryTimeout: 200 * time.Millisecond} ++ var attempts int ++ ++ _, err := retryRPC(ctx, c, "test", func() (struct{}, error) { ++ attempts++ ++ if attempts == 1 { ++ time.Sleep(2 * c.connectionRetryTimeout) ++ return struct{}{}, classifyRPCErr(ctx, status.Error(codes.Unavailable, "server restarting")) ++ } ++ return struct{}{}, nil ++ }) ++ ++ require.NoError(t, err) ++ assert.Equal(t, 2, attempts) ++} ++ ++func TestRetryRPCLongAttemptStartsNewFailureStreak(t *testing.T) { ++ t.Parallel() ++ ++ // Within one retry loop: a quick failure starts a streak, the next attempt ++ // reconnects and blocks for longer than the whole window (a long poll) ++ // before it fails again. That failure must start a new streak and be ++ // retried instead of exhausting the old one. ++ ctx := context.Background() ++ c := &client{connectionRetryTimeout: 200 * time.Millisecond} ++ var attempts int ++ ++ _, err := retryRPC(ctx, c, "test", func() (struct{}, error) { ++ attempts++ ++ switch attempts { ++ case 1: ++ return struct{}{}, classifyRPCErr(ctx, status.Error(codes.Unavailable, "server restarting")) ++ case 2: ++ time.Sleep(2 * c.connectionRetryTimeout) ++ return struct{}{}, classifyRPCErr(ctx, status.Error(codes.Unavailable, "server restarting again")) ++ default: ++ return struct{}{}, nil ++ } ++ }) ++ ++ require.NoError(t, err) ++ assert.Equal(t, 3, attempts) ++} ++ ++func TestRetryRPCGivesUpAfterWindow(t *testing.T) { ++ t.Parallel() ++ ++ tc := []struct { ++ name string ++ err error ++ classify bool ++ wantConnectionLost bool ++ }{ ++ // the guard error is returned by the operations as-is ++ {"not connected guard", errNotConnected, false, true}, ++ {"transport unavailable", status.Error(codes.Unavailable, "connection refused"), true, false}, ++ {"unauthenticated", status.Error(codes.Unauthenticated, "expired token"), true, false}, ++ } ++ ++ for _, tt := range tc { ++ t.Run(tt.name, func(t *testing.T) { ++ t.Parallel() ++ ++ ctx := context.Background() ++ c := &client{connectionRetryTimeout: 200 * time.Millisecond} ++ var attempts int ++ started := time.Now() ++ ++ _, err := retryRPC(ctx, c, "test", func() (struct{}, error) { ++ attempts++ ++ if tt.classify { ++ return struct{}{}, classifyRPCErr(ctx, tt.err) ++ } ++ return struct{}{}, tt.err ++ }) ++ ++ require.Error(t, err) ++ assert.Greater(t, attempts, 1, "must retry before giving up") ++ assert.Less(t, time.Since(started), 3*c.connectionRetryTimeout, "must give up close to the window") ++ if tt.wantConnectionLost { ++ assert.ErrorIs(t, err, ErrConnectionLost) ++ } else { ++ assert.ErrorIs(t, err, backoff.ErrMaxElapsedTime) ++ assert.NotErrorIs(t, err, ErrConnectionLost) ++ } ++ }) ++ } ++} +-- +2.55.0 + diff --git a/keploy-ci-woodpecker-agent/patches/0002-test-agent-rows-for-a-dropped-Wait-poll-and-the-retr.patch b/keploy-ci-woodpecker-agent/patches/0002-test-agent-rows-for-a-dropped-Wait-poll-and-the-retr.patch new file mode 100644 index 0000000..1cf7f31 --- /dev/null +++ b/keploy-ci-woodpecker-agent/patches/0002-test-agent-rows-for-a-dropped-Wait-poll-and-the-retr.patch @@ -0,0 +1,86 @@ +From 316dbe761f8412c30abcd49c087a176e55e61b3c Mon Sep 17 00:00:00 2001 +From: slayerjain +Date: Fri, 6 Nov 2026 09:01:33 +0530 +Subject: [PATCH 2/2] test(agent): rows for a dropped Wait poll and the retry + window's edges + +Signed-off-by: slayerjain +--- + agent/rpc/client_grpc_test.go | 64 +++++++++++++++++++++++++++++++++++ + 1 file changed, 64 insertions(+) + +diff --git a/agent/rpc/client_grpc_test.go b/agent/rpc/client_grpc_test.go +index d1d03241..a7208867 100644 +--- a/agent/rpc/client_grpc_test.go ++++ b/agent/rpc/client_grpc_test.go +@@ -333,3 +333,67 @@ func TestRetryRPCGivesUpAfterWindow(t *testing.T) { + }) + } + } ++ ++// A Wait() long poll stays open for the whole workflow. When its transport ++// drops once (here the GOAWAY a server sends after too many keepalive pings) ++// after the poll has been open longer than the retry timeout, the agent must ++// reconnect and poll again. Before the fix the first failure was final and ++// the runner canceled the workflow. ++func TestRetryRPCWaitSurvivesTransportDropAfterLongPoll(t *testing.T) { ++ t.Parallel() ++ ++ ctx := context.Background() ++ c := &client{connectionRetryTimeout: 300 * time.Millisecond} ++ var calls int ++ ++ canceled, err := retryRPC(ctx, c, "wait", func() (bool, error) { ++ calls++ ++ if calls == 1 { ++ time.Sleep(2 * c.connectionRetryTimeout) // the poll outlives the window ++ drop := status.Error(codes.Unavailable, `closing transport due to: connection error: desc = "error reading from server: EOF", received prior goaway: code: ENHANCE_YOUR_CALM, debug data: "too_many_pings"`) ++ return false, classifyRPCErr(ctx, drop) ++ } ++ return false, nil ++ }) ++ ++ require.NoError(t, err) ++ assert.False(t, canceled) ++ assert.Equal(t, 2, calls) ++} ++ ++// With no window (WOODPECKER_RETRY_TIMEOUT=0) the agent retries forever. Its ++// interval must still grow while the server stays away, not start again at ++// the initial 10 ms after every failed attempt. ++func TestFailureWindowBackOffZeroWindowKeepsGrowing(t *testing.T) { ++ t.Parallel() ++ ++ clock := &fakeClock{t: time.Unix(1_700_000_000, 0)} ++ b := newFailureWindowBackOff(0) ++ b.now = clock.now ++ ++ var next time.Duration ++ for range 10 { ++ started := clock.now() ++ clock.advance(time.Millisecond) // the attempt fails after 1 ms ++ b.attemptFailed(started) ++ next = b.NextBackOff() ++ require.NotEqual(t, backoff.Stop, next) ++ clock.advance(next) ++ } ++ ++ // 10 ms * 1.5^9 is about 384 ms; the randomization keeps it above half that. ++ assert.Greater(t, next, 100*time.Millisecond) ++} ++ ++// The agent gives up before a wait that would end past the window, not one ++// interval (up to 10 s) after it. ++func TestFailureWindowBackOffStopsBeforeAWaitPastTheWindow(t *testing.T) { ++ t.Parallel() ++ ++ clock := &fakeClock{t: time.Unix(1_700_000_000, 0)} ++ b := &failureWindowBackOff{BackOff: backoff.NewConstantBackOff(60 * time.Millisecond), window: 100 * time.Millisecond, now: clock.now} ++ ++ assert.Equal(t, 60*time.Millisecond, b.NextBackOff()) // 0 + 60 ms fits ++ clock.advance(60 * time.Millisecond) ++ assert.Equal(t, backoff.Stop, b.NextBackOff()) // 60 + 60 ms would end past 100 ms ++} +-- +2.55.0 + From 946450c09e012a24578d80fb69dece07bb34239c Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 6 Nov 2026 10:50:36 +0530 Subject: [PATCH 2/3] fix(woodpecker-agent): start the retry window over after a reconnect With upstream's fix alone, the window counted from the first failure of a streak, and a streak ended only after an attempt that stayed up for longer than the whole window. A drop soon after the agent had reconnected still counted against the outage before it: a server down for 60 s whose new connection dropped 90 s later, or drops after connections that each worked for less than the window, made the agent give up and cancel its workflows. Patch 0003 counts the times the connection became Ready, from a goroutine that watches its state and from every failed attempt. gRPC reports Ready only after a new transport's handshake with the server, so a count that moved between two failures proves a reconnection, and that failure starts a new window. The interval keeps growing, so a server that accepts connections and drops them at once is not called every 10 ms. Patch 0002 gains rows on the fake clock: a Wait() open for 30 minutes under the default 2 minute window, past the backoff library's own 15 minute default, survives one drop; a real outage still ends within the window; an attempt that stayed up for 1.5 windows starts a new streak and resets the interval. Signed-off-by: slayerjain --- README.md | 24 +- keploy-ci-woodpecker-agent/Dockerfile | 5 +- ...the-retry-window-from-the-first-fail.patch | 2 +- ...for-a-dropped-Wait-poll-and-the-retr.patch | 144 ++++- ...the-retry-window-over-once-the-agent.patch | 546 ++++++++++++++++++ 5 files changed, 701 insertions(+), 20 deletions(-) create mode 100644 keploy-ci-woodpecker-agent/patches/0003-fix-agent-start-the-retry-window-over-once-the-agent.patch diff --git a/README.md b/README.md index 4dc7101..d177ce0 100644 --- a/README.md +++ b/README.md @@ -109,12 +109,20 @@ default) from the moment an RPC began, not from its first failure. `Wait()` stays open for the whole workflow, so when the connection to the server drops once after that, the agent does not retry: it cancels every workflow it is running, and every step shows as killed. Patch 0001 is upstream's open fix, -woodpecker-ci/woodpecker#7111 (issue #7110), applied to v3.20.1. Patch 0002 -adds tests for the failure as it happened on our agents: a `Wait()` that -outlived the window and then got the server's `too_many_pings` GOAWAY, and an -agent with no window (`WOODPECKER_RETRY_TIMEOUT=0`) whose retry interval must -keep growing. The build runs the patched package's tests and fails if one -fails. +woodpecker-ci/woodpecker#7111 (issue #7110), applied to v3.20.1: the window +counts from the first failure. Patch 0002 adds tests for the failure as it +happened on our agents: a `Wait()` that outlived the window and then got the +server's `too_many_pings` GOAWAY, at production scale too (a 2 minute window +and a poll open for 30 minutes), and the window's edges. Patch 0003 starts the +window over once the agent has reconnected, so a drop soon after a +reconnection (a server restart followed by another drop, or a storm of +GOAWAYs) is retried instead of being counted against the outage before it. +The build runs the patched package's tests and fails if one fails. + +An outage longer than the window still ends with the agent giving up, and +the runner then cancels every workflow on the agent, so choose +`WOODPECKER_RETRY_TIMEOUT` longer than the outages to ride out, or 0 to +retry forever. **Contents:** the `woodpecker-agent` binary (reporting version `-keploy.`), CA certificates, timezone data, and upstream's @@ -127,8 +135,8 @@ natively and do not use this image. image: ghcr.io/keploy/keploy-ci:woodpecker-agent- ``` -When an upstream release carries the fix, move the agents back to upstream's -image at that release and delete this directory. +When an upstream release carries these fixes, move the agents back to +upstream's image at that release and delete this directory. Tag: `ghcr.io/keploy/keploy-ci:woodpecker-agent-`. diff --git a/keploy-ci-woodpecker-agent/Dockerfile b/keploy-ci-woodpecker-agent/Dockerfile index 3046a44..0ba6162 100644 --- a/keploy-ci-woodpecker-agent/Dockerfile +++ b/keploy-ci-woodpecker-agent/Dockerfile @@ -9,8 +9,9 @@ # cancels every workflow it is running, with every step marked killed. # 0001 is woodpecker-ci/woodpecker#7111 (for issue #7110), still open # upstream, applied to v3.20.1; 0002 adds the tests for the failure as it -# happened here. When an upstream release carries the fix, go back to -# upstream's image and delete this one. +# happened here; 0003 starts the window over once the agent has reconnected, +# so a drop soon after a reconnection is retried too. When an upstream release +# carries these fixes, go back to upstream's image and delete this one. # # Follows upstream's docker/Dockerfile.agent.multiarch: the agent is built on # the build platform for the target, and the final image is scratch. diff --git a/keploy-ci-woodpecker-agent/patches/0001-fix-agent-count-the-retry-window-from-the-first-fail.patch b/keploy-ci-woodpecker-agent/patches/0001-fix-agent-count-the-retry-window-from-the-first-fail.patch index 41cd53c..d2bf65e 100644 --- a/keploy-ci-woodpecker-agent/patches/0001-fix-agent-count-the-retry-window-from-the-first-fail.patch +++ b/keploy-ci-woodpecker-agent/patches/0001-fix-agent-count-the-retry-window-from-the-first-fail.patch @@ -1,7 +1,7 @@ From 3ed40d1758afaad91fca0b5c06e1054e3f567428 Mon Sep 17 00:00:00 2001 From: Thomas Baumeister Date: Sun, 6 Sep 2026 15:25:36 +0200 -Subject: [PATCH 1/2] fix(agent): count the retry window from the first +Subject: [PATCH 1/3] fix(agent): count the retry window from the first failure, not from the start of a long poll WOODPECKER_RETRY_TIMEOUT was passed to backoff.WithMaxElapsedTime, which diff --git a/keploy-ci-woodpecker-agent/patches/0002-test-agent-rows-for-a-dropped-Wait-poll-and-the-retr.patch b/keploy-ci-woodpecker-agent/patches/0002-test-agent-rows-for-a-dropped-Wait-poll-and-the-retr.patch index 1cf7f31..e5e6248 100644 --- a/keploy-ci-woodpecker-agent/patches/0002-test-agent-rows-for-a-dropped-Wait-poll-and-the-retr.patch +++ b/keploy-ci-woodpecker-agent/patches/0002-test-agent-rows-for-a-dropped-Wait-poll-and-the-retr.patch @@ -1,23 +1,40 @@ -From 316dbe761f8412c30abcd49c087a176e55e61b3c Mon Sep 17 00:00:00 2001 +From 14ba8d55b7a955511f3839c02b5ef238787606c5 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 6 Nov 2026 09:01:33 +0530 -Subject: [PATCH 2/2] test(agent): rows for a dropped Wait poll and the retry +Subject: [PATCH 2/3] test(agent): rows for a dropped Wait poll and the retry window's edges +- a Wait() that outlived the window and then got the too_many_pings + GOAWAY is retried, at test scale and, on the fake clock, at production + scale (2 minute window, a poll open for 30 minutes, past the backoff + library's own 15 minute default); +- a real outage still ends within the window; +- an attempt that stayed up for 1.5 windows starts a new streak; +- that attempt also resets the interval to 10 ms; +- with a zero window the interval keeps growing; +- the agent gives up before a wait that would end past the window. + Signed-off-by: slayerjain --- - agent/rpc/client_grpc_test.go | 64 +++++++++++++++++++++++++++++++++++ - 1 file changed, 64 insertions(+) + agent/rpc/client_grpc_test.go | 180 ++++++++++++++++++++++++++++++++++ + 1 file changed, 180 insertions(+) diff --git a/agent/rpc/client_grpc_test.go b/agent/rpc/client_grpc_test.go -index d1d03241..a7208867 100644 +index d1d03241..a7821e61 100644 --- a/agent/rpc/client_grpc_test.go +++ b/agent/rpc/client_grpc_test.go -@@ -333,3 +333,67 @@ func TestRetryRPCGivesUpAfterWindow(t *testing.T) { +@@ -333,3 +333,183 @@ func TestRetryRPCGivesUpAfterWindow(t *testing.T) { }) } } + ++// errGoawayDrop is the error a Wait() poll got when the server sent the GOAWAY ++// for too many keepalive pings, as the agents logged it. ++var errGoawayDrop = status.Error(codes.Unavailable, `closing transport due to: connection error: desc = "error reading from server: EOF", received prior goaway: code: ENHANCE_YOUR_CALM, debug data: "too_many_pings"`) ++ ++// errStillRetrying ends a row's retry loop that should have given up long ago. ++var errStillRetrying = errors.New("still retrying 10 minutes into the outage") ++ +// A Wait() long poll stays open for the whole workflow. When its transport +// drops once (here the GOAWAY a server sends after too many keepalive pings) +// after the poll has been open longer than the retry timeout, the agent must @@ -26,7 +43,7 @@ index d1d03241..a7208867 100644 +func TestRetryRPCWaitSurvivesTransportDropAfterLongPoll(t *testing.T) { + t.Parallel() + -+ ctx := context.Background() ++ ctx := t.Context() + c := &client{connectionRetryTimeout: 300 * time.Millisecond} + var calls int + @@ -34,8 +51,7 @@ index d1d03241..a7208867 100644 + calls++ + if calls == 1 { + time.Sleep(2 * c.connectionRetryTimeout) // the poll outlives the window -+ drop := status.Error(codes.Unavailable, `closing transport due to: connection error: desc = "error reading from server: EOF", received prior goaway: code: ENHANCE_YOUR_CALM, debug data: "too_many_pings"`) -+ return false, classifyRPCErr(ctx, drop) ++ return false, classifyRPCErr(ctx, errGoawayDrop) + } + return false, nil + }) @@ -81,6 +97,116 @@ index d1d03241..a7208867 100644 + clock.advance(60 * time.Millisecond) + assert.Equal(t, backoff.Stop, b.NextBackOff()) // 60 + 60 ms would end past 100 ms +} ++ ++// The same at production scale, on the fake clock: the default 2 minute window ++// and a Wait() that has been open for 30 minutes, longer than the backoff ++// library's own 15 minute default limit too. One drop is retried. ++func TestRetryRPCWaitOpen30MinutesSurvivesOneDrop(t *testing.T) { ++ synctest.Test(t, func(t *testing.T) { ++ ctx := t.Context() ++ c := &client{connectionRetryTimeout: 2 * time.Minute} ++ var calls int ++ ++ _, err := retryRPC(ctx, c, "wait", func() (bool, error) { ++ calls++ ++ if calls == 1 { ++ time.Sleep(30 * time.Minute) ++ return false, classifyRPCErr(ctx, errGoawayDrop) ++ } ++ return false, nil ++ }) ++ ++ require.NoError(t, err) ++ assert.Equal(t, 2, calls) ++ }) ++} ++ ++// The window still ends a real outage: after a 30 minute Wait() the server ++// goes away for good. The agent gives up after failing for at least the window ++// minus one interval (at most 15 s), and never after the window. ++func TestRetryRPCGivesUpWithinTheWindowOfARealOutage(t *testing.T) { ++ synctest.Test(t, func(t *testing.T) { ++ ctx := t.Context() ++ c := &client{connectionRetryTimeout: 2 * time.Minute} ++ var down time.Time ++ var calls int ++ ++ _, err := retryRPC(ctx, c, "wait", func() (bool, error) { ++ calls++ ++ switch { ++ case calls == 1: ++ time.Sleep(30 * time.Minute) ++ down = time.Now() ++ return false, classifyRPCErr(ctx, errGoawayDrop) ++ case time.Since(down) > 10*time.Minute: ++ return false, backoff.Permanent(errStillRetrying) ++ } ++ return false, errNotConnected ++ }) ++ ++ require.ErrorIs(t, err, ErrConnectionLost) ++ failing := time.Since(down) ++ assert.GreaterOrEqual(t, failing, 100*time.Second) ++ assert.LessOrEqual(t, failing, 2*time.Minute) ++ }) ++} ++ ++// An attempt that stayed up for longer than the window starts a new streak. ++// Here a quick failure is followed by a Wait() that ran for 3 minutes, less ++// than twice the 2 minute window, before it failed too. That failure is ++// retried. ++func TestRetryRPCAttemptLongerThanTheWindowStartsNewStreak(t *testing.T) { ++ synctest.Test(t, func(t *testing.T) { ++ ctx := t.Context() ++ c := &client{connectionRetryTimeout: 2 * time.Minute} ++ var calls int ++ ++ _, err := retryRPC(ctx, c, "wait", func() (bool, error) { ++ calls++ ++ switch calls { ++ case 1: ++ return false, classifyRPCErr(ctx, status.Error(codes.Unavailable, "connection refused")) ++ case 2: ++ time.Sleep(3 * time.Minute) ++ return false, classifyRPCErr(ctx, errGoawayDrop) ++ default: ++ return false, nil ++ } ++ }) ++ ++ require.NoError(t, err) ++ assert.Equal(t, 3, calls) ++ }) ++} ++ ++// newSteadyExponential is the agent's exponential policy without the ++// randomization, so a row can check its intervals exactly. ++func newSteadyExponential() *backoff.ExponentialBackOff { ++ exp := backoff.NewExponentialBackOff() ++ exp.InitialInterval = 10 * time.Millisecond ++ exp.MaxInterval = 10 * time.Second ++ exp.RandomizationFactor = 0 ++ return exp ++} ++ ++// After an attempt that outlived the window, the interval starts over at ++// 10 ms too, so the first retry after a long Wait() is not held back by an ++// earlier streak's interval. ++func TestFailureWindowBackOffLongAttemptResetsTheInterval(t *testing.T) { ++ t.Parallel() ++ ++ clock := &fakeClock{t: time.Unix(1_700_000_000, 0)} ++ b := &failureWindowBackOff{BackOff: newSteadyExponential(), window: time.Minute, now: clock.now} ++ for range 5 { ++ b.attemptFailed(clock.now()) ++ clock.advance(b.NextBackOff()) ++ } ++ ++ started := clock.now() ++ clock.advance(2 * time.Minute) ++ b.attemptFailed(started) ++ assert.Equal(t, 10*time.Millisecond, b.NextBackOff()) ++} -- 2.55.0 diff --git a/keploy-ci-woodpecker-agent/patches/0003-fix-agent-start-the-retry-window-over-once-the-agent.patch b/keploy-ci-woodpecker-agent/patches/0003-fix-agent-start-the-retry-window-over-once-the-agent.patch new file mode 100644 index 0000000..d89ec22 --- /dev/null +++ b/keploy-ci-woodpecker-agent/patches/0003-fix-agent-start-the-retry-window-over-once-the-agent.patch @@ -0,0 +1,546 @@ +From 9dc61d4899c3ac0aa909658a42c15e6f8b9d7857 Mon Sep 17 00:00:00 2001 +From: slayerjain +Date: Fri, 6 Nov 2026 10:20:48 +0530 +Subject: [PATCH 3/3] fix(agent): start the retry window over once the agent + has reconnected + +The window counts from the first failure of a streak, and a streak ended +only after an attempt that stayed up for longer than the whole window. +So a drop soon after the agent had reconnected was counted against an +outage that was already over: after a server restart (down for 60 s, +then a Wait() that ran for 90 s on the new connection and dropped), or +in a storm of GOAWAYs after connections that worked for less than the +window, the agent gave up and the runner canceled its workflows. + +The client now counts the times its connection became Ready, from a +goroutine that watches the state and from every failed attempt. gRPC +reports Ready only after a new transport has completed its handshake, so +a count that moved between two failures proves the agent reconnected in +between. That failure then starts a new window. The interval keeps +growing, so a server that accepts connections and drops them at once is +not called every 10 ms. Without a reconnection the window keeps counting +from the first failure, as before. + +Signed-off-by: slayerjain +--- + agent/rpc/client_grpc.go | 92 +++++++++- + agent/rpc/client_grpc_test.go | 333 ++++++++++++++++++++++++++++++++++ + 2 files changed, 420 insertions(+), 5 deletions(-) + +diff --git a/agent/rpc/client_grpc.go b/agent/rpc/client_grpc.go +index d5247a64..0079ff51 100644 +--- a/agent/rpc/client_grpc.go ++++ b/agent/rpc/client_grpc.go +@@ -19,6 +19,7 @@ import ( + "encoding/json" + "errors" + "strings" ++ "sync" + "time" + + "github.com/cenkalti/backoff/v7" +@@ -58,9 +59,13 @@ type client struct { + logs chan *proto.LogEntry + // connectionRetryTimeout bounds how long an RPC keeps failing before it + // gives up. Zero means infinite. The clock starts at the first failure, not +- // when the RPC was issued (see failureWindowBackOff). Whether a give-up +- // ends the agent is decided by the callers (cmd/agent/core/agent.go). ++ // when the RPC was issued, and starts over when the agent reconnects (see ++ // failureWindowBackOff). Whether a give-up ends the agent is decided by the ++ // callers (cmd/agent/core/agent.go). + connectionRetryTimeout time.Duration ++ // ready counts the connection's reconnections for the retry policy. Nil in ++ // a client made without NewGrpcClient. ++ ready *readyTracker + // logEntryBufferSize sets the buffer size before the log reader is blocking. + // If you have enough memory and log bursts, set it higher. + logEntryBufferSize int +@@ -78,8 +83,10 @@ func NewGrpcClient(ctx context.Context, conn *grpc.ClientConn, opts ...ClientOpt + } + + client.logs = make(chan *proto.LogEntry, client.logEntryBufferSize) // max memory use: buffer count * 1 MiB ++ client.ready = &readyTracker{conn: conn} + + go client.processLogs(ctx) ++ go client.ready.watch(ctx) + return client + } + +@@ -112,9 +119,68 @@ func (c *client) IsConnected() bool { + return state == connectivity.Ready || state == connectivity.Idle + } + ++// connState is the part of *grpc.ClientConn that readyTracker reads. ++type connState interface { ++ GetState() connectivity.State ++ WaitForStateChange(ctx context.Context, sourceState connectivity.State) bool ++} ++ ++// readyTracker counts the times the connection has become Ready. If the count ++// moved between two failed attempts, the agent reconnected to the server in ++// between: gRPC reports Ready only once a new transport has completed its ++// handshake with the server. ++type readyTracker struct { ++ conn connState ++ mu sync.Mutex ++ last connectivity.State ++ count uint64 ++} ++ ++// observe reads the connection's state and counts it if it is a Ready that the ++// previous read did not see. The state is read under the lock, so the reads of ++// the watcher and of failing RPCs are counted in the order they were made: a ++// Ready that a failure saw is not counted again when the watcher sees it late. ++func (r *readyTracker) observe() (uint64, connectivity.State) { ++ r.mu.Lock() ++ defer r.mu.Unlock() ++ ++ state := r.conn.GetState() ++ if state == connectivity.Ready && r.last != connectivity.Ready { ++ r.count++ ++ } ++ r.last = state ++ return r.count, state ++} ++ ++// watch reads the state after every change until ctx ends or the connection is ++// closed, so it counts a reconnection while a long poll is open, when no RPC ++// fails to read it. ++func (r *readyTracker) watch(ctx context.Context) { ++ for { ++ _, state := r.observe() ++ if state == connectivity.Shutdown { ++ return ++ } ++ if !r.conn.WaitForStateChange(ctx, state) { ++ return ++ } ++ } ++} ++ ++// readyCount reads the connection's state and returns its Ready count, or 0 ++// for a client with no connection to watch. ++func (c *client) readyCount() uint64 { ++ if c.ready == nil { ++ return 0 ++ } ++ count, _ := c.ready.observe() ++ return count ++} ++ + // failureWindowBackOff wraps the exponential policy and stops it once the + // operation has been failing for longer than window, counted from the first +-// failure of the current streak. ++// failure of the current streak. A streak ends when the agent reconnects to ++// the server (see readyCountAtFailure). + // + // The library's backoff.WithMaxElapsedTime cannot express this: it counts from + // the moment backoff.Retry was called, but Next and Wait are long polls that +@@ -127,6 +193,8 @@ type failureWindowBackOff struct { + window time.Duration + now func() time.Time + firstFailure time.Time ++ // readyCount is the connection's Ready count at the last failed attempt. ++ readyCount uint64 + } + + // newFailureWindowBackOff keeps the original tuning of the exponential policy +@@ -153,6 +221,18 @@ func (b *failureWindowBackOff) attemptFailed(started time.Time) { + } + } + ++// readyCountAtFailure takes the connection's Ready count at a failed attempt. ++// If it moved since the previous failure, the agent reconnected in between, so ++// this failure begins a new outage and the window starts over from it. The ++// interval keeps growing: a server that accepts connections and drops them at ++// once is called at the policy's growing interval, not every 10 ms. ++func (b *failureWindowBackOff) readyCountAtFailure(count uint64) { ++ if count != b.readyCount { ++ b.firstFailure = time.Time{} ++ } ++ b.readyCount = count ++} ++ + // NextBackOff returns backoff.Stop once the window has elapsed since the first + // failure of the current streak. A zero window never stops. + func (b *failureWindowBackOff) NextBackOff() time.Duration { +@@ -203,8 +283,9 @@ func (c *client) retryOpts(op string, b backoff.BackOff) []backoff.RetryOption { + + // retryRPC is the workhorse used by every RPC method in this file. It runs op + // under backoff.Retry with the standard options, tells the retry policy how +-// long each failed attempt lived, and translates the few special outcomes the +-// callers care about: ++// long each failed attempt lived and whether the agent reconnected since the ++// previous failure, and translates the few special outcomes the callers care ++// about: + // + // - op succeeds -> (result, nil) + // - ctx canceled -> (zero, nil) same contract as before +@@ -223,6 +304,7 @@ func retryRPC[T any](ctx context.Context, c *client, opName string, op backoff.O + started := b.now() + res, err := op() + if err != nil { ++ b.readyCountAtFailure(c.readyCount()) + b.attemptFailed(started) + } + return res, err +diff --git a/agent/rpc/client_grpc_test.go b/agent/rpc/client_grpc_test.go +index a7821e61..afe63aeb 100644 +--- a/agent/rpc/client_grpc_test.go ++++ b/agent/rpc/client_grpc_test.go +@@ -17,7 +17,10 @@ package rpc + import ( + "context" + "errors" ++ "net" ++ "runtime" + "sync" ++ "sync/atomic" + "testing" + "testing/synctest" + "time" +@@ -27,7 +30,10 @@ import ( + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" ++ "google.golang.org/grpc/connectivity" ++ "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" ++ "google.golang.org/grpc/test/bufconn" + + "go.woodpecker-ci.org/woodpecker/v3/rpc" + "go.woodpecker-ci.org/woodpecker/v3/rpc/proto" +@@ -513,3 +519,330 @@ func TestFailureWindowBackOffLongAttemptResetsTheInterval(t *testing.T) { + b.attemptFailed(started) + assert.Equal(t, 10*time.Millisecond, b.NextBackOff()) + } ++ ++// fakeConn is a connection whose state the test sets. Its channels belong to ++// the synctest bubble that made it, so a watcher waiting on it is durably ++// blocked. ++type fakeConn struct { ++ mu sync.Mutex ++ state connectivity.State ++ changed chan struct{} ++ // returnedFalse is set once WaitForStateChange has returned false, and ++ // waitedAfterFalse if it was called again after that. ++ returnedFalse atomic.Bool ++ waitedAfterFalse atomic.Bool ++} ++ ++// newFakeConn returns a connection that is Ready. ++func newFakeConn() *fakeConn { ++ return &fakeConn{state: connectivity.Ready, changed: make(chan struct{})} ++} ++ ++func (f *fakeConn) set(state connectivity.State) { ++ f.mu.Lock() ++ defer f.mu.Unlock() ++ if state == f.state { ++ return ++ } ++ f.state = state ++ close(f.changed) ++ f.changed = make(chan struct{}) ++} ++ ++func (f *fakeConn) GetState() connectivity.State { ++ f.mu.Lock() ++ defer f.mu.Unlock() ++ return f.state ++} ++ ++func (f *fakeConn) WaitForStateChange(ctx context.Context, source connectivity.State) bool { ++ if f.returnedFalse.Load() { ++ // The caller ignored the false it got: record that, and end the ++ // caller's goroutine instead of letting it spin. ++ f.waitedAfterFalse.Store(true) ++ runtime.Goexit() ++ } ++ ++ f.mu.Lock() ++ state, changed := f.state, f.changed ++ f.mu.Unlock() ++ if state != source { ++ return true ++ } ++ select { ++ case <-ctx.Done(): ++ f.returnedFalse.Store(true) ++ return false ++ case <-changed: ++ return true ++ } ++} ++ ++// newWatchedClient returns a client whose Ready count follows conn, watched ++// the way NewGrpcClient watches the real connection. ++func newWatchedClient(ctx context.Context, window time.Duration, conn *fakeConn) *client { ++ c := &client{connectionRetryTimeout: window, ready: &readyTracker{conn: conn}} ++ go c.ready.watch(ctx) ++ return c ++} ++ ++// The server restarts: it is down for 60 s, comes back, and the re-sent ++// Wait() runs for 90 s on the new connection before that drops too. The second ++// drop begins a new outage, so it is retried, though the first failure is ++// only 150 s, less than two windows, behind it. ++func TestRetryRPCDropAfterAReconnectStartsANewWindow(t *testing.T) { ++ synctest.Test(t, func(t *testing.T) { ++ ctx, cancel := context.WithCancelCause(t.Context()) ++ defer cancel(nil) ++ conn := newFakeConn() ++ c := newWatchedClient(ctx, 2*time.Minute, conn) ++ var down time.Time ++ phase := 0 ++ ++ _, err := retryRPC(ctx, c, "wait", func() (bool, error) { ++ switch phase { ++ case 0: // the long poll; then the server goes away ++ time.Sleep(30 * time.Minute) ++ conn.set(connectivity.Idle) ++ down = time.Now() ++ phase = 1 ++ return false, classifyRPCErr(ctx, errGoawayDrop) ++ case 1: ++ if time.Since(down) < time.Minute { ++ conn.set(connectivity.TransientFailure) ++ return false, errNotConnected ++ } ++ // The server is back: the agent reconnects, and the Wait() it ++ // sends again runs for 90 s before this connection drops too. ++ conn.set(connectivity.Ready) ++ time.Sleep(90 * time.Second) ++ conn.set(connectivity.Idle) ++ phase = 2 ++ return false, classifyRPCErr(ctx, errGoawayDrop) ++ default: ++ phase = 3 ++ return false, nil ++ } ++ }) ++ ++ require.NoError(t, err) ++ assert.Equal(t, 3, phase) ++ }) ++} ++ ++// The storm a server sends when it GOAWAYs agents for too many pings: drops ++// after connections that worked for 30 s, 60 s and 110 s, each shorter than the ++// 2 minute window and each reconnecting at once. Every drop is retried. ++func TestRetryRPCDropsAfterReconnectsAreAllRetried(t *testing.T) { ++ synctest.Test(t, func(t *testing.T) { ++ ctx, cancel := context.WithCancelCause(t.Context()) ++ defer cancel(nil) ++ conn := newFakeConn() ++ c := newWatchedClient(ctx, 2*time.Minute, conn) ++ lives := []time.Duration{30 * time.Minute, 30 * time.Second, time.Minute, 110 * time.Second} ++ var calls int ++ ++ _, err := retryRPC(ctx, c, "wait", func() (bool, error) { ++ calls++ ++ if calls > len(lives) { ++ return false, nil ++ } ++ conn.set(connectivity.Ready) ++ time.Sleep(lives[calls-1]) ++ conn.set(connectivity.Idle) ++ return false, classifyRPCErr(ctx, errGoawayDrop) ++ }) ++ ++ require.NoError(t, err) ++ assert.Equal(t, len(lives)+1, calls) ++ }) ++} ++ ++// With no reconnection the window keeps counting from the first failure, even ++// when an attempt in between took 50 s to fail (a connection attempt that ++// hung). The agent gives up within the window. ++func TestRetryRPCSlowFailureWithoutAReconnectKeepsTheWindow(t *testing.T) { ++ synctest.Test(t, func(t *testing.T) { ++ ctx, cancel := context.WithCancelCause(t.Context()) ++ defer cancel(nil) ++ conn := newFakeConn() ++ c := newWatchedClient(ctx, 2*time.Minute, conn) ++ var down time.Time ++ var calls int ++ ++ _, err := retryRPC(ctx, c, "wait", func() (bool, error) { ++ calls++ ++ switch { ++ case calls == 1: ++ time.Sleep(30 * time.Minute) ++ conn.set(connectivity.Idle) ++ down = time.Now() ++ return false, classifyRPCErr(ctx, errGoawayDrop) ++ case time.Since(down) > 10*time.Minute: ++ return false, backoff.Permanent(errStillRetrying) ++ case calls == 5: ++ conn.set(connectivity.Connecting) ++ time.Sleep(50 * time.Second) ++ } ++ conn.set(connectivity.TransientFailure) ++ return false, errNotConnected ++ }) ++ ++ require.ErrorIs(t, err, ErrConnectionLost) ++ assert.LessOrEqual(t, time.Since(down), 2*time.Minute) ++ }) ++} ++ ++// A failure counts the Ready it reads itself. A watcher that gets to that same ++// connection only after the failure does not make it look like a ++// reconnection: the server answers every attempt with an error on a connection ++// that stays Ready, the watcher reads it 100 s into the streak, and the agent ++// still gives up within the window. ++func TestRetryRPCLateWatcherDoesNotStartANewWindow(t *testing.T) { ++ synctest.Test(t, func(t *testing.T) { ++ ctx := t.Context() ++ conn := newFakeConn() ++ c := &client{connectionRetryTimeout: 2 * time.Minute, ready: &readyTracker{conn: conn}} ++ var first time.Time ++ var calls int ++ watched := false ++ ++ _, err := retryRPC(ctx, c, "wait", func() (bool, error) { ++ calls++ ++ switch { ++ case calls == 1: ++ first = time.Now() ++ case time.Since(first) > 10*time.Minute: ++ return false, backoff.Permanent(errStillRetrying) ++ case !watched && time.Since(first) > 100*time.Second: ++ watched = true ++ c.ready.observe() // the watcher, late ++ } ++ return false, classifyRPCErr(ctx, status.Error(codes.Unavailable, "server is shutting down")) ++ }) ++ ++ require.ErrorIs(t, err, backoff.ErrMaxElapsedTime) ++ require.True(t, watched, "gave up before the watcher read the connection") ++ assert.LessOrEqual(t, time.Since(first), 2*time.Minute) ++ }) ++} ++ ++// A reconnection starts the window over but not the interval, so a server that ++// accepts connections and drops them at once is called at a growing interval, ++// not every 10 ms. ++func TestFailureWindowBackOffReconnectKeepsTheInterval(t *testing.T) { ++ t.Parallel() ++ ++ clock := &fakeClock{t: time.Unix(1_700_000_000, 0)} ++ b := &failureWindowBackOff{BackOff: newSteadyExponential(), window: time.Minute, now: clock.now} ++ var next time.Duration ++ for count := range uint64(6) { ++ b.readyCountAtFailure(count + 1) // reconnected before every failure ++ b.attemptFailed(clock.now()) ++ next = b.NextBackOff() ++ clock.advance(next) ++ } ++ ++ // 10 ms * 1.5^5 ++ assert.Equal(t, 75937500*time.Nanosecond, next) ++} ++ ++// The watcher ends when the connection is closed, without waiting for its ++// context. ++func TestReadyTrackerWatchEndsWhenTheConnectionCloses(t *testing.T) { ++ synctest.Test(t, func(t *testing.T) { ++ ctx, cancel := context.WithCancelCause(t.Context()) ++ defer cancel(nil) ++ conn := newFakeConn() ++ r := &readyTracker{conn: conn} ++ done := make(chan struct{}) ++ go func() { ++ r.watch(ctx) ++ close(done) ++ }() ++ ++ conn.set(connectivity.Shutdown) ++ synctest.Wait() ++ ++ select { ++ case <-done: ++ default: ++ t.Fatal("watch still runs after the connection closed") ++ } ++ }) ++} ++ ++// The watcher ends when its context ends. ++func TestReadyTrackerWatchEndsWithItsContext(t *testing.T) { ++ synctest.Test(t, func(t *testing.T) { ++ ctx, cancel := context.WithCancelCause(t.Context()) ++ conn := newFakeConn() ++ r := &readyTracker{conn: conn} ++ done := make(chan struct{}) ++ go func() { ++ r.watch(ctx) ++ close(done) ++ }() ++ ++ cancel(nil) ++ synctest.Wait() ++ ++ assert.False(t, conn.waitedAfterFalse.Load(), "watch waited again after its context ended") ++ select { ++ case <-done: ++ default: ++ t.Fatal("watch still runs after its context ended") ++ } ++ }) ++} ++ ++// readyCountOf reads r's count without reading the connection's state. ++func readyCountOf(r *readyTracker) uint64 { ++ r.mu.Lock() ++ defer r.mu.Unlock() ++ return r.count ++} ++ ++// NewGrpcClient counts the real connection's reconnections: once when it ++// first connects, and once more when it connects again after the server went ++// away and came back. ++func TestNewGrpcClientCountsReconnections(t *testing.T) { ++ ctx, cancel := context.WithCancelCause(t.Context()) ++ defer cancel(nil) ++ ++ var lis atomic.Pointer[bufconn.Listener] ++ serve := func() *grpc.Server { ++ l := bufconn.Listen(1 << 16) ++ lis.Store(l) ++ srv := grpc.NewServer() ++ go func() { _ = srv.Serve(l) }() ++ return srv ++ } ++ srv := serve() ++ conn, err := grpc.NewClient("passthrough:///bufnet", ++ grpc.WithTransportCredentials(insecure.NewCredentials()), ++ grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { ++ return lis.Load().DialContext(ctx) ++ }), ++ ) ++ require.NoError(t, err) ++ defer conn.Close() ++ c, ok := NewGrpcClient(ctx, conn).(*client) ++ require.True(t, ok) ++ ++ // Connect only starts a connection attempt when the connection is idle, ++ // as it is after the server went away, so it is called until the count ++ // moves. ++ reaches := func(want uint64) func() bool { ++ return func() bool { ++ conn.Connect() ++ return readyCountOf(c.ready) == want ++ } ++ } ++ require.Eventually(t, reaches(1), 10*time.Second, time.Millisecond) ++ ++ srv.Stop() ++ srv = serve() ++ defer srv.Stop() ++ require.Eventually(t, reaches(2), 10*time.Second, time.Millisecond) ++} +-- +2.55.0 + From 8f42efe2a22a3e36a67d61cb62e2f1316bd41b1e Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 6 Nov 2026 13:34:04 +0530 Subject: [PATCH 3/3] docs(woodpecker-agent): say which outages a retry window rides out The README advised a window longer than the outages to ride out, but an outage well under the window can still end with the agent giving up. While the connection is down the agent's retries do not reach the server, so gRPC's reconnect backoff decides when the connection comes back, and the agent stops up to one retry interval before the window ends. Say so, quote the measured rows, and advise a window of about twice the longest outage, or 0. Say too that keploy's agents run 0 and that the fixes matter for a finite window. Signed-off-by: slayerjain --- README.md | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index d177ce0..c5c7c18 100644 --- a/README.md +++ b/README.md @@ -119,10 +119,20 @@ reconnection (a server restart followed by another drop, or a storm of GOAWAYs) is retried instead of being counted against the outage before it. The build runs the patched package's tests and fails if one fails. -An outage longer than the window still ends with the agent giving up, and -the runner then cancels every workflow on the agent, so choose -`WOODPECKER_RETRY_TIMEOUT` longer than the outages to ride out, or 0 to -retry forever. +keploy's agents run `WOODPECKER_RETRY_TIMEOUT=0`, which retries forever, and +at 0 this image retries as v3.20.1 does. The fixes matter for a finite window: +upstream's users, and anyone who sets one. + +A finite window rides out only outages well shorter than itself. When the agent +gives up, the runner cancels every workflow on the agent. While the connection +is down, every RPC returns `errNotConnected` without calling the server, so the +agent's retries do not bring the connection back. Only gRPC's reconnect backoff +does: 1 s, growing 1.6x per attempt to 120 s, with about 20% jitter, and a +connect attempt can take 20 s or more. The agent also stops up to one retry +interval (at most 15 s) before the window ends. With a 6 s window, an outage of +60% of it gave up in 5 of 6 runs. With a 2 minute window, 1 of 12 runs gave up +at 60%, and none at 50%. So choose a window of minutes, about twice the longest +outage to ride out, or 0. **Contents:** the `woodpecker-agent` binary (reporting version `-keploy.`), CA certificates, timezone data, and upstream's