From f13362b0eeff501041eb466edc647d2df0294b18 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Fri, 13 Nov 2026 19:07:44 +0300 Subject: [PATCH 1/4] fix(api): make monitor watch versions usable as delete preconditions A watch event triggered by a WorkloadMonitor carries the monitor's resourceVersion, so a monitor-only status change reaches informer handlers: client-go treats an update with an unchanged resourceVersion as a resync and hides it from them. That version never equals the HelmRelease's, though, so a delete with it as a precondition always failed, and its spec came from the informer cache, which can lag behind the monitor revision. The event now builds the Application from a release no older than the monitor revision and carries the newer of the two versions. HelmReleases and WorkloadMonitors are stored in the same etcd, so their versions are revisions of one sequence, and a value this API hands out that is newer than the live release names the current spec. A resourceVersion precondition on delete is therefore checked against the live release and only an older one is a conflict; the delete itself then carries the live version. The two backing watches are not ordered, so a monitor event can be processed after a release event that is newer than the monitor, and a resumed watch can replay a monitor before the release the client already holds. When the event would carry the version the client may hold, which without anything sent for the object yet means any release version, it falls back to the monitor's own version and the object's version steps back. A delete with that version from the client's cache gets a conflict until the object's next release event or monitor change; no write is lost. The release is read live when the cache does not have it or has one older than the monitor revision; otherwise the cached release already pairs its spec with its own version. A watch start replays every existing monitor as ADDED, so a watch that starts or reconnects reads live once for each monitor written after its release last changed, and each later monitor status change costs at most one read per open watch. Fixes: 1bae0775be19 ("feat(application): add WorkloadsReady condition and Events tab") Assisted-by: LLM Signed-off-by: Aleksei Sviridkin --- pkg/registry/apps/application/rest.go | 118 ++++- .../apps/application/rest_watch_rv_test.go | 441 ++++++++++++++++++ .../application/rest_write_options_test.go | 6 +- 3 files changed, 552 insertions(+), 13 deletions(-) create mode 100644 pkg/registry/apps/application/rest_watch_rv_test.go diff --git a/pkg/registry/apps/application/rest.go b/pkg/registry/apps/application/rest.go index aa0e24a62..817eff526 100644 --- a/pkg/registry/apps/application/rest.go +++ b/pkg/registry/apps/application/rest.go @@ -19,6 +19,7 @@ package application import ( "context" "encoding/json" + "errors" "fmt" "maps" "net/http" @@ -673,9 +674,20 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va // Construct HelmRelease name with the configured prefix helmReleaseName := r.releaseConfig.Prefix + name + // A resourceVersion precondition is judged against the live release, so + // read it uncached. + var callerRV *string + if options != nil && options.Preconditions != nil { + callerRV = options.Preconditions.ResourceVersion + } + reader := client.Reader(r.c) + if callerRV != nil { + reader = r.w + } + // Retrieve the HelmRelease before attempting to delete helmRelease := &helmv2.HelmRelease{} - err = r.c.Get(ctx, client.ObjectKey{Namespace: namespace, Name: helmReleaseName}, helmRelease, &client.GetOptions{Raw: &metav1.GetOptions{}}) + err = reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: helmReleaseName}, helmRelease, &client.GetOptions{Raw: &metav1.GetOptions{}}) if err != nil { if apierrors.IsNotFound(err) { // If HelmRelease does not exist, return NotFound error for Application @@ -694,6 +706,15 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va return nil, false, apierrors.NewNotFound(r.gvr.GroupResource(), name) } + if callerRV != nil { + if err := r.checkResourceVersion(name, *callerRV, helmRelease.ResourceVersion); err != nil { + return nil, false, err + } + options = options.DeepCopy() + liveRV := helmRelease.ResourceVersion + options.Preconditions.ResourceVersion = &liveRV + } + // Run the genericapiserver-supplied admission chain (validating webhooks // and ValidatingAdmissionPolicies) on the resolved Application before // removing the underlying HelmRelease. Custom REST handlers must invoke @@ -723,6 +744,39 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va return nil, true, nil } +// checkResourceVersion applies a caller's resourceVersion precondition to the +// live HelmRelease. Every resourceVersion is a revision of the same etcd. An +// Application carries the version of the release its spec came from or, on a +// WorkloadMonitor-triggered watch event, a monitor revision, which is newer +// than that release only when the release was read at or after it. A value +// newer than the live release therefore names the current spec, and only an +// older one is a conflict. +func (r *REST) checkResourceVersion(name, callerRV, liveRV string) error { + caller, err := strconv.ParseUint(callerRV, 10, 64) + if err != nil { + return apierrors.NewBadRequest(fmt.Sprintf("invalid resourceVersion %q: %v", callerRV, err)) + } + live, err := strconv.ParseUint(liveRV, 10, 64) + if err != nil { + return fmt.Errorf("HelmRelease for %s has an invalid resourceVersion %q: %w", name, liveRV, err) + } + if caller < live { + return apierrors.NewConflict(r.gvr.GroupResource(), name, errors.New("the object has been modified; please apply your changes to the latest version and try again")) + } + return nil +} + +// newerResourceVersion returns whichever of two numeric resourceVersions is +// higher, preferring b when either does not parse. +func newerResourceVersion(a, b string) string { + av, aErr := strconv.ParseUint(a, 10, 64) + bv, bErr := strconv.ParseUint(b, 10, 64) + if aErr != nil || bErr != nil || bv >= av { + return b + } + return a +} + // Watch sets up a watch on HelmReleases, filters them based on application labels, and converts events to Applications func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error) { namespace, err := r.getNamespace(ctx) @@ -871,7 +925,12 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio // workload whose status flips during the snapshot window (after the // Application ADDED but before the bookmark) and then stops changing // would leave the client with a stale WorkloadsReady forever. - var pendingWMEvents []watch.Event + type monitorEvent struct { + event watch.Event + monitorRV string + releaseRV string + } + var pendingWMEvents []monitorEvent // Get the starting resourceVersion from options // If client provides resourceVersion (e.g., from a previous List), we should skip @@ -895,9 +954,38 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio } } + // lastSent holds, per Application, the resourceVersion of the last + // event this watch sent. + lastSent := map[client.ObjectKey]string{} + remember := func(app *appsv1alpha1.Application, eventType watch.EventType) { + key := client.ObjectKey{Namespace: app.Namespace, Name: app.Name} + if eventType == watch.Deleted { + delete(lastSent, key) + return + } + lastSent[key] = app.ResourceVersion + } + + // sendMonitorEvent falls back to the monitor's own resourceVersion + // when the event might repeat the one the client already holds, which + // a shared informer hides from its handlers. Without an entry for the + // object, a client resuming this watch may hold any release version, + // so the release's own version counts as held. The object the client + // caches from a fallback event gets a conflict on a precondition-checked + // delete until its next event. + sendMonitorEvent := func(me monitorEvent) bool { + app := me.event.Object.(*appsv1alpha1.Application) + last, known := lastSent[client.ObjectKey{Namespace: app.Namespace, Name: app.Name}] + if (known && app.ResourceVersion == last) || (!known && app.ResourceVersion == me.releaseRV) { + app.SetResourceVersion(me.monitorRV) + } + remember(app, me.event.Type) + return send(me.event) + } + drainPendingWMEvents := func() bool { for _, ev := range pendingWMEvents { - if !send(ev) { + if !sendMonitorEvent(ev) { return false } } @@ -1012,6 +1100,7 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio // When startingRV == 0, always send ADDED events (client wants full state) // Send event to custom watcher + remember(&app, event.Type) if !send(watch.Event{Type: event.Type, Object: &app}) { return } @@ -1070,10 +1159,19 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio } else if !fieldFilter.MatchesNamespace(hrNS) { continue } + // The event's resourceVersion may be the monitor's, which a + // Delete precondition accepts as current while the release has + // not moved past it. A cached release older than the monitor + // revision could pair a stale spec with that version, so only + // then is the release read live. + hrKey := client.ObjectKey{Namespace: hrNS, Name: hrName} hr := &helmv2.HelmRelease{} - if err := r.c.Get(ctx, client.ObjectKey{Namespace: hrNS, Name: hrName}, hr); err != nil { - klog.V(4).Infof("Cannot find HelmRelease %s/%s for WorkloadMonitor event: %v", hrNS, hrName, err) - continue + if err := r.c.Get(ctx, hrKey, hr); err != nil || newerResourceVersion(wm.GetResourceVersion(), hr.GetResourceVersion()) != hr.GetResourceVersion() { + hr = &helmv2.HelmRelease{} + if err := r.w.Get(ctx, hrKey, hr); err != nil { + klog.V(4).Infof("Cannot find HelmRelease %s/%s for WorkloadMonitor event: %v", hrNS, hrName, err) + continue + } } // Pass the fresh WorkloadMonitor so conversion uses the latest // operational status even if the cache (r.c) has not yet @@ -1094,10 +1192,8 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio continue } } - // Use the WorkloadMonitor's ResourceVersion for the emitted event - // so clients see a monotonically increasing RV and don't skip this update. - app.SetResourceVersion(wm.GetResourceVersion()) - outEvent := watch.Event{Type: watch.Modified, Object: &app} + app.SetResourceVersion(newerResourceVersion(wm.GetResourceVersion(), hr.GetResourceVersion())) + outEvent := monitorEvent{event: watch.Event{Type: watch.Modified, Object: &app}, monitorRV: wm.GetResourceVersion(), releaseRV: hr.GetResourceVersion()} // Buffer WM-triggered events that arrive before the // initial-events-end bookmark. They will be replayed in order // immediately after the bookmark is emitted. @@ -1106,7 +1202,7 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio continue } bookmarker.Observe(wm.GetResourceVersion()) - if !send(outEvent) { + if !sendMonitorEvent(outEvent) { return } diff --git a/pkg/registry/apps/application/rest_watch_rv_test.go b/pkg/registry/apps/application/rest_watch_rv_test.go new file mode 100644 index 000000000..a8c141cfc --- /dev/null +++ b/pkg/registry/apps/application/rest_watch_rv_test.go @@ -0,0 +1,441 @@ +package application + +import ( + "context" + "encoding/json" + "strconv" + "testing" + "time" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" + "github.com/cozystack/cozystack/pkg/config" + helmv2 "github.com/fluxcd/helm-controller/api/v2" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/watch" + "k8s.io/apiserver/pkg/endpoints/request" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +// rvWatchFixture models the two clients REST uses: c reads from an informer +// cache and writes to the API server, w talks to the API server directly. +// The cache can be left behind the live release, and the HelmRelease and +// WorkloadMonitor watches are fake watchers the test drives. +type rvWatchFixture struct { + rest *REST + cache client.Client + live client.WithWatch + hrW *watch.FakeWatcher + wmW *watch.FakeWatcher + // liveReleaseGets counts HelmRelease reads that bypass the cache. The + // watch goroutine and the test both update it; receiving an event from + // the watch orders the watch's updates before the test's next access. + liveReleaseGets int +} + +var rvReleaseKey = client.ObjectKey{Namespace: "default", Name: "postgresql-mydb"} + +func newRVWatchFixture(t *testing.T) *rvWatchFixture { + t.Helper() + scheme := runtime.NewScheme() + if err := cozyv1alpha1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if err := helmv2.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + release := func() *helmv2.HelmRelease { + return &helmv2.HelmRelease{ + ObjectMeta: metav1.ObjectMeta{ + Name: rvReleaseKey.Name, + Namespace: rvReleaseKey.Namespace, + Labels: map[string]string{ + ApplicationKindLabel: "PostgreSQL", + ApplicationGroupLabel: appsv1alpha1.GroupName, + ApplicationNameLabel: "mydb", + }, + }, + Spec: helmv2.HelmReleaseSpec{Values: &apiextensionsv1.JSON{Raw: []byte(`{"marker":"cached"}`)}}, + } + } + + f := &rvWatchFixture{hrW: watch.NewFake(), wmW: watch.NewFake()} + liveStore := fake.NewClientBuilder().WithScheme(scheme).WithObjects(release()).Build() + f.live = interceptor.NewClient(liveStore, interceptor.Funcs{ + Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*helmv2.HelmRelease); ok { + f.liveReleaseGets++ + } + return c.Get(ctx, key, obj, opts...) + }, + Watch: func(_ context.Context, _ client.WithWatch, list client.ObjectList, _ ...client.ListOption) (watch.Interface, error) { + if _, ok := list.(*cozyv1alpha1.WorkloadMonitorList); ok { + return f.wmW, nil + } + return f.hrW, nil + }, + }) + f.cache = interceptor.NewClient(fake.NewClientBuilder().WithScheme(scheme).WithObjects(release()).Build(), interceptor.Funcs{ + Delete: func(ctx context.Context, _ client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + return liveStore.Delete(ctx, obj, opts...) + }, + }) + f.rest = NewREST(f.cache, f.live, &config.Resource{ + Application: config.ApplicationConfig{Kind: "PostgreSQL", Plural: "postgresqls", Singular: "postgresql"}, + Release: config.ReleaseConfig{Prefix: "postgresql-"}, + }) + return f +} + +func (f *rvWatchFixture) liveRelease(t *testing.T) *helmv2.HelmRelease { + t.Helper() + hr := &helmv2.HelmRelease{} + if err := f.live.Get(context.Background(), rvReleaseKey, hr); err != nil { + t.Fatal(err) + } + return hr +} + +// advanceLive writes a new spec to the live release only, leaving the cache +// one version behind, and returns the new live release. +func (f *rvWatchFixture) advanceLive(t *testing.T, marker string) *helmv2.HelmRelease { + t.Helper() + hr := f.liveRelease(t) + before := hr.ResourceVersion + hr.Spec.Values = &apiextensionsv1.JSON{Raw: []byte(`{"marker":"` + marker + `"}`)} + if err := f.live.Update(context.Background(), hr); err != nil { + t.Fatal(err) + } + if hr.ResourceVersion == before { + t.Fatal("fake client did not advance the release version") + } + return hr +} + +func (f *rvWatchFixture) monitorEvent(rv string) { + f.wmW.Modify(&cozyv1alpha1.WorkloadMonitor{ + ObjectMeta: metav1.ObjectMeta{ + Name: "mon-1", + Namespace: "default", + ResourceVersion: rv, + Labels: map[string]string{ + appsv1alpha1.ApplicationKindLabel: "PostgreSQL", + appsv1alpha1.ApplicationGroupLabel: appsv1alpha1.GroupName, + appsv1alpha1.ApplicationNameLabel: "mydb", + }, + }, + Status: cozyv1alpha1.WorkloadMonitorStatus{Operational: new(true)}, + }) +} + +func startRVWatch(t *testing.T, f *rvWatchFixture) (context.Context, watch.Interface) { + t.Helper() + ctx, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) + t.Cleanup(cancel) + w, err := f.rest.Watch(ctx, &metainternalversion.ListOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(w.Stop) + return ctx, w +} + +func nextApplication(t *testing.T, w watch.Interface) *appsv1alpha1.Application { + t.Helper() + select { + case ev, ok := <-w.ResultChan(): + if !ok { + t.Fatal("watch closed") + } + app, ok := ev.Object.(*appsv1alpha1.Application) + if !ok { + t.Fatalf("got %s %T, want an Application", ev.Type, ev.Object) + } + return app + case <-time.After(5 * time.Second): + t.Fatal("no event") + } + return nil +} + +func specMarker(t *testing.T, app *appsv1alpha1.Application) string { + t.Helper() + var v struct { + Marker string `json:"marker"` + } + if app.Spec == nil { + t.Fatal("application has no spec") + } + if err := json.Unmarshal(app.Spec.Raw, &v); err != nil { + t.Fatal(err) + } + return v.Marker +} + +func rvNumber(t *testing.T, rv string) uint64 { + t.Helper() + n, err := strconv.ParseUint(rv, 10, 64) + if err != nil { + t.Fatalf("resourceVersion %q: %v", rv, err) + } + return n +} + +// The spec in a monitor-triggered event must come from a release read no +// earlier than the monitor revision the event carries, or a precondition on +// that version would accept a write built on a stale spec. +func TestWatchMonitorEventReadsReleaseLive(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + f.advanceLive(t, "live") + + f.monitorEvent("5000") + app := nextApplication(t, w) + if got := specMarker(t, app); got != "live" { + t.Fatalf("spec marker %q, want the live release's", got) + } + if app.ResourceVersion != "5000" { + t.Fatalf("resourceVersion %q, want the monitor's 5000", app.ResourceVersion) + } + if f.liveReleaseGets != 2 { + t.Fatalf("%d live release reads, want the test's own plus one for the event", f.liveReleaseGets) + } +} + +// A release cached at or past the monitor revision already pairs its spec +// with its own version, so the event uses it without a live read: a watch +// replays every existing monitor as ADDED when it starts. With nothing sent +// for the object yet, the client may hold that release version, so the event +// carries the monitor's. +func TestWatchMonitorEventUsesCacheNotOlderThanMonitor(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + cached := &helmv2.HelmRelease{} + if err := f.cache.Get(context.Background(), rvReleaseKey, cached); err != nil { + t.Fatal(err) + } + f.advanceLive(t, "live") + gets := f.liveReleaseGets + + f.monitorEvent("1") + app := nextApplication(t, w) + if got := specMarker(t, app); got != "cached" { + t.Fatalf("spec marker %q, want the cached release's", got) + } + if app.ResourceVersion != "1" { + t.Fatalf("resourceVersion %q, want the monitor's 1 rather than the cached release's %q", app.ResourceVersion, cached.ResourceVersion) + } + if f.liveReleaseGets != gets { + t.Fatalf("%d live release reads for a monitor older than the cached release, want none", f.liveReleaseGets-gets) + } +} + +// Shared informers deliver an update whose resourceVersion equals the stored +// one only to handlers due for a resync, so each monitor-only change must +// arrive with a resourceVersion different from the previous event's. +func TestWatchMonitorOnlyChangeAdvancesVersion(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + + f.hrW.Modify(live.DeepCopy()) + prev := rvNumber(t, nextApplication(t, w).ResourceVersion) + for _, rv := range []string{"5000", "5001"} { + f.monitorEvent(rv) + got := rvNumber(t, nextApplication(t, w).ResourceVersion) + if got <= prev { + t.Fatalf("monitor event resourceVersion %d, want above the previous event's %d", got, prev) + } + prev = got + } +} + +// A monitor event processed after the release event it predates must not +// repeat the resourceVersion the client already holds, or a shared informer +// hides it from its handlers. It falls back to the monitor's older version, +// and a delete with that version gets a conflict instead of acting on a spec +// the client may not have. +func TestWatchLateMonitorEventDoesNotRepeatVersion(t *testing.T) { + f := newRVWatchFixture(t) + ctx, w := startRVWatch(t, f) + live := f.liveRelease(t) + + f.hrW.Modify(live.DeepCopy()) + if got := nextApplication(t, w).ResourceVersion; got != live.ResourceVersion { + t.Fatalf("release event resourceVersion %q, want %q", got, live.ResourceVersion) + } + f.monitorEvent("1") + rv := nextApplication(t, w).ResourceVersion + if rv != "1" { + t.Fatalf("late monitor event resourceVersion %q, want the monitor's 1 rather than the held %q", rv, live.ResourceVersion) + } + _, _, err := f.rest.Delete(ctx, "mydb", nil, &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{ResourceVersion: &rv}}) + if !apierrors.IsConflict(err) { + t.Fatalf("delete with the monitor's older version: got %v, want Conflict", err) + } +} + +// A release the client already holds is skipped on a resumed watch, so the +// next monitor event must not repeat its version either. +func TestWatchLateMonitorEventAfterSkippedReplay(t *testing.T) { + f := newRVWatchFixture(t) + live := f.liveRelease(t) + w := startRVWatchFrom(t, f, live.ResourceVersion) + + f.hrW.Add(live.DeepCopy()) + f.monitorEvent("1") + if rv := nextApplication(t, w).ResourceVersion; rv != "1" { + t.Fatalf("monitor event after the skipped replay has resourceVersion %q, want the monitor's 1 rather than the held %q", rv, live.ResourceVersion) + } +} + +// Once this watch has sent the object a monitor version, the release version +// is no longer what the client holds, and the event can carry it. +func TestWatchMonitorEventCarriesReleaseAfterFallback(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.liveRelease(t) + + f.monitorEvent("1") + if rv := nextApplication(t, w).ResourceVersion; rv != "1" { + t.Fatalf("first monitor event resourceVersion %q, want the monitor's 1", rv) + } + f.monitorEvent("2") + if rv := nextApplication(t, w).ResourceVersion; rv != live.ResourceVersion { + t.Fatalf("second monitor event resourceVersion %q, want the release's %q", rv, live.ResourceVersion) + } +} + +// A release event in between makes the release version the held one again. +func TestWatchReleaseEventResetsHeldVersion(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.liveRelease(t) + + f.monitorEvent("1") + nextApplication(t, w) + f.hrW.Modify(live.DeepCopy()) + if rv := nextApplication(t, w).ResourceVersion; rv != live.ResourceVersion { + t.Fatalf("release event resourceVersion %q, want %q", rv, live.ResourceVersion) + } + f.monitorEvent("2") + if rv := nextApplication(t, w).ResourceVersion; rv != "2" { + t.Fatalf("monitor event after the release event has resourceVersion %q, want the monitor's 2 rather than the held %q", rv, live.ResourceVersion) + } +} + +func startRVWatchFrom(t *testing.T, f *rvWatchFixture, resourceVersion string) watch.Interface { + t.Helper() + ctx, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) + t.Cleanup(cancel) + w, err := f.rest.Watch(ctx, &metainternalversion.ListOptions{ResourceVersion: resourceVersion}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(w.Stop) + return w +} + +// On a resumed watch the replayed monitor can arrive before the replayed +// release, so nothing is known yet about the version the client holds. +func TestWatchResumedMonitorReplayBeforeRelease(t *testing.T) { + f := newRVWatchFixture(t) + live := f.liveRelease(t) + w := startRVWatchFrom(t, f, live.ResourceVersion) + + f.monitorEvent("1") + if rv := nextApplication(t, w).ResourceVersion; rv != "1" { + t.Fatalf("replayed monitor event has resourceVersion %q, want the monitor's 1 rather than the possibly held %q", rv, live.ResourceVersion) + } +} + +// A fallback event steps the client's resume point below versions it holds, +// so a resumed client can hold a release version above the one it resumes +// from. +func TestWatchResumedBelowHeldReleaseVersion(t *testing.T) { + f := newRVWatchFixture(t) + live := f.liveRelease(t) + if rvNumber(t, live.ResourceVersion) <= 500 { + t.Fatalf("fixture release version %q must be above the resume point", live.ResourceVersion) + } + w := startRVWatchFrom(t, f, "500") + + f.monitorEvent("1") + if rv := nextApplication(t, w).ResourceVersion; rv != "1" { + t.Fatalf("replayed monitor event has resourceVersion %q, want the monitor's 1 rather than the possibly held %q", rv, live.ResourceVersion) + } +} + +func TestDeleteWithVersionFromMonitorEvent(t *testing.T) { + f := newRVWatchFixture(t) + ctx, w := startRVWatch(t, f) + f.advanceLive(t, "live") + + f.monitorEvent("5000") + rv := nextApplication(t, w).ResourceVersion + _, _, err := f.rest.Delete(ctx, "mydb", nil, &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{ResourceVersion: &rv}}) + if err != nil { + t.Fatalf("delete with resourceVersion %q from the watch event: %v", rv, err) + } + if err := f.live.Get(context.Background(), rvReleaseKey, &helmv2.HelmRelease{}); !apierrors.IsNotFound(err) { + t.Fatalf("release still present after delete: %v", err) + } +} + +func TestDeleteRejectsVersionOlderThanLive(t *testing.T) { + f := newRVWatchFixture(t) + cached := &helmv2.HelmRelease{} + if err := f.cache.Get(context.Background(), rvReleaseKey, cached); err != nil { + t.Fatal(err) + } + f.advanceLive(t, "live") + + ctx := request.WithNamespace(context.Background(), "default") + rv := cached.ResourceVersion + _, _, err := f.rest.Delete(ctx, "mydb", nil, &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{ResourceVersion: &rv}}) + if !apierrors.IsConflict(err) { + t.Fatalf("delete with stale resourceVersion %q: got %v, want Conflict", rv, err) + } + if err := f.live.Get(context.Background(), rvReleaseKey, &helmv2.HelmRelease{}); err != nil { + t.Fatalf("release gone after a rejected delete: %v", err) + } +} + +func TestCheckResourceVersion(t *testing.T) { + r := newTestRESTWithSchemesFromClient(nil) + for _, tc := range []struct { + caller string + check func(error) bool + }{ + {"100", func(err error) bool { return err == nil }}, + {"101", func(err error) bool { return err == nil }}, + {"99", apierrors.IsConflict}, + {"0", apierrors.IsConflict}, + {"", apierrors.IsBadRequest}, + {"abc", apierrors.IsBadRequest}, + } { + if err := r.checkResourceVersion("mydb", tc.caller, "100"); !tc.check(err) { + t.Errorf("caller resourceVersion %q against live 100: unexpected result %v", tc.caller, err) + } + } +} + +func TestNewerResourceVersion(t *testing.T) { + for _, tc := range []struct{ a, b, want string }{ + {"7", "5", "7"}, + {"5", "7", "7"}, + {"7", "7", "7"}, + {"x", "5", "5"}, + {"7", "y", "y"}, + } { + if got := newerResourceVersion(tc.a, tc.b); got != tc.want { + t.Errorf("newerResourceVersion(%q, %q) = %q, want %q", tc.a, tc.b, got, tc.want) + } + } +} diff --git a/pkg/registry/apps/application/rest_write_options_test.go b/pkg/registry/apps/application/rest_write_options_test.go index 823a7327c..fd6417c3f 100644 --- a/pkg/registry/apps/application/rest_write_options_test.go +++ b/pkg/registry/apps/application/rest_write_options_test.go @@ -58,7 +58,7 @@ func newOptionsTestREST(t *testing.T, funcs interceptor.Funcs, objects ...client WithObjects(objects...). WithInterceptorFuncs(funcs). Build() - return NewREST(c, nil, &config.Resource{ + return NewREST(c, c, &config.Resource{ Application: config.ApplicationConfig{ Kind: "PostgreSQL", Plural: "postgresqls", @@ -185,7 +185,9 @@ func TestDeletePropagatesWriteOptions(t *testing.T) { grace := int64(3) propagation := metav1.DeletePropagationForeground uid := types.UID("expected-uid") - rv := "17" + // The version the fake client stamps on seeded objects: a resourceVersion + // precondition is checked against the live release. + rv := "999" want := &metav1.DeleteOptions{ GracePeriodSeconds: &grace, Preconditions: &metav1.Preconditions{UID: &uid, ResourceVersion: &rv}, From 0ccb3fead7835fb6aef4022512c089513607ad34 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Mon, 16 Nov 2026 13:10:44 +0300 Subject: [PATCH 2/4] fix(api): retry the live release read behind a monitor event When the cached release is older than the monitor revision, the watch reads the release live so that an event never pairs a stale spec with the monitor's version. A transient error on that read dropped the monitor event. Both streams are plain API watches, so nothing replayed it, and a client kept the old WorkloadsReady state until the next change of either object. Retry the live read a few times before giving the event up. This covers a failure shorter than the retry window; a longer one still drops the event, as a cache miss did before. A release that is gone is not retried: the event is dropped after one read. The live reads run under a context that Stop cancels, so a stopped watch does not wait on the API server. The tests also pin the two paths that were untested: a release the cache has not seen yet is read live and delivered, and a release that is gone everywhere produces no event. Fixes: f13362b0eeff ("fix(api): make monitor watch versions usable as delete preconditions") Assisted-by: LLM Signed-off-by: Aleksei Sviridkin --- pkg/registry/apps/application/rest.go | 34 +++- .../apps/application/rest_watch_rv_test.go | 183 +++++++++++++++++- 2 files changed, 214 insertions(+), 3 deletions(-) diff --git a/pkg/registry/apps/application/rest.go b/pkg/registry/apps/application/rest.go index 817eff526..d6c18b410 100644 --- a/pkg/registry/apps/application/rest.go +++ b/pkg/registry/apps/application/rest.go @@ -777,6 +777,13 @@ func newerResourceVersion(a, b string) string { return a } +// Bounded so that an apiserver outage drops the monitor event instead of +// holding the watch goroutine. +const ( + liveReleaseReadAttempts = 3 + liveReleaseReadRetryDelay = 100 * time.Millisecond +) + // Watch sets up a watch on HelmReleases, filters them based on application labels, and converts events to Applications func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error) { namespace, err := r.getNamespace(ctx) @@ -916,6 +923,17 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio if wmWatcherForCleanup != nil { defer wmWatcherForCleanup.Stop() } + // Live reads use a context that Stop cancels, so a stopped watch + // never waits on the API server. + readCtx, cancelReads := context.WithCancel(ctx) + defer cancelReads() + go func() { + select { + case <-customW.stopChan: + cancelReads() + case <-readCtx.Done(): + } + }() // Buffer of WorkloadMonitor events that arrived before the initial // snapshot finished. The watch-list contract requires the stream to @@ -1168,8 +1186,20 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio hr := &helmv2.HelmRelease{} if err := r.c.Get(ctx, hrKey, hr); err != nil || newerResourceVersion(wm.GetResourceVersion(), hr.GetResourceVersion()) != hr.GetResourceVersion() { hr = &helmv2.HelmRelease{} - if err := r.w.Get(ctx, hrKey, hr); err != nil { - klog.V(4).Infof("Cannot find HelmRelease %s/%s for WorkloadMonitor event: %v", hrNS, hrName, err) + // Nothing replays a monitor event this watch drops, so a + // transient failure of the live read is retried briefly. + // A missing release is final. + liveErr := r.w.Get(readCtx, hrKey, hr) + for attempt := 1; liveErr != nil && !apierrors.IsNotFound(liveErr) && attempt < liveReleaseReadAttempts; attempt++ { + select { + case <-readCtx.Done(): + return + case <-time.After(liveReleaseReadRetryDelay): + } + liveErr = r.w.Get(readCtx, hrKey, hr) + } + if liveErr != nil { + klog.V(4).Infof("Cannot find HelmRelease %s/%s for WorkloadMonitor event: %v", hrNS, hrName, liveErr) continue } } diff --git a/pkg/registry/apps/application/rest_watch_rv_test.go b/pkg/registry/apps/application/rest_watch_rv_test.go index a8c141cfc..f3c30ac38 100644 --- a/pkg/registry/apps/application/rest_watch_rv_test.go +++ b/pkg/registry/apps/application/rest_watch_rv_test.go @@ -3,6 +3,7 @@ package application import ( "context" "encoding/json" + "errors" "strconv" "testing" "time" @@ -37,6 +38,15 @@ type rvWatchFixture struct { // watch goroutine and the test both update it; receiving an event from // the watch orders the watch's updates before the test's next access. liveReleaseGets int + // liveReleaseErrs are returned by the next live HelmRelease reads, one + // per read, before reads reach the store again. + liveReleaseErrs []error + // liveReleaseHang makes live HelmRelease reads block until their context + // ends, like a request to an API server that never answers. + liveReleaseHang bool + // cacheStore is the store behind cache, for tests that leave the cache + // without the release. + cacheStore client.WithWatch } var rvReleaseKey = client.ObjectKey{Namespace: "default", Name: "postgresql-mydb"} @@ -71,6 +81,15 @@ func newRVWatchFixture(t *testing.T) *rvWatchFixture { Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { if _, ok := obj.(*helmv2.HelmRelease); ok { f.liveReleaseGets++ + if f.liveReleaseHang { + <-ctx.Done() + return ctx.Err() + } + if len(f.liveReleaseErrs) > 0 { + err := f.liveReleaseErrs[0] + f.liveReleaseErrs = f.liveReleaseErrs[1:] + return err + } } return c.Get(ctx, key, obj, opts...) }, @@ -81,7 +100,8 @@ func newRVWatchFixture(t *testing.T) *rvWatchFixture { return f.hrW, nil }, }) - f.cache = interceptor.NewClient(fake.NewClientBuilder().WithScheme(scheme).WithObjects(release()).Build(), interceptor.Funcs{ + f.cacheStore = fake.NewClientBuilder().WithScheme(scheme).WithObjects(release()).Build() + f.cache = interceptor.NewClient(f.cacheStore, interceptor.Funcs{ Delete: func(ctx context.Context, _ client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { return liveStore.Delete(ctx, obj, opts...) }, @@ -312,6 +332,167 @@ func TestWatchMonitorEventCarriesReleaseAfterFallback(t *testing.T) { } } +// expectNoApplication fails if the watch delivers anything within the wait, +// then sends a release event and receives it so that the watch goroutine's +// earlier bookkeeping is ordered before the caller's next read of it. +func expectNoApplication(t *testing.T, f *rvWatchFixture, w watch.Interface, release *helmv2.HelmRelease) { + t.Helper() + select { + case ev := <-w.ResultChan(): + t.Fatalf("unexpected %s event", ev.Type) + case <-time.After((liveReleaseReadAttempts + 2) * liveReleaseReadRetryDelay): + } + f.hrW.Modify(release) + nextApplication(t, w) +} + +// A transient failure of the live read must not cost the client the monitor +// change: nothing replays it, so the read is retried. +func TestWatchMonitorEventRetriesLiveRead(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + timeout := errors.New("etcdserver: request timed out") + f.liveReleaseErrs = []error{timeout, timeout} + + f.monitorEvent(live.ResourceVersion) + app := nextApplication(t, w) + if got := f.liveReleaseGets - readsBefore; got != 3 { + t.Fatalf("live release reads %d, want two failed attempts and one success", got) + } + if got := specMarker(t, app); got != "live" { + t.Fatalf("spec marker %q, want the live spec", got) + } + if app.ResourceVersion != live.ResourceVersion { + t.Fatalf("resourceVersion %q, want the live release's %q", app.ResourceVersion, live.ResourceVersion) + } +} + +// A read that keeps failing is given up after the last attempt, so a broken +// apiserver cannot hold the watch goroutine. +func TestWatchMonitorEventGivesUpAfterRetries(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + timeout := errors.New("etcdserver: request timed out") + for range liveReleaseReadAttempts { + f.liveReleaseErrs = append(f.liveReleaseErrs, timeout) + } + + f.monitorEvent(live.ResourceVersion) + expectNoApplication(t, f, w, live) + if got := f.liveReleaseGets - readsBefore; got != liveReleaseReadAttempts { + t.Fatalf("live release reads %d, want %d attempts and no more", got, liveReleaseReadAttempts) + } +} + +// stopDuringLiveReadRetry queues a failure for every attempt, sends a monitor +// event and calls stop while the watch waits between attempts. The watch must +// close after the one read made before the stop. +func stopDuringLiveReadRetry(t *testing.T, f *rvWatchFixture, w watch.Interface, stop func()) { + t.Helper() + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + timeout := errors.New("etcdserver: request timed out") + for range liveReleaseReadAttempts { + f.liveReleaseErrs = append(f.liveReleaseErrs, timeout) + } + + f.monitorEvent(live.ResourceVersion) + stop() + select { + case ev, ok := <-w.ResultChan(): + if ok { + t.Fatalf("unexpected %s event", ev.Type) + } + case <-time.After(5 * time.Second): + t.Fatal("watch still open") + } + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want the one before the stop", got) + } +} + +func TestWatchStopEndsLiveReadRetry(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + stopDuringLiveReadRetry(t, f, w, w.Stop) +} + +func TestWatchContextCancelEndsLiveReadRetry(t *testing.T) { + f := newRVWatchFixture(t) + ctx, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) + t.Cleanup(cancel) + w, err := f.rest.Watch(ctx, &metainternalversion.ListOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(w.Stop) + stopDuringLiveReadRetry(t, f, w, cancel) +} + +// A live read that never answers must not outlive the watch: Stop cancels +// the read's context, and the watch closes. +func TestWatchStopCancelsHungLiveRead(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + f.liveReleaseHang = true + + f.monitorEvent(live.ResourceVersion) + w.Stop() + select { + case ev, ok := <-w.ResultChan(): + if ok { + t.Fatalf("unexpected %s event", ev.Type) + } + case <-time.After(5 * time.Second): + t.Fatal("watch still open while a live read hangs") + } +} + +// A release that is gone is final: the event is dropped after one read, +// without retries that would delay the next event. +func TestWatchMonitorEventDroppedWhenReleaseIsGone(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + release := f.liveRelease(t) + for _, c := range []client.Client{f.cacheStore, f.live} { + if err := c.Delete(context.Background(), release.DeepCopy()); err != nil { + t.Fatal(err) + } + } + readsBefore := f.liveReleaseGets + + f.monitorEvent(strconv.FormatUint(rvNumber(t, release.ResourceVersion)+1, 10)) + expectNoApplication(t, f, w, release) + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want a single read", got) + } +} + +// A release the cache has not seen yet is read live and delivered. +func TestWatchMonitorEventReadsReleaseMissingFromCache(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + if err := f.cacheStore.Delete(context.Background(), live.DeepCopy()); err != nil { + t.Fatal(err) + } + readsBefore := f.liveReleaseGets + + f.monitorEvent(live.ResourceVersion) + app := nextApplication(t, w) + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want one", got) + } + if got := specMarker(t, app); got != "live" { + t.Fatalf("spec marker %q, want the live spec", got) + } +} + // A release event in between makes the release version the held one again. func TestWatchReleaseEventResetsHeldVersion(t *testing.T) { f := newRVWatchFixture(t) From 48d83b5f77586fa04680e0f4081b88b8bcbca82b Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Tue, 17 Nov 2026 23:02:58 +0300 Subject: [PATCH 3/4] test(api): cancel monitor live reads before retrying FakeWatcher.Modify synchronizes event receipt, not processing. A test that cancels after sending the event can lose the retry-delay window and observe more reads even when cancellation works correctly. Cancel at the first failed live read and wait for its context to end before returning the error, so the exact read count does not depend on which goroutine runs next. Fixes: 0ccb3fead783 ("fix(api): retry the live release read behind a monitor event") Assisted-by: LLM Signed-off-by: Aleksei Sviridkin --- .../apps/application/rest_watch_rv_test.go | 31 +++++++++++++------ 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/pkg/registry/apps/application/rest_watch_rv_test.go b/pkg/registry/apps/application/rest_watch_rv_test.go index f3c30ac38..06640d72e 100644 --- a/pkg/registry/apps/application/rest_watch_rv_test.go +++ b/pkg/registry/apps/application/rest_watch_rv_test.go @@ -40,7 +40,8 @@ type rvWatchFixture struct { liveReleaseGets int // liveReleaseErrs are returned by the next live HelmRelease reads, one // per read, before reads reach the store again. - liveReleaseErrs []error + liveReleaseErrs []error + onLiveReleaseError func(context.Context) // liveReleaseHang makes live HelmRelease reads block until their context // ends, like a request to an API server that never answers. liveReleaseHang bool @@ -88,6 +89,10 @@ func newRVWatchFixture(t *testing.T) *rvWatchFixture { if len(f.liveReleaseErrs) > 0 { err := f.liveReleaseErrs[0] f.liveReleaseErrs = f.liveReleaseErrs[1:] + if hook := f.onLiveReleaseError; hook != nil { + f.onLiveReleaseError = nil + hook(ctx) + } return err } } @@ -388,10 +393,9 @@ func TestWatchMonitorEventGivesUpAfterRetries(t *testing.T) { } } -// stopDuringLiveReadRetry queues a failure for every attempt, sends a monitor -// event and calls stop while the watch waits between attempts. The watch must -// close after the one read made before the stop. -func stopDuringLiveReadRetry(t *testing.T, f *rvWatchFixture, w watch.Interface, stop func()) { +// Cancel before the first failed Get returns: a send to FakeWatcher only +// orders event receipt, so cancelling after the send can lose the retry window. +func stopAtFailedLiveRead(t *testing.T, f *rvWatchFixture, w watch.Interface, stop func()) { t.Helper() live := f.advanceLive(t, "live") readsBefore := f.liveReleaseGets @@ -400,8 +404,15 @@ func stopDuringLiveReadRetry(t *testing.T, f *rvWatchFixture, w watch.Interface, f.liveReleaseErrs = append(f.liveReleaseErrs, timeout) } + f.onLiveReleaseError = func(ctx context.Context) { + stop() + select { + case <-ctx.Done(): + case <-time.After(5 * time.Second): + t.Error("live read context still open after cancellation") + } + } f.monitorEvent(live.ResourceVersion) - stop() select { case ev, ok := <-w.ResultChan(): if ok { @@ -415,13 +426,13 @@ func stopDuringLiveReadRetry(t *testing.T, f *rvWatchFixture, w watch.Interface, } } -func TestWatchStopEndsLiveReadRetry(t *testing.T) { +func TestWatchStopAtFailedLiveReadPreventsRetry(t *testing.T) { f := newRVWatchFixture(t) _, w := startRVWatch(t, f) - stopDuringLiveReadRetry(t, f, w, w.Stop) + stopAtFailedLiveRead(t, f, w, w.Stop) } -func TestWatchContextCancelEndsLiveReadRetry(t *testing.T) { +func TestWatchContextCancelAtFailedLiveReadPreventsRetry(t *testing.T) { f := newRVWatchFixture(t) ctx, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) t.Cleanup(cancel) @@ -430,7 +441,7 @@ func TestWatchContextCancelEndsLiveReadRetry(t *testing.T) { t.Fatal(err) } t.Cleanup(w.Stop) - stopDuringLiveReadRetry(t, f, w, cancel) + stopAtFailedLiveRead(t, f, w, cancel) } // A live read that never answers must not outlive the watch: Stop cancels From dff4553216b99532ac957a75a5b8a37f6cc01a3b Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Wed, 18 Nov 2026 17:29:29 +0300 Subject: [PATCH 4/4] fix(api): bound live release reads in application watches A stalled live release read holds the whole application watch event loop. End the watch when a refresh runs out of time so clients can reconnect without relying on stale cached release data. Fixes: 0ccb3fead783 ("fix(api): retry the live release read behind a monitor event") Assisted-by: LLM Signed-off-by: Aleksei Sviridkin --- pkg/registry/apps/application/rest.go | 20 ++- .../application/rest_watch_deadline_test.go | 149 ++++++++++++++++++ 2 files changed, 163 insertions(+), 6 deletions(-) create mode 100644 pkg/registry/apps/application/rest_watch_deadline_test.go diff --git a/pkg/registry/apps/application/rest.go b/pkg/registry/apps/application/rest.go index d6c18b410..a560cb7fe 100644 --- a/pkg/registry/apps/application/rest.go +++ b/pkg/registry/apps/application/rest.go @@ -777,11 +777,11 @@ func newerResourceVersion(a, b string) string { return a } -// Bounded so that an apiserver outage drops the monitor event instead of -// holding the watch goroutine. +// Watches bypass the API server's default one-minute request timeout. const ( liveReleaseReadAttempts = 3 liveReleaseReadRetryDelay = 100 * time.Millisecond + liveReleaseReadTimeout = time.Minute ) // Watch sets up a watch on HelmReleases, filters them based on application labels, and converts events to Applications @@ -1189,14 +1189,22 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio // Nothing replays a monitor event this watch drops, so a // transient failure of the live read is retried briefly. // A missing release is final. - liveErr := r.w.Get(readCtx, hrKey, hr) + liveCtx, cancelLiveRead := context.WithTimeout(readCtx, liveReleaseReadTimeout) + liveErr := r.w.Get(liveCtx, hrKey, hr) for attempt := 1; liveErr != nil && !apierrors.IsNotFound(liveErr) && attempt < liveReleaseReadAttempts; attempt++ { select { - case <-readCtx.Done(): - return + case <-liveCtx.Done(): case <-time.After(liveReleaseReadRetryDelay): } - liveErr = r.w.Get(readCtx, hrKey, hr) + if liveCtx.Err() != nil { + break + } + liveErr = r.w.Get(liveCtx, hrKey, hr) + } + readEnded := liveCtx.Err() != nil + cancelLiveRead() + if readEnded { + return } if liveErr != nil { klog.V(4).Infof("Cannot find HelmRelease %s/%s for WorkloadMonitor event: %v", hrNS, hrName, liveErr) diff --git a/pkg/registry/apps/application/rest_watch_deadline_test.go b/pkg/registry/apps/application/rest_watch_deadline_test.go new file mode 100644 index 000000000..3d4bc68f5 --- /dev/null +++ b/pkg/registry/apps/application/rest_watch_deadline_test.go @@ -0,0 +1,149 @@ +package application + +import ( + "context" + "errors" + "testing" + "testing/synctest" + "time" + + metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion" + "k8s.io/apimachinery/pkg/watch" + "k8s.io/apiserver/pkg/endpoints/request" +) + +func expectLiveReadWatchClosed(t *testing.T, w watch.Interface) { + t.Helper() + select { + case event, open := <-w.ResultChan(): + if open { + t.Fatalf("unexpected %s event instead of watch closure", event.Type) + } + default: + t.Fatal("watch remains open after the live-read deadline") + } +} + +func TestWatchHungLiveReadDeadlineClosesAndReconnects(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := newRVWatchFixture(t) + parent, w := startRVWatch(t, f) + cached := f.liveRelease(t) + f.hrW.Modify(cached.DeepCopy()) + resume := nextApplication(t, w).ResourceVersion + live := f.advanceLive(t, "before-timeout") + readsBefore := f.liveReleaseGets + entered := make(chan context.Context, 1) + f.liveReleaseErrs = []error{errors.New("live read failed")} + f.onLiveReleaseError = func(ctx context.Context) { + entered <- ctx + <-ctx.Done() + } + + readStarted := time.Now() + f.monitorEvent(live.ResourceVersion) + synctest.Wait() + var liveCtx context.Context + select { + case liveCtx = <-entered: + default: + t.Fatal("live read did not start") + } + time.Sleep(time.Minute) + synctest.Wait() + expectLiveReadWatchClosed(t, w) + if !errors.Is(liveCtx.Err(), context.DeadlineExceeded) { + t.Fatalf("live read ended with %v, want its own deadline", liveCtx.Err()) + } + deadline, bounded := liveCtx.Deadline() + if !bounded || deadline.Sub(readStarted) != time.Minute { + t.Fatalf("live read budget %v, bounded=%t, want exactly one minute", deadline.Sub(readStarted), bounded) + } + if parent.Err() != nil { + t.Fatalf("watch parent unexpectedly ended: %v", parent.Err()) + } + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want one bounded hung read", got) + } + + f.hrW, f.wmW = watch.NewFake(), watch.NewFake() + fresh := f.advanceLive(t, "after-reconnect") + reconnected := startRVWatchFrom(t, f, resume) + f.monitorEvent(fresh.ResourceVersion) + app := nextApplication(t, reconnected) + if got := specMarker(t, app); got != "after-reconnect" { + t.Fatalf("reconnected spec marker %q, want fresh live state", got) + } + if app.ResourceVersion != fresh.ResourceVersion { + t.Fatalf("reconnected version %q, want %q", app.ResourceVersion, fresh.ResourceVersion) + } + }) +} + +func TestWatchLiveReadDeadlineIncludesRetries(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + f.liveReleaseErrs = []error{errors.New("temporary live read failure")} + f.onLiveReleaseError = func(context.Context) { + time.Sleep(45 * time.Second) + f.liveReleaseHang = true + } + + f.monitorEvent(live.ResourceVersion) + synctest.Wait() + time.Sleep(time.Minute) + synctest.Wait() + expectLiveReadWatchClosed(t, w) + if got := f.liveReleaseGets - readsBefore; got != 2 { + t.Fatalf("live release reads %d, want one slow failure and one hung retry", got) + } + }) +} + +func TestWatchCancellationEndsHungLiveReadBeforeDeadline(t *testing.T) { + for _, mode := range []string{"stop", "context"} { + t.Run(mode, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := newRVWatchFixture(t) + parent, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) + t.Cleanup(cancel) + w, err := f.rest.Watch(parent, &metainternalversion.ListOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(w.Stop) + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + entered := make(chan context.Context, 1) + f.liveReleaseErrs = []error{errors.New("live read failed")} + f.onLiveReleaseError = func(ctx context.Context) { + entered <- ctx + <-ctx.Done() + } + f.monitorEvent(live.ResourceVersion) + synctest.Wait() + liveCtx := <-entered + before := time.Now() + if mode == "stop" { + w.Stop() + } else { + cancel() + } + synctest.Wait() + expectLiveReadWatchClosed(t, w) + if !errors.Is(liveCtx.Err(), context.Canceled) { + t.Fatalf("live read ended with %v, want cancellation", liveCtx.Err()) + } + if time.Since(before) != 0 { + t.Fatal("cancellation waited for a timer") + } + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want exactly one", got) + } + }) + }) + } +}