fix(e2e): keep chainsaw asserts polling through transient API errors

Chainsaw v0.2.15 ends an assert or error operation on the first API
error other than NotFound. kube-apiserver answers a GET with 500 when
etcd changes its leader, so a leader change that lands inside a poll
fails the step long before its own timeout, on whichever suite happens
to be polling.

The sandbox image now builds v0.2.15 from source with the fix proposed
upstream in kyverno/chainsaw#2761, applied unchanged, until a chainsaw
release carries it. The build runs the tests of the patched packages
and a test that drives chainsaw built from the patched tree against a
fake apiserver: a run of 500s must not fail an assert, and a
persistent one must fail it at its timeout rather than at the first
error.

Closes: #4720

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
(cherry picked from commit 813c618086)
Signed-off-by: Myasnikov Daniil <myasnikovdaniil2001@gmail.com>
This commit is contained in:
Aleksei Sviridkin authored and Myasnikov Daniil committed 2026-11-10 12:43:14 +00:00
1 parent b3a6c17d23
commit df75adc11c
6 files changed
+500 -5

No files matched your search

+15
View File
@@ -85,6 +85,21 @@
"matchFileNames": ["packages/system/cilium/images/cilium-operator/**"],
"enabled": false
},
{
"description": "Split golang patch from minor updates for the e2e sandbox builder, so the rule below can drop the minor bump without taking the patch bump with it. By default both land in one non-major bucket and only the newest release is proposed.",
"matchManagers": ["dockerfile"],
"matchFileNames": ["packages/core/testing/images/e2e-sandbox/**"],
"matchPackageNames": ["golang"],
"separateMinorPatch": true
},
{
"description": "The e2e sandbox builds a patched chainsaw release with the Go minor upstream shipped that release with. A golang minor or major bump builds it with a toolchain upstream never shipped it with. Patch and digest updates of the same minor still arrive; move the minor by hand together with CHAINSAW_VERSION.",
"matchManagers": ["dockerfile"],
"matchFileNames": ["packages/core/testing/images/e2e-sandbox/**"],
"matchPackageNames": ["golang"],
"matchUpdateTypes": ["major", "minor"],
"enabled": false
},
{
"description": "The seaweedfs rebuild compiles one upstream release with the Go toolchain upstream's docker/Dockerfile.go_build uses at that tag, lays it over the upstream image of that tag, and `make update` in packages/system/seaweedfs re-pins the builder, the base image digest and the source checksum from there. A Renovate bump of any of them builds a combination upstream never shipped, and the next `make update` silently reverts it. Updates are disabled here; all of them move with the SeaweedFS version.",
"matchManagers": ["dockerfile"],
+1 -1
View File
@@ -81,4 +81,4 @@ chainsaw test postgres/
## CI integration
The `e2e` job in `.github/workflows/pull-requests.yaml` runs `make -C packages/core/testing test-chainsaw` (which execs `hack/e2e-chainsaw-run.sh` inside the e2e sandbox) and uploads `chainsaw-report.xml`. The runner calls `chainsaw test` once per suite directory, fails a suite whose pods outlive its cleanup by more than the default `timeouts.cleanup` (`LEAKED-PODS suite=<dir>` in the log; see `docs/agents/e2e-testing.md` §8 and `_lib/leak-allowlist.txt` for known, filed leaks), and merges the per-suite reports into that one file. A local `chainsaw test` as shown above runs the same tests without the leak check. The sandbox image (`packages/core/testing/images/e2e-sandbox/Dockerfile`) ships the `chainsaw` binary alongside `kubectl`/`helm`/`mc`/`jq`/`nc`.
The `e2e` job in `.github/workflows/pull-requests.yaml` runs `make -C packages/core/testing test-chainsaw` (which execs `hack/e2e-chainsaw-run.sh` inside the e2e sandbox) and uploads `chainsaw-report.xml`. The runner calls `chainsaw test` once per suite directory, fails a suite whose pods outlive its cleanup by more than the default `timeouts.cleanup` (`LEAKED-PODS suite=<dir>` in the log; see `docs/agents/e2e-testing.md` §8 and `_lib/leak-allowlist.txt` for known, filed leaks), and merges the per-suite reports into that one file. A local `chainsaw test` as shown above runs the same tests without the leak check. The sandbox image (`packages/core/testing/images/e2e-sandbox/Dockerfile`) ships the `chainsaw` binary alongside `kubectl`/`helm`/`mc`/`jq`/`nc`, built from source with a patch that keeps an assert polling through transient API errors such as an etcd leader change; a released `chainsaw` run locally fails the assert on the first such error instead.
@@ -1,3 +1,54 @@
# Chainsaw is built from source because v0.2.15 ends an assert on the first API
# error other than NotFound, so an etcd leader change during a poll fails the
# step long before its timeout. The patch keeps polling on transient server
# errors. Go back to the release tarball, dropping this stage, patches/ and
# chainsaw-transient/, once a chainsaw release carries kyverno/chainsaw#2761.
# Go 1.26 and -trimpath follow the v0.2.15 release binary (go1.26.0); a newer
# Go minor is not what that release was tested with.
FROM --platform=$BUILDPLATFORM golang:1.26.8@sha256:3c3e25a4da13fd0478eed2df1eb35a0e667094a7124d3993a6a1d30f71c17e79 AS chainsaw
ARG GOPROXY
ARG CHAINSAW_VERSION=0.2.15
ARG CHAINSAW_SOURCE_SHA256=04f3fc7dd8e958e4fc7d73383bc22b05827240dd2fe7a8e32ee99d8c0332da2a
ARG TARGETOS
ARG TARGETARCH
ARG BUILDOS
ARG BUILDARCH
WORKDIR /workspace
RUN curl -fsSL "https://github.com/kyverno/chainsaw/archive/refs/tags/v${CHAINSAW_VERSION}.tar.gz" -o /tmp/chainsaw.tar.gz \
&& echo "${CHAINSAW_SOURCE_SHA256} /tmp/chainsaw.tar.gz" | sha256sum -c - \
&& tar -xzf /tmp/chainsaw.tar.gz --strip=1 \
&& rm -f /tmp/chainsaw.tar.gz
COPY patches /patches
RUN git apply /patches/*.patch
# go build never compiles a _test.go, so nothing else runs the tests of the
# packages the patches touch. The list is read into a variable first: a for
# loop drops the exit status of a command substitution.
RUN files=$(git apply --numstat /patches/*.patch) || exit 1; \
for dir in $(printf '%s\n' "$files" | cut -f3 | grep '\.go$' | xargs -r -n1 dirname | sort -u); do \
(cd "$dir" && go test .) || exit 1; \
done
RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH go build -trimpath \
-ldflags "-s -w -X github.com/kyverno/chainsaw/pkg/version.BuildVersion=${CHAINSAW_VERSION}" \
-o /chainsaw .
# The test executes chainsaw, so a cross build tests a host build of the same
# patched tree instead of the shipped binary. The tests skip without CHAINSAW,
# and a skip reports ok, so a skip fails the step here.
COPY chainsaw-transient /chainsaw-transient
RUN if [ "$TARGETOS/$TARGETARCH" = "$BUILDOS/$BUILDARCH" ]; then \
bin=/chainsaw; \
else \
bin=/tmp/chainsaw-host && CGO_ENABLED=0 go build -o "$bin" . || exit 1; \
fi; \
cd /chainsaw-transient && out=$(CHAINSAW="$bin" go test -count=1 -v .) || { printf '%s\n' "$out"; exit 1; }; \
printf '%s\n' "$out"; \
if printf '%s\n' "$out" | grep -q -- '--- SKIP'; then echo "chainsaw-transient skipped its tests" >&2; exit 1; fi
FROM ubuntu:24.04@sha256:008173c23f95b170204355c12626cb5a965d779a7e1283b09e9cffbb1bf33ca3
ARG KUBECTL_VERSION=1.33.13
@@ -5,7 +56,6 @@ ARG TALOSCTL_VERSION=1.13.5
ARG HELM_VERSION=3.21.2
ARG COZYHR_VERSION=1.6.1
ARG CRUST_GATHER_VERSION=v0.15.2
ARG CHAINSAW_VERSION=0.2.15
ARG MC_VERSION=RELEASE.2025-08-13T08-35-41Z
ARG FLUX_VERSION=2.8.6
@@ -41,9 +91,7 @@ RUN case "${TARGETARCH}" in \
# `crust-gather serve`-able from the cozyreport artifact. Installs a static musl
# binary as crust-gather.
RUN curl -sSfL "https://github.com/crust-gather/crust-gather/raw/main/install.sh" | sh -s -- --version "${CRUST_GATHER_VERSION}" --bin-dir /usr/local/bin --yes
RUN curl -sSL "https://github.com/kyverno/chainsaw/releases/download/v${CHAINSAW_VERSION}/chainsaw_${TARGETOS}_${TARGETARCH}.tar.gz" \
| tar -xz -C /usr/local/bin chainsaw \
&& chmod +x /usr/local/bin/chainsaw
COPY --from=chainsaw /chainsaw /usr/local/bin/chainsaw
RUN <<'EOF'
cat <<'EOT' >> /etc/bash.bashrc
. /etc/bash_completion
@@ -0,0 +1,3 @@
module github.com/cozystack/cozystack/e2e-sandbox/chainsaw-transient
go 1.26
@@ -0,0 +1,182 @@
// Package transient runs a chainsaw built from the e2e sandbox's patched tree
// against a fake apiserver that answers the asserted object's GET with
// HTTP 500 and an empty reason, which is what kube-apiserver sends for an etcd
// error such as `etcdserver: leader changed`.
// Release v0.2.15 ends an assert on the first such answer; the image carries
// a patch that keeps it polling until its own timeout.
package transient
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"sync/atomic"
"testing"
"time"
)
const assertTimeout = 10 * time.Second
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
_ = json.NewEncoder(w).Encode(v)
}
func status(code int, reason, message string) map[string]any {
return map[string]any{
"kind": "Status", "apiVersion": "v1", "status": "Failure",
"code": code, "reason": reason, "message": message,
}
}
// fakeAPIServer serves just enough discovery for chainsaw to resolve
// v1/ConfigMap, and answers GET default/probe with 500 for the first
// `failures` requests (all of them when failures < 0), then with the object.
func fakeAPIServer(t *testing.T, failures int64) (*httptest.Server, *atomic.Int64) {
t.Helper()
var gets atomic.Int64
mux := http.NewServeMux()
mux.HandleFunc("/version", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"major": "1", "minor": "33", "gitVersion": "v1.33.0"})
})
mux.HandleFunc("/api", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"kind": "APIVersions", "versions": []string{"v1"},
"serverAddressByClientCIDRs": []map[string]string{{"clientCIDR": "0.0.0.0/0", "serverAddress": "127.0.0.1"}},
})
})
mux.HandleFunc("/apis", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"kind": "APIGroupList", "apiVersion": "v1", "groups": []any{}})
})
mux.HandleFunc("/api/v1", func(w http.ResponseWriter, _ *http.Request) {
verbs := []string{"create", "delete", "get", "list", "patch", "update", "watch"}
writeJSON(w, http.StatusOK, map[string]any{
"kind": "APIResourceList", "apiVersion": "v1", "groupVersion": "v1",
"resources": []map[string]any{
{"name": "namespaces", "singularName": "namespace", "namespaced": false, "kind": "Namespace", "verbs": verbs},
{"name": "configmaps", "singularName": "configmap", "namespaced": true, "kind": "ConfigMap", "verbs": verbs},
},
})
})
mux.HandleFunc("/api/v1/namespaces/default", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"kind": "Namespace", "apiVersion": "v1",
"metadata": map[string]any{"name": "default"},
"status": map[string]any{"phase": "Active"},
})
})
mux.HandleFunc("/api/v1/namespaces/default/configmaps/probe", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
writeJSON(w, http.StatusMethodNotAllowed, status(http.StatusMethodNotAllowed, "MethodNotAllowed", r.Method))
return
}
n := gets.Add(1)
if failures < 0 || n <= failures {
writeJSON(w, http.StatusInternalServerError, status(http.StatusInternalServerError, "", "etcdserver: leader changed"))
return
}
writeJSON(w, http.StatusOK, map[string]any{
"kind": "ConfigMap", "apiVersion": "v1",
"metadata": map[string]any{"name": "probe", "namespace": "default"},
"data": map[string]string{"ready": "true"},
})
})
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusNotFound, status(http.StatusNotFound, "NotFound", r.URL.Path))
})
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
return srv, &gets
}
func runChainsaw(t *testing.T, server string) (time.Duration, string, error) {
t.Helper()
bin := os.Getenv("CHAINSAW")
// The image build sets CHAINSAW; `make go-module-tests` reaches this module
// too, with no patched binary to test.
if bin == "" {
t.Skip("CHAINSAW is not set to the chainsaw binary under test")
}
dir := t.TempDir()
kubeconfig := filepath.Join(dir, "kubeconfig")
if err := os.WriteFile(kubeconfig, []byte(fmt.Sprintf(`apiVersion: v1
kind: Config
clusters:
- name: fake
cluster:
server: %s
contexts:
- name: fake
context:
cluster: fake
user: fake
current-context: fake
users:
- name: fake
user: {}
`, server)), 0o600); err != nil {
t.Fatal(err)
}
suite := filepath.Join(dir, "suite")
if err := os.Mkdir(suite, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(suite, "chainsaw-test.yaml"), []byte(fmt.Sprintf(`apiVersion: chainsaw.kyverno.io/v1alpha1
kind: Test
metadata:
name: transient
spec:
namespace: default
skipDelete: true
steps:
- try:
- assert:
timeout: %s
resource:
apiVersion: v1
kind: ConfigMap
metadata:
name: probe
namespace: default
data:
ready: "true"
`, assertTimeout)), 0o600); err != nil {
t.Fatal(err)
}
cmd := exec.Command(bin, "test", "--test-dir", suite, "--no-color")
cmd.Env = append(os.Environ(), "KUBECONFIG="+kubeconfig)
start := time.Now()
out, err := cmd.CombinedOutput()
return time.Since(start), string(out), err
}
// A run of 500s shorter than the timeout must not fail the assert: the poll
// carries on and passes once the object comes back.
func TestAssertSurvivesTransientServerErrors(t *testing.T) {
srv, gets := fakeAPIServer(t, 5)
elapsed, out, err := runChainsaw(t, srv.URL)
if err != nil {
t.Fatalf("chainsaw failed after %s and %d GETs of the object, want a pass once the 500s stop:\n%s", elapsed, gets.Load(), out)
}
if gets.Load() <= 5 {
t.Fatalf("chainsaw passed after only %d GETs of the object, so it never saw the 500s:\n%s", gets.Load(), out)
}
}
// When the 500s never stop, the assert still fails, and it fails by its own
// timeout rather than on the first error.
func TestAssertFailsAtItsTimeoutOnPersistentServerErrors(t *testing.T) {
srv, gets := fakeAPIServer(t, -1)
elapsed, out, err := runChainsaw(t, srv.URL)
if err == nil {
t.Fatalf("chainsaw passed against an apiserver that only answers 500:\n%s", out)
}
if elapsed < assertTimeout || gets.Load() < 2 {
t.Fatalf("chainsaw failed after %s and %d GETs of the object, want the %s assert timeout and more than one GET:\n%s", elapsed, gets.Load(), assertTimeout, out)
}
}
@@ -0,0 +1,247 @@
From dcbe912b15be1060c741b88d275b2134b29a2704 Mon Sep 17 00:00:00 2001
From: Shubham Singh <shubhsoch@gmail.com>
Date: Mon, 3 Aug 2026 16:18:17 +0530
Subject: [PATCH] fix: assert-polling-error
Upstream: https://github.com/kyverno/chainsaw/pull/2761
Signed-off-by: Shubham Singh <shubhsoch@gmail.com>
---
pkg/engine/operations/assert/operation.go | 10 ++-
.../operations/assert/operation_test.go | 8 +-
pkg/engine/operations/error/operation.go | 9 ++-
pkg/engine/operations/error/operation_test.go | 4 +-
pkg/engine/operations/internal/errors.go | 18 +++++
pkg/engine/operations/internal/errors_test.go | 81 +++++++++++++++++++
6 files changed, 122 insertions(+), 8 deletions(-)
create mode 100644 pkg/engine/operations/internal/errors.go
create mode 100644 pkg/engine/operations/internal/errors_test.go
diff --git a/pkg/engine/operations/assert/operation.go b/pkg/engine/operations/assert/operation.go
index c457d7d64..0b70fe05d 100644
--- a/pkg/engine/operations/assert/operation.go
+++ b/pkg/engine/operations/assert/operation.go
@@ -3,6 +3,7 @@ package assert
import (
"context"
"errors"
+ "fmt"
"github.com/kyverno/chainsaw/pkg/apis"
"github.com/kyverno/chainsaw/pkg/apis/v1alpha1"
@@ -100,6 +101,10 @@ func (o *operation) execute(ctx context.Context, bindings apis.Bindings, obj uns
errs = append(errs, errors.New("actual resource not found"))
return false, nil
}
+ if internal.IsRetriable(err) {
+ errs = append(errs, err)
+ return false, nil
+ }
return false, err
} else if len(candidates) == 0 {
errs = append(errs, errors.New("no actual resource found"))
@@ -127,7 +132,10 @@ func (o *operation) execute(ctx context.Context, bindings apis.Bindings, obj uns
}
// eventually return a combination of last errors
if len(lastErrs) != 0 {
- return multierr.Combine(lastErrs...)
+ return multierr.Append(
+ multierr.Combine(lastErrs...),
+ fmt.Errorf("operation terminated with error: %w", err),
+ )
}
// return received error
return err
diff --git a/pkg/engine/operations/assert/operation_test.go b/pkg/engine/operations/assert/operation_test.go
index cf5b64c59..7ceea5c98 100644
--- a/pkg/engine/operations/assert/operation_test.go
+++ b/pkg/engine/operations/assert/operation_test.go
@@ -96,7 +96,7 @@ func Test_operationAssert(t *testing.T) {
expectErr: true,
expectedLogs: []string{
"ASSERT: RUN - []",
- "ASSERT: ERROR - [=== ERROR\n---------------\nv1/Pod/test-pod\n---------------\n* spec.containers[0].image: Invalid value: \"fake-image\": Expected value: \"test-image\"\n* spec.containers[0].name: Invalid value: \"fake-container\": Expected value: \"test-container\"\n\n--- expected\n+++ actual\n@@ -4,6 +4,6 @@\n name: test-pod\n spec:\n containers:\n- - image: test-image\n- name: test-container\n+ - image: fake-image\n+ name: fake-container]",
+ "ASSERT: ERROR - [=== ERROR\n---------------\nv1/Pod/test-pod\n---------------\n* spec.containers[0].image: Invalid value: \"fake-image\": Expected value: \"test-image\"\n* spec.containers[0].name: Invalid value: \"fake-container\": Expected value: \"test-container\"\n\n--- expected\n+++ actual\n@@ -4,6 +4,6 @@\n name: test-pod\n spec:\n containers:\n- - image: test-image\n- name: test-container\n+ - image: fake-image\n+ name: fake-container\n \n\noperation terminated with error: context deadline exceeded]",
},
}, {
name: "Not found using Get",
@@ -117,7 +117,7 @@ func Test_operationAssert(t *testing.T) {
},
},
expectErr: true,
- expectedLogs: []string{"ASSERT: RUN - []", "ASSERT: ERROR - [=== ERROR\nactual resource not found]"},
+ expectedLogs: []string{"ASSERT: RUN - []", "ASSERT: ERROR - [=== ERROR\nactual resource not found\noperation terminated with error: context deadline exceeded]"},
}, {
name: "Bad assert",
expected: unstructured.Unstructured{
@@ -176,7 +176,7 @@ func Test_operationAssert(t *testing.T) {
return nil
},
},
- expectedLogs: []string{"ASSERT: RUN - []", "ASSERT: ERROR - [=== ERROR\n---------------\nv1/Pod/test-pod\n---------------\n* spec.foo: Required value: field not found in the input object\n\n--- expected\n+++ actual\n@@ -2,6 +2,5 @@\n kind: Pod\n metadata:\n name: test-pod\n-spec:\n- foo: bar\n+spec: {}]"},
+ expectedLogs: []string{"ASSERT: RUN - []", "ASSERT: ERROR - [=== ERROR\n---------------\nv1/Pod/test-pod\n---------------\n* spec.foo: Required value: field not found in the input object\n\n--- expected\n+++ actual\n@@ -2,6 +2,5 @@\n kind: Pod\n metadata:\n name: test-pod\n-spec:\n- foo: bar\n+spec: {}\n \n\noperation terminated with error: context deadline exceeded]"},
expectErr: true,
}, {
name: "Successful match using List",
@@ -243,7 +243,7 @@ func Test_operationAssert(t *testing.T) {
},
},
expectErr: true,
- expectedLogs: []string{"ASSERT: RUN - []", "ASSERT: ERROR - [=== ERROR\nno actual resource found]"},
+ expectedLogs: []string{"ASSERT: RUN - []", "ASSERT: ERROR - [=== ERROR\nno actual resource found\noperation terminated with error: context deadline exceeded]"},
}, {
name: "List operation fails",
expected: unstructured.Unstructured{
diff --git a/pkg/engine/operations/error/operation.go b/pkg/engine/operations/error/operation.go
index 031f1c2eb..8fcf2ee39 100644
--- a/pkg/engine/operations/error/operation.go
+++ b/pkg/engine/operations/error/operation.go
@@ -95,6 +95,10 @@ func (o *operation) execute(ctx context.Context, bindings apis.Bindings, obj uns
if kerrors.IsNotFound(err) {
return true, nil
}
+ if internal.IsRetriable(err) {
+ errs = append(errs, err)
+ return false, nil
+ }
return false, err
} else if len(candidates) == 0 {
return true, nil
@@ -119,7 +123,10 @@ func (o *operation) execute(ctx context.Context, bindings apis.Bindings, obj uns
}
// eventually return a combination of last errors
if len(lastErrs) != 0 {
- return multierr.Combine(lastErrs...)
+ return multierr.Append(
+ multierr.Combine(lastErrs...),
+ fmt.Errorf("operation terminated with error: %w", err),
+ )
}
// return received error
return err
diff --git a/pkg/engine/operations/error/operation_test.go b/pkg/engine/operations/error/operation_test.go
index 0280b2cb2..e2be30464 100644
--- a/pkg/engine/operations/error/operation_test.go
+++ b/pkg/engine/operations/error/operation_test.go
@@ -80,8 +80,8 @@ func Test_operationError(t *testing.T) {
return nil
},
},
- expectedErr: fmt.Errorf("v1/Pod/foo/test-pod - resource matches expectation"),
- expectedLogs: []string{"ERROR: RUN - []", "ERROR: ERROR - [=== ERROR\nv1/Pod/foo/test-pod - resource matches expectation]"},
+ expectedErr: fmt.Errorf("v1/Pod/foo/test-pod - resource matches expectation; operation terminated with error: context deadline exceeded"),
+ expectedLogs: []string{"ERROR: RUN - []", "ERROR: ERROR - [=== ERROR\noperation terminated with error: context deadline exceeded\nv1/Pod/foo/test-pod - resource matches expectation]"},
}, {
name: "Bad assert",
expected: unstructured.Unstructured{
diff --git a/pkg/engine/operations/internal/errors.go b/pkg/engine/operations/internal/errors.go
new file mode 100644
index 000000000..dacff7efd
--- /dev/null
+++ b/pkg/engine/operations/internal/errors.go
@@ -0,0 +1,18 @@
+package internal
+
+import (
+ kerrors "k8s.io/apimachinery/pkg/api/errors"
+)
+
+// IsRetriable checks if an error from the API server is a transient error that should be retried.
+func IsRetriable(err error) bool {
+ if err == nil {
+ return false
+ }
+ return kerrors.IsInternalError(err) ||
+ kerrors.IsServiceUnavailable(err) ||
+ kerrors.IsTimeout(err) ||
+ kerrors.IsServerTimeout(err) ||
+ kerrors.IsTooManyRequests(err) ||
+ kerrors.IsUnexpectedServerError(err)
+}
diff --git a/pkg/engine/operations/internal/errors_test.go b/pkg/engine/operations/internal/errors_test.go
new file mode 100644
index 000000000..012d16c0d
--- /dev/null
+++ b/pkg/engine/operations/internal/errors_test.go
@@ -0,0 +1,81 @@
+package internal
+
+import (
+ "errors"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ kerrors "k8s.io/apimachinery/pkg/api/errors"
+ "k8s.io/apimachinery/pkg/runtime/schema"
+)
+
+func TestIsRetriable(t *testing.T) {
+ tests := []struct {
+ name string
+ err error
+ expected bool
+ }{
+ {
+ name: "nil error",
+ err: nil,
+ expected: false,
+ },
+ {
+ name: "generic error",
+ err: errors.New("some error"),
+ expected: false,
+ },
+ {
+ name: "forbidden error",
+ err: kerrors.NewForbidden(schema.GroupResource{Group: "", Resource: "pods"}, "test-pod", errors.New("forbidden")),
+ expected: false,
+ },
+ {
+ name: "unauthorized error",
+ err: kerrors.NewUnauthorized("unauthorized"),
+ expected: false,
+ },
+ {
+ name: "bad request error",
+ err: kerrors.NewBadRequest("bad request"),
+ expected: false,
+ },
+ {
+ name: "internal error",
+ err: kerrors.NewInternalError(errors.New("internal server error")),
+ expected: true,
+ },
+ {
+ name: "service unavailable error",
+ err: kerrors.NewServiceUnavailable("service unavailable"),
+ expected: true,
+ },
+ {
+ name: "timeout error",
+ err: kerrors.NewTimeoutError("timeout", 10),
+ expected: true,
+ },
+ {
+ name: "server timeout error",
+ err: kerrors.NewServerTimeout(schema.GroupResource{Group: "", Resource: "pods"}, "get", 10),
+ expected: true,
+ },
+ {
+ name: "too many requests error",
+ err: kerrors.NewTooManyRequests("too many requests", 10),
+ expected: true,
+ },
+ {
+ name: "unexpected server error",
+ err: kerrors.NewGenericServerResponse(500, "GET", schema.GroupResource{Group: "", Resource: "pods"}, "test-pod", "unexpected body", 0, false),
+ expected: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ actual := IsRetriable(tt.err)
+ assert.Equal(t, tt.expected, actual)
+ })
+ }
+}