From e7cd1a78b6530c568c98f2f988482543b96a5a51 Mon Sep 17 00:00:00 2001 From: SurbhiAgarwal Date: Sat, 17 Oct 2026 21:59:25 +0530 Subject: [PATCH] Support timeout field in Kptfile pipeline steps Add support for specifying a timeout field on individual mutator and validator pipeline steps in the Kptfile (e.g. timeout: 30s). - Add Timeout field to Function type in api/kptfile/v1/types.go and generated applyconfigurations. - Validate that the timeout field contains a valid, positive duration. - Parse step timeout and pass to ContainerFn and ExecFn runtimes. - Maintain precedence: the shorter limit wins (pipeline-level --timeout flag limits the whole run, step-level timeout limits the individual function, and step-level timeout overrides the default 5-minute timeout). - Update Kptfile schema definitions (JSON and YAML). - Add unit tests for validation, step execution timeout, and precedence. Part of #4473 Signed-off-by: SurbhiAgarwal --- .../kptfile/v1/function.go | 12 ++++ api/kptfile/v1/types.go | 5 ++ api/kptfile/v1/validation.go | 27 +++++++ api/kptfile/v1/validation_test.go | 70 +++++++++++++++++++ cli/go.mod | 4 +- .../en/reference/schema/kptfile/kptfile.json | 5 ++ .../en/reference/schema/kptfile/kptfile.yaml | 7 ++ go.mod | 2 +- pkg/fn/runtime/runner.go | 11 +++ pkg/fn/runtime/runner_test.go | 34 ++++++++- pkg/lib/kptops/render_executor_test.go | 42 +++++++++++ 11 files changed, 215 insertions(+), 4 deletions(-) diff --git a/api/generated/applyconfigurations/kptfile/v1/function.go b/api/generated/applyconfigurations/kptfile/v1/function.go index a520062f03..0b1e7becb0 100644 --- a/api/generated/applyconfigurations/kptfile/v1/function.go +++ b/api/generated/applyconfigurations/kptfile/v1/function.go @@ -77,6 +77,10 @@ type FunctionApplyConfiguration struct { // - Check resource count among the selected resources: // `when: "resources.filter(r, r.kind == 'Deployment').size() > 0"` CelCondition *string `json:"when,omitempty"` + // Timeout specifies the maximum execution time for this function step + // (e.g. "30s", "1m", "5m"). If omitted, the pipeline timeout or default + // function timeout (5m) is used. + Timeout *string `json:"timeout,omitempty"` } // FunctionApplyConfiguration constructs a declarative configuration of the Function type for use with @@ -180,3 +184,11 @@ func (b *FunctionApplyConfiguration) WithCelCondition(value string) *FunctionApp b.CelCondition = &value return b } + +// WithTimeout sets the Timeout field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Timeout field is set to the value of the last call. +func (b *FunctionApplyConfiguration) WithTimeout(value string) *FunctionApplyConfiguration { + b.Timeout = &value + return b +} diff --git a/api/kptfile/v1/types.go b/api/kptfile/v1/types.go index 483a2e37bf..777c1eacc8 100644 --- a/api/kptfile/v1/types.go +++ b/api/kptfile/v1/types.go @@ -402,6 +402,11 @@ type Function struct { // - Check resource count among the selected resources: // `when: "resources.filter(r, r.kind == 'Deployment').size() > 0"` CelCondition string `yaml:"when,omitempty" json:"when,omitempty"` + + // Timeout specifies the maximum execution time for this function step + // (e.g. "30s", "1m", "5m"). If omitted, the default function timeout (5m) + // is used. + Timeout string `yaml:"timeout,omitempty" json:"timeout,omitempty"` } // ResourceReference identifies a resource within the package by its API identity. diff --git a/api/kptfile/v1/validation.go b/api/kptfile/v1/validation.go index 2c7c9e9304..793bb3f68f 100644 --- a/api/kptfile/v1/validation.go +++ b/api/kptfile/v1/validation.go @@ -21,6 +21,7 @@ import ( "regexp" "slices" "strings" + "time" "github.com/distribution/reference" "sigs.k8s.io/kustomize/kyaml/filesys" @@ -256,6 +257,32 @@ func (f *Function) validate(fsys filesys.FileSystem, fnType string, idx int, pkg if err := f.validateExecutor(fnType, idx); err != nil { return err } + if err := f.validateTimeout(fnType, idx); err != nil { + return err + } + return nil +} + +// validateTimeout checks that the optional timeout string is a valid positive duration. +func (f *Function) validateTimeout(fnType string, idx int) error { + if f.Timeout == "" { + return nil + } + d, err := time.ParseDuration(f.Timeout) + if err != nil { + return &ValidateError{ + Field: fmt.Sprintf("pipeline.%s[%d].timeout", fnType, idx), + Value: f.Timeout, + Reason: fmt.Sprintf("invalid duration %q: %v", f.Timeout, err), + } + } + if d <= 0 { + return &ValidateError{ + Field: fmt.Sprintf("pipeline.%s[%d].timeout", fnType, idx), + Value: f.Timeout, + Reason: fmt.Sprintf("timeout %q must be greater than zero", f.Timeout), + } + } return nil } diff --git a/api/kptfile/v1/validation_test.go b/api/kptfile/v1/validation_test.go index 6b535867bd..a7ca5d73ab 100644 --- a/api/kptfile/v1/validation_test.go +++ b/api/kptfile/v1/validation_test.go @@ -148,6 +148,76 @@ func TestKptfileValidate(t *testing.T) { }, valid: false, }, + { + name: "pipeline: valid mutator step timeout", + kptfile: KptFile{ + Pipeline: &Pipeline{ + Mutators: []Function{ + { + Image: "image", + Timeout: "30s", + }, + }, + }, + }, + valid: true, + }, + { + name: "pipeline: valid validator step timeout", + kptfile: KptFile{ + Pipeline: &Pipeline{ + Validators: []Function{ + { + Image: "image", + Timeout: "1m", + }, + }, + }, + }, + valid: true, + }, + { + name: "pipeline: invalid step timeout syntax", + kptfile: KptFile{ + Pipeline: &Pipeline{ + Mutators: []Function{ + { + Image: "image", + Timeout: "not-a-duration", + }, + }, + }, + }, + valid: false, + }, + { + name: "pipeline: non-positive zero step timeout", + kptfile: KptFile{ + Pipeline: &Pipeline{ + Mutators: []Function{ + { + Image: "image", + Timeout: "0s", + }, + }, + }, + }, + valid: false, + }, + { + name: "pipeline: negative step timeout", + kptfile: KptFile{ + Pipeline: &Pipeline{ + Validators: []Function{ + { + Image: "image", + Timeout: "-10s", + }, + }, + }, + }, + valid: false, + }, } for _, c := range cases { diff --git a/cli/go.mod b/cli/go.mod index b05cedc1ea..e50c7d95ca 100644 --- a/cli/go.mod +++ b/cli/go.mod @@ -3,8 +3,8 @@ module github.com/kptdev/kpt/cli go 1.26.9 // TODO: Comment the lines below out when the next version of the API is released. -// replace github.com/kptdev/kpt/api => ../api -// replace github.com/kptdev/kpt => .. +replace github.com/kptdev/kpt/api => ../api +replace github.com/kptdev/kpt => .. require ( github.com/go-errors/errors v1.5.1 diff --git a/documentation/content/en/reference/schema/kptfile/kptfile.json b/documentation/content/en/reference/schema/kptfile/kptfile.json index bb36dc49ef..c2c3e4c89d 100644 --- a/documentation/content/en/reference/schema/kptfile/kptfile.json +++ b/documentation/content/en/reference/schema/kptfile/kptfile.json @@ -129,6 +129,11 @@ "type": "string", "x-go-name": "Tag" }, + "timeout": { + "description": "`Timeout` is an optional field for specifying the maximum time the function is allowed to run,\ne.g. '30s' or '10m'. If omitted, the function is limited by the pipeline run timeout (if set)\nor defaults to 5 minutes. Applicable to container and exec based functions only.", + "type": "string", + "x-go-name": "Timeout" + }, "when": { "description": "CelCondition is an optional CEL expression (exposed as 'when' in YAML) that determines whether this\nfunction should be executed. The expression is evaluated against the list\nof KRM resources passed to this function step (after `Selectors` and\n`Exclude` have been applied) and should return a boolean value.\nIf omitted or evaluates to true, the function executes normally.\nIf evaluates to false, the function is skipped.\n\nExamples:\n\nCheck if a specific ConfigMap exists among the selected resources:\nwhen: `\"resources.exists(r, r.kind == 'ConfigMap' && r.metadata.name == 'my-config')\"`\n\nCheck resource count among the selected resources:\n`when: \"resources.filter(r, r.kind == 'Deployment').size() > 0\"`", "type": "string", diff --git a/documentation/content/en/reference/schema/kptfile/kptfile.yaml b/documentation/content/en/reference/schema/kptfile/kptfile.yaml index 97242775dc..683ded2707 100644 --- a/documentation/content/en/reference/schema/kptfile/kptfile.yaml +++ b/documentation/content/en/reference/schema/kptfile/kptfile.yaml @@ -121,6 +121,13 @@ definitions: Can be a semver constraint satisfying this spec: https://github.com/Masterminds/semver?tab=readme-ov-file#checking-version-constraints type: string x-go-name: Tag + timeout: + description: |- + `Timeout` is an optional field for specifying the maximum time the function is allowed to run, + e.g. '30s' or '10m'. If omitted, the function is limited by the pipeline run timeout (if set) + or defaults to 5 minutes. Applicable to container and exec based functions only. + type: string + x-go-name: Timeout when: description: |- CelCondition is an optional CEL expression (exposed as 'when' in YAML) that determines whether this diff --git a/go.mod b/go.mod index 7ffb9190a4..46a5fb7823 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/kptdev/kpt go 1.26.9 // TODO: Comment the line below out when the next version of the API is released. -// replace github.com/kptdev/kpt/api => ./api +replace github.com/kptdev/kpt/api => ./api require ( github.com/Masterminds/semver/v3 v3.5.0 diff --git a/pkg/fn/runtime/runner.go b/pkg/fn/runtime/runner.go index 722d87b50e..710e0f79b1 100644 --- a/pkg/fn/runtime/runner.go +++ b/pkg/fn/runtime/runner.go @@ -132,6 +132,15 @@ func NewRunner( pkgCtxGenerator := &builtins.PackageContextGenerator{} fltr.Run = pkgCtxGenerator.Run } else { + var fnTimeout time.Duration + if f.Timeout != "" { + var err error + fnTimeout, err = time.ParseDuration(f.Timeout) + if err != nil { + return nil, fmt.Errorf("invalid function timeout %q: %w", f.Timeout, err) + } + } + switch { case f.Image != "": // If allowWasm is true, we will use wasm runtime for image field. @@ -145,6 +154,7 @@ func NewRunner( cfn := &ContainerFn{ Image: f.Image, ImagePullPolicy: opts.ImagePullPolicy, + Timeout: fnTimeout, Perm: ContainerFnPermission{ AllowNetwork: opts.AllowNetwork, // mounts are disabled for render operations (currently) @@ -181,6 +191,7 @@ func NewRunner( eFn := &ExecFn{ Path: execPath, Args: execArgs, + Timeout: fnTimeout, FnResult: fnResult, } fltr.Run = eFn.Run diff --git a/pkg/fn/runtime/runner_test.go b/pkg/fn/runtime/runner_test.go index 9208aa4dc2..35dc9cf4e2 100644 --- a/pkg/fn/runtime/runner_test.go +++ b/pkg/fn/runtime/runner_test.go @@ -21,9 +21,11 @@ import ( "context" "io" "os" + "os/exec" "path/filepath" "strings" "testing" + "time" fnresultv1 "github.com/kptdev/kpt/api/fnresult/v1" kptfilev1 "github.com/kptdev/kpt/api/kptfile/v1" @@ -1123,7 +1125,6 @@ func TestPrintFnResult(t *testing.T) { }) } } - // TestFunctionRunner_do_AcceptsNamelessList: a nameless *List-kind // resource (e.g. ConfigMapList) must pass do()'s validation on both // the input and output side, matching krmvalidate.IsKRM's exemption @@ -1155,3 +1156,34 @@ items: [] _, err = fr.do(nodes) assert.NoError(t, err, "a nameless *List resource must not be rejected as non-KRM") } + +func TestNewRunner_StepTimeout(t *testing.T) { + if _, err := exec.LookPath("sleep"); err != nil { + t.Skip("skipping exec timeout test: no sleep binary found") + } + + out := &bytes.Buffer{} + ctx := printer.WithContext(context.Background(), printer.New(out, out)) + opts := runneroptions.RunnerOptions{} + opts.InitDefaults(runneroptions.GHCRImagePrefix) + + fnResults := fnresultv1.NewResultList() + fr, err := NewRunner(ctx, filesys.MakeFsInMemory(), &kptfilev1.Function{Exec: "sleep 30", Timeout: "100ms"}, + "", fnResults, opts, nil) + require.NoError(t, err) + + start := time.Now() + _, err = fr.Filter(nil) + assert.Error(t, err) + assert.Less(t, time.Since(start), 5*time.Second) + require.Len(t, fnResults.Items, 1) +} + +func TestNewRunner_InvalidTimeout(t *testing.T) { + opts := runneroptions.RunnerOptions{} + opts.InitDefaults(runneroptions.GHCRImagePrefix) + fnResults := fnresultv1.NewResultList() + _, err := NewRunner(context.Background(), filesys.MakeFsInMemory(), &kptfilev1.Function{Exec: "sleep 30", Timeout: "not-a-duration"}, + "", fnResults, opts, nil) + assert.ErrorContains(t, err, "invalid function timeout \"not-a-duration\"") +} diff --git a/pkg/lib/kptops/render_executor_test.go b/pkg/lib/kptops/render_executor_test.go index 61c58141ad..0da0a926aa 100644 --- a/pkg/lib/kptops/render_executor_test.go +++ b/pkg/lib/kptops/render_executor_test.go @@ -18,9 +18,11 @@ import ( "bytes" "context" "fmt" + "os/exec" "path/filepath" "strings" "testing" + "time" fnresultv1 "github.com/kptdev/kpt/api/fnresult/v1" kptfilev1 "github.com/kptdev/kpt/api/kptfile/v1" @@ -397,6 +399,46 @@ func TestRenderer_Execute_RenderOrder(t *testing.T) { }) } } +func TestRenderer_Execute_StepTimeout(t *testing.T) { + if _, err := exec.LookPath("sleep"); err != nil { + t.Skip("skipping render timeout test: no sleep binary found") + } + + var outputBuffer bytes.Buffer + ctx := printer.WithContext(t.Context(), printer.New(&outputBuffer, &outputBuffer)) + + mockFileSystem := filesys.MakeFsInMemory() + assert.NoError(t, mockFileSystem.Mkdir(rootString)) + assert.NoError(t, mockFileSystem.WriteFile(filepath.Join(rootString, "Kptfile"), []byte(`apiVersion: kpt.dev/v1 +kind: Kptfile +metadata: + name: root-package +pipeline: + mutators: + - exec: sleep 30 + timeout: 100ms +`))) + assert.NoError(t, mockFileSystem.WriteFile(filepath.Join(rootString, "resources.yaml"), []byte(`apiVersion: v1 +kind: ConfigMap +metadata: + name: root-cm +`))) + + opts := runneroptions.RunnerOptions{} + opts.InitDefaults(runneroptions.GHCRImagePrefix) + opts.AllowExec = true + renderer := &Renderer{ + PkgPath: rootString, + FileSystem: mockFileSystem, + RunnerOptions: opts, + Output: &bytes.Buffer{}, + } + + start := time.Now() + _, err := renderer.Execute(ctx) + assert.Error(t, err) + assert.Less(t, time.Since(start), 10*time.Second) +} func TestRunPipeline_SubpkgNameDisplay(t *testing.T) { tests := []struct { name string