From 53402df6e854ae47ca8947159720119a400321a8 Mon Sep 17 00:00:00 2001 From: Simon Koudijs Date: Fri, 27 Nov 2026 21:31:40 +0000 Subject: [PATCH 1/5] fix(commitrequest): serve a relisted request from the list, so a new one is not claimed behind every stored one Each session lists a source cluster's CommitRequests and hands every item to consider, whose first step got the request again. A relist therefore sent one GET per stored request, finished ones included, through the provider's rate-limited client (20 QPS, burst 30), and a request created during the relist waited behind all of them for its claim: about (N - 30) / 20 seconds every five minutes. A finished or unclaimed request now takes its first step from the object the list or watch event delivered. A finished one does no source-cluster call at all until its delete-after time is near. Both are safe on an object that may be older than the stored one, because every step reads or writes conditionally before anything else. A claimed request is still read again first: its step attaches to the worker straight away, and an old event (the claim's own, arriving after the save ended) would attach a finished request a second time. Co-Authored-By: Claude Opus 5.5 --- internal/controller/commitrequest_core.go | 11 ++ internal/controller/commitrequest_server.go | 42 +++++- .../controller/commitrequest_server_test.go | 122 ++++++++++++++++++ .../controller/commitrequest_wakes_test.go | 9 +- 4 files changed, 177 insertions(+), 7 deletions(-) diff --git a/internal/controller/commitrequest_core.go b/internal/controller/commitrequest_core.go index e76cf557a..975dba8ad 100644 --- a/internal/controller/commitrequest_core.go +++ b/internal/controller/commitrequest_core.go @@ -126,6 +126,17 @@ func (c *commitRequestCore) serve( } return 0, client.IgnoreNotFound(err) } + return c.serveStored(ctx, p, cr) +} + +// serveStored takes one step for cr, as it was read from p's store: by a get, or by the list or watch +// event that delivered it, where the caller knows the step is safe on an object that may have changed +// since (servableAsDelivered). Every write is conditional on cr.ResourceVersion, so such a step fails +// with a conflict and the next one reads the request again. +func (c *commitRequestCore) serveStored( + ctx context.Context, p commitRequestPath, cr *configbutleraiv1alpha3.CommitRequest, +) (time.Duration, error) { + key := client.ObjectKeyFromObject(cr) if !cr.DeletionTimestamp.IsZero() { c.inFlight.forget(p, key) return 0, nil diff --git a/internal/controller/commitrequest_server.go b/internal/controller/commitrequest_server.go index 5a78eba5a..654a58915 100644 --- a/internal/controller/commitrequest_server.go +++ b/internal/controller/commitrequest_server.go @@ -597,6 +597,11 @@ func (s *CommitRequestServer) session( // consider serves a request no goroutine serves yet: it takes steps until the core has nothing due // before the next relist looks at the request again. +// +// A finished or unclaimed request takes its first step from u, the object the list or watch event just +// delivered, not from a get of it: a relist would otherwise get every stored request again, finished +// ones included, through the source cluster's rate-limited client, and a request created meanwhile +// would wait behind them all for its claim. See servableAsDelivered for why only those two. func (s *CommitRequestServer) consider( ctx context.Context, watcher *commitRequestWatcher, @@ -609,7 +614,7 @@ func (s *CommitRequestServer) consider( return } key := k8stypes.NamespacedName{Namespace: u.GetNamespace(), Name: u.GetName()} - core := s.core() + step := stepsOf(s.core(), watcher.path, key, u) wait := s.after if wait == nil { wait = time.After @@ -619,7 +624,7 @@ func (s *CommitRequestServer) consider( woken, stop := s.Wakes.watch(u.GetUID()) defer stop() for ctx.Err() == nil { - after, err := core.serve(ctx, watcher.path, key) + after, err := step(ctx) if err != nil { watcher.path.log.V(1).Info("A CommitRequest step failed; will retry", "commitRequest", key, "err", err.Error()) @@ -637,6 +642,39 @@ func (s *CommitRequestServer) consider( }() } +// stepsOf takes the steps of the request key, which u delivered: the first from u itself where +// servableAsDelivered allows it, and every other from the request as it is stored then. +func stepsOf( + core *commitRequestCore, path commitRequestPath, key k8stypes.NamespacedName, u *unstructured.Unstructured, +) func(context.Context) (time.Duration, error) { + delivered, err := commitRequestFromUnstructured(u) + if err != nil || !servableAsDelivered(delivered) { + delivered = nil // the first step gets it, and reports what cannot be read + } + return func(ctx context.Context) (time.Duration, error) { + if cr := delivered; cr != nil { + delivered = nil + return core.serveStored(ctx, path, cr) + } + return core.serve(ctx, path, key) + } +} + +// servableAsDelivered reports whether a step may be decided from cr as a list or watch event delivered +// it, which may be older than the stored request: an event can arrive after the goroutine that made the +// write took its later steps and ended. That is safe where every step only reads, or writes +// conditionally, before anything else: +// +// - A finished request never opens again, and each write and the delete of one is conditional. +// - An unclaimed request, with no status at all, is claimed by a conditional write before it is +// attached, and a conflict then leaves it to whoever wrote first. +// +// A claimed request is attached to its worker, or withdrawn from it, as its step's first act, so it is +// read again first: an old object would attach one whose save has already ended. +func servableAsDelivered(cr *configbutleraiv1alpha3.CommitRequest) bool { + return commitRequestIsTerminal(cr) || len(cr.Status.Conditions) == 0 +} + func (s *CommitRequestServer) core() *commitRequestCore { s.streamsOnce.Do(func() { s.streams = &commitRequestStreams{set: s.FactStreams} }) return &commitRequestCore{ diff --git a/internal/controller/commitrequest_server_test.go b/internal/controller/commitrequest_server_test.go index 3ee0340cf..f55471266 100644 --- a/internal/controller/commitrequest_server_test.go +++ b/internal/controller/commitrequest_server_test.go @@ -541,3 +541,125 @@ func TestCommitRequestServer_AWatchClosedAtOnceWaitsBeforeListingAgain(t *testin } } } + +// finishedSourceCommitRequest is a request on a source cluster whose save ended and that waits out a +// delete-after time far away, as every request a provider keeps for its TTL does. +func finishedSourceCommitRequest(name string) *unstructured.Unstructured { + u := sourceCommitRequest(name) + u.SetAnnotations(map[string]string{ + CommitRequestDeleteAfterAnnotation: time.Now().Add(48 * time.Hour).UTC().Format(time.RFC3339), + }) + u.Object["status"] = map[string]any{"conditions": []any{map[string]any{ + "type": ConditionTypeReady, "status": string(metav1.ConditionTrue), "reason": crReasonCommitted, + "message": "committed", "lastTransitionTime": time.Now().UTC().Format(time.RFC3339), + }}} + return u +} + +// A list serves each request it returns from the listed object, not from a get of it: through a +// rate-limited client, a get of every stored request would queue a request created during the relist +// behind them all, so its claim waited in proportion to how many requests the namespace keeps. Here +// each get holds the client's later calls behind it, as client-side throttling does, and the new one is +// still served within a bound no number of finished requests reaches. +func TestCommitRequestServer_ARelistDoesNotQueueANewRequestBehindTheStoredOnes(t *testing.T) { + const finished = 40 + const throttle = 100 * time.Millisecond // finished * throttle is four seconds of queue + provider := kubeconfigProvider("edge", true) + provider.Spec.CommitRequests = configv1alpha3.CommitRequestsReconcileAndDeleteFinished + c := newCommitRequestClient(t, nil, mirroringTarget("edge"), provider) + gvr := commitRequestGVR() + stored := make([]runtime.Object, 0, finished) + finishedNames := map[string]bool{} + for i := range finished { + name := "finished-" + string(rune('a'+i%26)) + string(rune('a'+i/26)) + finishedNames[name] = true + stored = append(stored, finishedSourceCommitRequest(name)) + } + source := dynamicfake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), + map[schema.GroupVersionResource]string{gvr: "CommitRequestList"}, stored...) + // The fake client takes one action at a time, so each get holds every later call of this client + // behind it, as a rate limiter does. + var finishedGets atomic.Int32 + source.PrependReactor("get", "commitrequests", func(action clienttesting.Action) (bool, runtime.Object, error) { + if finishedNames[action.(clienttesting.GetAction).GetName()] { + finishedGets.Add(1) + } + time.Sleep(throttle) + return false, nil, nil + }) + watching := make(chan struct{}) + var watchOnce sync.Once + source.PrependWatchReactor("commitrequests", func(clienttesting.Action) (bool, k8swatch.Interface, error) { + watchOnce.Do(func() { close(watching) }) + return false, nil, nil + }) + s := &CommitRequestServer{ + Client: c, Finalizer: committed(), TTL: time.Hour, Log: logr.Discard(), + Clusters: fakeClusters{dynamic: source, discovery: fakeDiscovery(nil, + commitRequestResources("configbutler.ai/v1alpha3", "commitrequests"))}, + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + s.syncProviders(ctx) + select { + case <-watching: + case <-time.After(5 * time.Second): + t.Fatal("the session never watched") + } + + // Created by someone else, on the cluster, not through the server's own throttled client. + require.NoError(t, source.Tracker().Create(gvr, sourceCommitRequest("new"), "default")) + require.Eventually(t, func() bool { + u, getErr := source.Tracker().Get(gvr, "default", "new") + if getErr != nil { + return false + } + cr, convErr := commitRequestFromUnstructured(u.(*unstructured.Unstructured)) + if convErr != nil { + return false + } + return apimeta.FindStatusCondition(cr.Status.Conditions, ConditionTypeReady) != nil // the claim + }, 2*time.Second, 20*time.Millisecond, "the new request is claimed without waiting behind the stored ones") + assert.Zero(t, finishedGets.Load(), "no finished request is read again after the list returned it") +} + +// An event can deliver a request older than the stored one: the write of its claim, arriving after the +// steps that pushed it. A claimed request is read again before it is attached, so an old object never +// attaches a request whose save has ended. +func TestCommitRequestServer_AnOldEventOfAClaimedRequestIsReadAgain(t *testing.T) { + cr := newCommitRequest("save") + cr.Spec.GitTargetRef.Namespace = "default" + f := committed() + c := newCommitRequestClient(t, nil, cr, mirroringTarget("edge"), kubeconfigProvider("edge", true)) + server := &CommitRequestServer{Client: c, Finalizer: f} + watcher := &commitRequestWatcher{ + provider: types.NamespacedName{Namespace: "default", Name: "edge"}, path: watcherPath(c, "edge", false), + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + deliver := func(cr *configv1alpha3.CommitRequest) { + u, err := commitRequestToUnstructured(cr) + require.NoError(t, err) + server.consider(ctx, watcher, u) + require.Eventually(t, func() bool { + _, serving := watcher.serving.Load(cr.UID) + return !serving + }, 10*time.Second, time.Millisecond, "the delivered request's steps end") + } + + stored := fetchCommitRequest(t, c, "save") + claimEvent := stored.DeepCopy() // how the claim reads, as its event will deliver it + var target configv1alpha3.GitTarget + require.NoError(t, c.Get(ctx, types.NamespacedName{Namespace: "default", Name: "team-a-config"}, &target)) + claimEvent.Status.GitTargetUID = string(target.UID) + markCommitRequestProgressing(claimEvent, "", "") + + deliver(&stored) + ready := commitRequestReady(t, c, "save") + require.NotNil(t, ready) + require.Equal(t, crReasonCommitted, ready.Reason, "the request is pushed") + require.Len(t, f.calls, 1) + + deliver(claimEvent) + assert.Len(t, f.calls, 1, "the old event attached nothing: the stored request had finished") +} diff --git a/internal/controller/commitrequest_wakes_test.go b/internal/controller/commitrequest_wakes_test.go index c9ea6f5d4..f921136e7 100644 --- a/internal/controller/commitrequest_wakes_test.go +++ b/internal/controller/commitrequest_wakes_test.go @@ -12,7 +12,6 @@ import ( "github.com/stretchr/testify/require" apimeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" @@ -143,10 +142,10 @@ func serveSave(t *testing.T, woken bool) *servedSave { watcher := &commitRequestWatcher{ provider: types.NamespacedName{Namespace: "default", Name: "edge"}, path: watcherPath(c, "edge", false), } - u := &unstructured.Unstructured{} - u.SetNamespace("default") - u.SetName("save") - u.SetUID(cr.UID) + var stored configv1alpha3.CommitRequest + require.NoError(t, c.Get(ctx, client.ObjectKeyFromObject(cr), &stored)) + u, err := commitRequestToUnstructured(&stored) // the object the list or watch event delivers + require.NoError(t, err) server.consider(ctx, watcher, u) s := &servedSave{t: t, c: c, cr: cr, worker: worker, timers: timers} From 7bf341180f3e6694bbb3d3655a63847358e82c83 Mon Sep 17 00:00:00 2001 From: Simon Koudijs Date: Fri, 27 Nov 2026 21:52:32 +0000 Subject: [PATCH 2/5] fix(commitrequest): forget an in-flight request only by its own object The shutdown tracker keyed a request by name alone. A finished object that a list or watch event delivers can belong to a request another of its name has since replaced, and dropping it by name forgot the replacement this process may have attached, so a shutdown would not settle it. The tracker now remembers the UID, and a step that judges a delivered or written object finished or deleting drops the entry only when it is that object's. A read by name that finds nothing still drops by name. Co-Authored-By: Claude Opus 5.5 --- internal/controller/commitrequest_core.go | 10 +++--- internal/controller/commitrequest_decide.go | 4 +-- internal/controller/commitrequest_settle.go | 31 ++++++++++++++++--- .../controller/commitrequest_settle_test.go | 20 +++++++++++- 4 files changed, 53 insertions(+), 12 deletions(-) diff --git a/internal/controller/commitrequest_core.go b/internal/controller/commitrequest_core.go index 975dba8ad..be9b8df96 100644 --- a/internal/controller/commitrequest_core.go +++ b/internal/controller/commitrequest_core.go @@ -136,17 +136,17 @@ func (c *commitRequestCore) serve( func (c *commitRequestCore) serveStored( ctx context.Context, p commitRequestPath, cr *configbutleraiv1alpha3.CommitRequest, ) (time.Duration, error) { - key := client.ObjectKeyFromObject(cr) if !cr.DeletionTimestamp.IsZero() { - c.inFlight.forget(p, key) + c.inFlight.forgetObject(p, cr) return 0, nil } if commitRequestIsTerminal(cr) { - c.inFlight.forget(p, key) + c.inFlight.forgetObject(p, cr) return c.serveFinished(ctx, p, cr) } if c.finalizer == nil { - p.log.V(1).Info("CommitRequest finalize disabled: no Finalizer configured", "name", key) + p.log.V(1).Info("CommitRequest finalize disabled: no Finalizer configured", + "name", client.ObjectKeyFromObject(cr)) return 0, nil } return c.serveOpen(ctx, p, cr) @@ -526,7 +526,7 @@ func (c *commitRequestCore) drive( target *configbutleraiv1alpha3.GitTarget, provider *configbutleraiv1alpha3.KubeProvider, ) (time.Duration, error) { // Remembered before anything reaches a worker, so whatever it decides is written at shutdown. - c.inFlight.track(c, p, client.ObjectKeyFromObject(cr)) + c.inFlight.track(c, p, cr) attach := c.attachFor(cr) if target != nil && string(target.UID) != cr.Status.GitTargetUID { admitted, refusal, err := c.admit(ctx, p, cr, target, provider) diff --git a/internal/controller/commitrequest_decide.go b/internal/controller/commitrequest_decide.go index 6bf0dacf0..f5636c7eb 100644 --- a/internal/controller/commitrequest_decide.go +++ b/internal/controller/commitrequest_decide.go @@ -93,11 +93,11 @@ func (c *commitRequestCore) decide( if err != nil || !written { if err == nil && current != nil && commitRequestIsTerminal(current) { // Another write got there first, and the request is finished all the same. - c.inFlight.forget(p, client.ObjectKeyFromObject(current)) + c.inFlight.forgetObject(p, current) } return commitRequestRequeueNow, err } - c.inFlight.forget(p, client.ObjectKeyFromObject(current)) + c.inFlight.forgetObject(p, current) if !afterClaim { recordCommitRequestOutcome(ctx, o.metricOutcome(), target) } diff --git a/internal/controller/commitrequest_settle.go b/internal/controller/commitrequest_settle.go index c0b045753..2cf84f54b 100644 --- a/internal/controller/commitrequest_settle.go +++ b/internal/controller/commitrequest_settle.go @@ -9,6 +9,8 @@ import ( "github.com/go-logr/logr" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" + + configbutleraiv1alpha3 "github.com/ConfigButler/gitops-reverser/api/v1alpha3" ) // A save's outcome is decided by its branch worker and lives in the worker's memory until a step of @@ -42,14 +44,19 @@ type inFlightKey struct { request types.NamespacedName } -// inFlightRequest is how to take a step of a remembered request. +// inFlightRequest is how to take a step of a remembered request, and which request of its name it is. type inFlightRequest struct { core *commitRequestCore path commitRequestPath + uid types.UID } // track remembers a request p attaches. -func (f *CommitRequestsInFlight) track(c *commitRequestCore, p commitRequestPath, key types.NamespacedName) { +func (f *CommitRequestsInFlight) track( + c *commitRequestCore, + p commitRequestPath, + cr *configbutleraiv1alpha3.CommitRequest, +) { if f == nil { return } @@ -58,10 +65,11 @@ func (f *CommitRequestsInFlight) track(c *commitRequestCore, p commitRequestPath if f.requests == nil { f.requests = map[inFlightKey]inFlightRequest{} } - f.requests[inFlightKey{provider: p.provider, request: key}] = inFlightRequest{core: c, path: p} + f.requests[inFlightKey{provider: p.provider, request: client.ObjectKeyFromObject(cr)}] = + inFlightRequest{core: c, path: p, uid: cr.UID} } -// forget drops a request that finished, or is gone. +// forget drops the request of key's name, read as gone or finished from where that name is stored now. func (f *CommitRequestsInFlight) forget(p commitRequestPath, key types.NamespacedName) { if f == nil { return @@ -71,6 +79,21 @@ func (f *CommitRequestsInFlight) forget(p commitRequestPath, key types.Namespace delete(f.requests, inFlightKey{provider: p.provider, request: key}) } +// forgetObject drops cr, finished or being deleted, but only while what is remembered under its name is +// cr itself: cr may be an object a list or watch event delivered after the request was replaced by +// another of its name, which this process may have attached since. +func (f *CommitRequestsInFlight) forgetObject(p commitRequestPath, cr *configbutleraiv1alpha3.CommitRequest) { + if f == nil { + return + } + f.mu.Lock() + defer f.mu.Unlock() + key := inFlightKey{provider: p.provider, request: client.ObjectKeyFromObject(cr)} + if remembered, ok := f.requests[key]; ok && remembered.uid == cr.UID { + delete(f.requests, key) + } +} + // remembered copies the requests out, for Settle to step through without the lock. func (f *CommitRequestsInFlight) remembered() map[inFlightKey]inFlightRequest { f.mu.Lock() diff --git a/internal/controller/commitrequest_settle_test.go b/internal/controller/commitrequest_settle_test.go index eee32aee7..0e5c25aa3 100644 --- a/internal/controller/commitrequest_settle_test.go +++ b/internal/controller/commitrequest_settle_test.go @@ -281,12 +281,30 @@ func TestCommitRequestsInFlight_ASourceClusterRequestIsSettledOnItsCluster(t *te func TestCommitRequestsInFlight_Nil(t *testing.T) { var inFlight *CommitRequestsInFlight assert.NotPanics(t, func() { - inFlight.track(&commitRequestCore{}, commitRequestPath{}, types.NamespacedName{Name: "save"}) + inFlight.track(&commitRequestCore{}, commitRequestPath{}, newCommitRequest("save")) inFlight.forget(commitRequestPath{}, types.NamespacedName{Name: "save"}) + inFlight.forgetObject(commitRequestPath{}, newCommitRequest("save")) inFlight.Settle(context.Background()) }) } +// A finished object of a request that another of its name replaced, as a list or watch event may still +// deliver it, leaves the new request remembered: only that request's own object drops it. +func TestCommitRequestsInFlight_AnOldObjectOfAReplacedRequestLeavesTheNewOne(t *testing.T) { + inFlight := &CommitRequestsInFlight{} + p := commitRequestPath{provider: types.NamespacedName{Namespace: "default", Name: "edge"}} + replaced := newCommitRequest("save") + replacement := newCommitRequest("save") + replacement.UID = "uid-save-again" + inFlight.track(&commitRequestCore{}, p, replacement) + + inFlight.forgetObject(p, replaced) + assert.Len(t, inFlight.remembered(), 1, "the replaced request's object leaves the new one remembered") + + inFlight.forgetObject(p, replacement) + assert.Empty(t, inFlight.remembered(), "its own object drops it") +} + // A shutdown out of time writes nothing more: what is left is attached again by the next process. func TestCommitRequestsInFlight_OutOfTimeLeavesTheRest(t *testing.T) { c := newCommitRequestClient(t, nil, withInProgress(newCommitRequest("save"))) From ac210625654befc16f743213996b4c741afab12d Mon Sep 17 00:00:00 2001 From: Simon Koudijs Date: Fri, 27 Nov 2026 22:17:44 +0000 Subject: [PATCH 3/5] refactor(commitrequest): serve only finished requests from the delivered object Narrow the relist fix to what the bug needs. The core's serveDelivered serves a finished request from the object a list or watch event delivered, and reads every other request fresh, as serve always has. That drops servableAsDelivered, the unclaimed-request shortcut, serveStored and the stepsOf closure. consider now takes an explicit first step, then loops on serve as before. The in-flight tracker keeps its UID check, now used only where a delivered finished object is forgotten; decide is back to forgetting by name. The relist test throttles gets with client-go's token-bucket limiter outside the fake's lock. The watch therefore opens at once, and the claim latency fails on its own when the refetch is restored. Co-Authored-By: Claude Opus 5.5 --- internal/controller/commitrequest_core.go | 31 ++++--- internal/controller/commitrequest_decide.go | 4 +- internal/controller/commitrequest_server.go | 59 +++++-------- .../controller/commitrequest_server_test.go | 86 +++++++++++++------ internal/controller/commitrequest_settle.go | 9 +- .../controller/commitrequest_wakes_test.go | 9 +- 6 files changed, 108 insertions(+), 90 deletions(-) diff --git a/internal/controller/commitrequest_core.go b/internal/controller/commitrequest_core.go index be9b8df96..b8bbcd8bc 100644 --- a/internal/controller/commitrequest_core.go +++ b/internal/controller/commitrequest_core.go @@ -126,32 +126,35 @@ func (c *commitRequestCore) serve( } return 0, client.IgnoreNotFound(err) } - return c.serveStored(ctx, p, cr) -} - -// serveStored takes one step for cr, as it was read from p's store: by a get, or by the list or watch -// event that delivered it, where the caller knows the step is safe on an object that may have changed -// since (servableAsDelivered). Every write is conditional on cr.ResourceVersion, so such a step fails -// with a conflict and the next one reads the request again. -func (c *commitRequestCore) serveStored( - ctx context.Context, p commitRequestPath, cr *configbutleraiv1alpha3.CommitRequest, -) (time.Duration, error) { if !cr.DeletionTimestamp.IsZero() { - c.inFlight.forgetObject(p, cr) + c.inFlight.forget(p, key) return 0, nil } if commitRequestIsTerminal(cr) { - c.inFlight.forgetObject(p, cr) + c.inFlight.forget(p, key) return c.serveFinished(ctx, p, cr) } if c.finalizer == nil { - p.log.V(1).Info("CommitRequest finalize disabled: no Finalizer configured", - "name", client.ObjectKeyFromObject(cr)) + p.log.V(1).Info("CommitRequest finalize disabled: no Finalizer configured", "name", key) return 0, nil } return c.serveOpen(ctx, p, cr) } +// serveDelivered is serve for a request a list or watch event delivered, which may be older than the +// stored one. A finished request is served from it: it never reopens, and each write or delete of one +// is conditional on its resourceVersion, so a relist reads no finished request again. Any other is +// read fresh first, because its step may attach it to a worker before any conditional write. +func (c *commitRequestCore) serveDelivered( + ctx context.Context, p commitRequestPath, delivered *configbutleraiv1alpha3.CommitRequest, +) (time.Duration, error) { + if !commitRequestIsTerminal(delivered) || !delivered.DeletionTimestamp.IsZero() { + return c.serve(ctx, p, client.ObjectKeyFromObject(delivered)) + } + c.inFlight.forgetObject(p, delivered) + return c.serveFinished(ctx, p, delivered) +} + // serveOpen is the step of a request whose save has not ended: it waits for its GitTarget, leaves it // to the path that owns it, or claims and drives it as its owner. func (c *commitRequestCore) serveOpen( diff --git a/internal/controller/commitrequest_decide.go b/internal/controller/commitrequest_decide.go index f5636c7eb..6bf0dacf0 100644 --- a/internal/controller/commitrequest_decide.go +++ b/internal/controller/commitrequest_decide.go @@ -93,11 +93,11 @@ func (c *commitRequestCore) decide( if err != nil || !written { if err == nil && current != nil && commitRequestIsTerminal(current) { // Another write got there first, and the request is finished all the same. - c.inFlight.forgetObject(p, current) + c.inFlight.forget(p, client.ObjectKeyFromObject(current)) } return commitRequestRequeueNow, err } - c.inFlight.forgetObject(p, current) + c.inFlight.forget(p, client.ObjectKeyFromObject(current)) if !afterClaim { recordCommitRequestOutcome(ctx, o.metricOutcome(), target) } diff --git a/internal/controller/commitrequest_server.go b/internal/controller/commitrequest_server.go index 654a58915..d4be9374f 100644 --- a/internal/controller/commitrequest_server.go +++ b/internal/controller/commitrequest_server.go @@ -596,12 +596,8 @@ func (s *CommitRequestServer) session( } // consider serves a request no goroutine serves yet: it takes steps until the core has nothing due -// before the next relist looks at the request again. -// -// A finished or unclaimed request takes its first step from u, the object the list or watch event just -// delivered, not from a get of it: a relist would otherwise get every stored request again, finished -// ones included, through the source cluster's rate-limited client, and a request created meanwhile -// would wait behind them all for its claim. See servableAsDelivered for why only those two. +// before the next relist looks at the request again. The first step starts from u, the object the +// list or watch event delivered (serveDelivered); every later step reads the request fresh. func (s *CommitRequestServer) consider( ctx context.Context, watcher *commitRequestWatcher, @@ -614,7 +610,7 @@ func (s *CommitRequestServer) consider( return } key := k8stypes.NamespacedName{Namespace: u.GetNamespace(), Name: u.GetName()} - step := stepsOf(s.core(), watcher.path, key, u) + core := s.core() wait := s.after if wait == nil { wait = time.After @@ -623,56 +619,41 @@ func (s *CommitRequestServer) consider( defer watcher.serving.Delete(u.GetUID()) woken, stop := s.Wakes.watch(u.GetUID()) defer stop() - for ctx.Err() == nil { - after, err := step(ctx) + // nextStepDue waits for the step a result asks for, and reports false when none is due. + nextStepDue := func(after time.Duration, err error) bool { if err != nil { watcher.path.log.V(1).Info("A CommitRequest step failed; will retry", "commitRequest", key, "err", err.Error()) after = commitRequestPollInterval } if after == 0 || after >= commitRequestRelist { - return + return false } select { case <-ctx.Done(): case <-wait(after): case <-woken: } + return ctx.Err() == nil + } + + after, err := serveDeliveredObject(ctx, core, watcher.path, u) + for nextStepDue(after, err) { + after, err = core.serve(ctx, watcher.path, key) } }() } -// stepsOf takes the steps of the request key, which u delivered: the first from u itself where -// servableAsDelivered allows it, and every other from the request as it is stored then. -func stepsOf( - core *commitRequestCore, path commitRequestPath, key k8stypes.NamespacedName, u *unstructured.Unstructured, -) func(context.Context) (time.Duration, error) { +// serveDeliveredObject takes the first step for u. An object that cannot be read as a CommitRequest +// fails the step, and the next one reads the request fresh. +func serveDeliveredObject( + ctx context.Context, core *commitRequestCore, p commitRequestPath, u *unstructured.Unstructured, +) (time.Duration, error) { delivered, err := commitRequestFromUnstructured(u) - if err != nil || !servableAsDelivered(delivered) { - delivered = nil // the first step gets it, and reports what cannot be read - } - return func(ctx context.Context) (time.Duration, error) { - if cr := delivered; cr != nil { - delivered = nil - return core.serveStored(ctx, path, cr) - } - return core.serve(ctx, path, key) + if err != nil { + return 0, err } -} - -// servableAsDelivered reports whether a step may be decided from cr as a list or watch event delivered -// it, which may be older than the stored request: an event can arrive after the goroutine that made the -// write took its later steps and ended. That is safe where every step only reads, or writes -// conditionally, before anything else: -// -// - A finished request never opens again, and each write and the delete of one is conditional. -// - An unclaimed request, with no status at all, is claimed by a conditional write before it is -// attached, and a conflict then leaves it to whoever wrote first. -// -// A claimed request is attached to its worker, or withdrawn from it, as its step's first act, so it is -// read again first: an old object would attach one whose save has already ended. -func servableAsDelivered(cr *configbutleraiv1alpha3.CommitRequest) bool { - return commitRequestIsTerminal(cr) || len(cr.Status.Conditions) == 0 + return core.serveDelivered(ctx, p, delivered) } func (s *CommitRequestServer) core() *commitRequestCore { diff --git a/internal/controller/commitrequest_server_test.go b/internal/controller/commitrequest_server_test.go index f55471266..dea86cc67 100644 --- a/internal/controller/commitrequest_server_test.go +++ b/internal/controller/commitrequest_server_test.go @@ -5,6 +5,7 @@ package controller import ( "context" "errors" + "fmt" "slices" "sync" "sync/atomic" @@ -28,6 +29,7 @@ import ( "k8s.io/client-go/dynamic" dynamicfake "k8s.io/client-go/dynamic/fake" clienttesting "k8s.io/client-go/testing" + "k8s.io/client-go/util/flowcontrol" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/event" @@ -542,8 +544,8 @@ func TestCommitRequestServer_AWatchClosedAtOnceWaitsBeforeListingAgain(t *testin } } -// finishedSourceCommitRequest is a request on a source cluster whose save ended and that waits out a -// delete-after time far away, as every request a provider keeps for its TTL does. +// finishedSourceCommitRequest is a request on a source cluster whose save ended, kept until a +// delete-after time far away. func finishedSourceCommitRequest(name string) *unstructured.Unstructured { u := sourceCommitRequest(name) u.SetAnnotations(map[string]string{ @@ -556,14 +558,47 @@ func finishedSourceCommitRequest(name string) *unstructured.Unstructured { return u } -// A list serves each request it returns from the listed object, not from a get of it: through a -// rate-limited client, a get of every stored request would queue a request created during the relist -// behind them all, so its claim waited in proportion to how many requests the namespace keeps. Here -// each get holds the client's later calls behind it, as client-side throttling does, and the new one is -// still served within a bound no number of finished requests reaches. -func TestCommitRequestServer_ARelistDoesNotQueueANewRequestBehindTheStoredOnes(t *testing.T) { +// throttledGets is a source cluster's client whose gets wait for a token-bucket rate limiter, as every +// call of a real client does, outside the fake's own lock, so a list and watch never wait behind them. +type throttledGets struct { + dynamic.Interface + + limiter flowcontrol.RateLimiter +} + +func (c throttledGets) Resource(gvr schema.GroupVersionResource) dynamic.NamespaceableResourceInterface { + return throttledResource{NamespaceableResourceInterface: c.Interface.Resource(gvr), limiter: c.limiter} +} + +type throttledResource struct { + dynamic.NamespaceableResourceInterface + + limiter flowcontrol.RateLimiter +} + +func (r throttledResource) Namespace(namespace string) dynamic.ResourceInterface { + return throttledNamespace{ResourceInterface: r.NamespaceableResourceInterface.Namespace(namespace), + limiter: r.limiter} +} + +type throttledNamespace struct { + dynamic.ResourceInterface + + limiter flowcontrol.RateLimiter +} + +func (r throttledNamespace) Get( + ctx context.Context, name string, options metav1.GetOptions, subresources ...string, +) (*unstructured.Unstructured, error) { + r.limiter.Accept() + return r.ResourceInterface.Get(ctx, name, options, subresources...) +} + +// A relist serves each finished request from the listed object. Before, it got every one again through +// the source cluster's rate-limited client, and a request created meanwhile waited behind them all for +// its claim: here 40 finished requests at 10 gets a second would hold it about four seconds. +func TestCommitRequestServer_ARelistDoesNotQueueANewRequestBehindTheFinishedOnes(t *testing.T) { const finished = 40 - const throttle = 100 * time.Millisecond // finished * throttle is four seconds of queue provider := kubeconfigProvider("edge", true) provider.Spec.CommitRequests = configv1alpha3.CommitRequestsReconcileAndDeleteFinished c := newCommitRequestClient(t, nil, mirroringTarget("edge"), provider) @@ -571,20 +606,17 @@ func TestCommitRequestServer_ARelistDoesNotQueueANewRequestBehindTheStoredOnes(t stored := make([]runtime.Object, 0, finished) finishedNames := map[string]bool{} for i := range finished { - name := "finished-" + string(rune('a'+i%26)) + string(rune('a'+i/26)) + name := fmt.Sprintf("finished-%02d", i) finishedNames[name] = true stored = append(stored, finishedSourceCommitRequest(name)) } source := dynamicfake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[schema.GroupVersionResource]string{gvr: "CommitRequestList"}, stored...) - // The fake client takes one action at a time, so each get holds every later call of this client - // behind it, as a rate limiter does. var finishedGets atomic.Int32 source.PrependReactor("get", "commitrequests", func(action clienttesting.Action) (bool, runtime.Object, error) { if finishedNames[action.(clienttesting.GetAction).GetName()] { finishedGets.Add(1) } - time.Sleep(throttle) return false, nil, nil }) watching := make(chan struct{}) @@ -595,31 +627,33 @@ func TestCommitRequestServer_ARelistDoesNotQueueANewRequestBehindTheStoredOnes(t }) s := &CommitRequestServer{ Client: c, Finalizer: committed(), TTL: time.Hour, Log: logr.Discard(), - Clusters: fakeClusters{dynamic: source, discovery: fakeDiscovery(nil, - commitRequestResources("configbutler.ai/v1alpha3", "commitrequests"))}, + Clusters: fakeClusters{ + dynamic: throttledGets{Interface: source, limiter: flowcontrol.NewTokenBucketRateLimiter(10, 1)}, + discovery: fakeDiscovery(nil, commitRequestResources("configbutler.ai/v1alpha3", "commitrequests")), + }, } ctx, cancel := context.WithCancel(context.Background()) defer cancel() s.syncProviders(ctx) select { - case <-watching: + case <-watching: // the list has been served, and any gets of it are queued case <-time.After(5 * time.Second): t.Fatal("the session never watched") } - // Created by someone else, on the cluster, not through the server's own throttled client. + created := time.Now() require.NoError(t, source.Tracker().Create(gvr, sourceCommitRequest("new"), "default")) - require.Eventually(t, func() bool { - u, getErr := source.Tracker().Get(gvr, "default", "new") - if getErr != nil { - return false - } - cr, convErr := commitRequestFromUnstructured(u.(*unstructured.Unstructured)) - if convErr != nil { + claimed := func() bool { + u, err := source.Tracker().Get(gvr, "default", "new") + if err != nil { return false } - return apimeta.FindStatusCondition(cr.Status.Conditions, ConditionTypeReady) != nil // the claim - }, 2*time.Second, 20*time.Millisecond, "the new request is claimed without waiting behind the stored ones") + cr, err := commitRequestFromUnstructured(u.(*unstructured.Unstructured)) + return err == nil && apimeta.FindStatusCondition(cr.Status.Conditions, ConditionTypeReady) != nil + } + assert.Eventually(t, claimed, 2*time.Second, 20*time.Millisecond, + "the new request is claimed without waiting behind the finished ones") + t.Logf("claimed %s after it was created", time.Since(created).Round(10*time.Millisecond)) assert.Zero(t, finishedGets.Load(), "no finished request is read again after the list returned it") } diff --git a/internal/controller/commitrequest_settle.go b/internal/controller/commitrequest_settle.go index 2cf84f54b..0187aecc1 100644 --- a/internal/controller/commitrequest_settle.go +++ b/internal/controller/commitrequest_settle.go @@ -44,7 +44,7 @@ type inFlightKey struct { request types.NamespacedName } -// inFlightRequest is how to take a step of a remembered request, and which request of its name it is. +// inFlightRequest is how to take a step of a remembered request, and its UID. type inFlightRequest struct { core *commitRequestCore path commitRequestPath @@ -69,7 +69,7 @@ func (f *CommitRequestsInFlight) track( inFlightRequest{core: c, path: p, uid: cr.UID} } -// forget drops the request of key's name, read as gone or finished from where that name is stored now. +// forget drops a request that finished, or is gone, as read fresh by its name. func (f *CommitRequestsInFlight) forget(p commitRequestPath, key types.NamespacedName) { if f == nil { return @@ -79,9 +79,8 @@ func (f *CommitRequestsInFlight) forget(p commitRequestPath, key types.Namespace delete(f.requests, inFlightKey{provider: p.provider, request: key}) } -// forgetObject drops cr, finished or being deleted, but only while what is remembered under its name is -// cr itself: cr may be an object a list or watch event delivered after the request was replaced by -// another of its name, which this process may have attached since. +// forgetObject drops cr, which finished, only if the request remembered under its name has cr's UID: an +// old delivered object must not drop a newer request that reuses the name. func (f *CommitRequestsInFlight) forgetObject(p commitRequestPath, cr *configbutleraiv1alpha3.CommitRequest) { if f == nil { return diff --git a/internal/controller/commitrequest_wakes_test.go b/internal/controller/commitrequest_wakes_test.go index f921136e7..c9ea6f5d4 100644 --- a/internal/controller/commitrequest_wakes_test.go +++ b/internal/controller/commitrequest_wakes_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/require" apimeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" @@ -142,10 +143,10 @@ func serveSave(t *testing.T, woken bool) *servedSave { watcher := &commitRequestWatcher{ provider: types.NamespacedName{Namespace: "default", Name: "edge"}, path: watcherPath(c, "edge", false), } - var stored configv1alpha3.CommitRequest - require.NoError(t, c.Get(ctx, client.ObjectKeyFromObject(cr), &stored)) - u, err := commitRequestToUnstructured(&stored) // the object the list or watch event delivers - require.NoError(t, err) + u := &unstructured.Unstructured{} + u.SetNamespace("default") + u.SetName("save") + u.SetUID(cr.UID) server.consider(ctx, watcher, u) s := &servedSave{t: t, c: c, cr: cr, worker: worker, timers: timers} From 6fbad21f42f6cf8f424c2c908b21dc829872a734 Mon Sep 17 00:00:00 2001 From: Simon Koudijs Date: Fri, 27 Nov 2026 22:25:43 +0000 Subject: [PATCH 4/5] test(commitrequest): make the relist regression test fail every time the refetch is back Opening the watch did not mean the listed requests' goroutines had reached the rate limiter, so the new request could take the first token and be claimed before any finished get was counted: with the refetch restored, one run in ten passed. The limiter now hands out turns in the order gets are made, and records each get when it takes its turn. The test waits until every listed request has either taken a turn or finished its step, a point that holds with and without the fix, before it creates the new request. With the refetch restored, both assertions fail in 30 of 30 runs; with the fix, the test passes 100 of 100. Co-Authored-By: Claude Opus 5.5 --- .../controller/commitrequest_server_test.go | 85 ++++++++++++++----- 1 file changed, 62 insertions(+), 23 deletions(-) diff --git a/internal/controller/commitrequest_server_test.go b/internal/controller/commitrequest_server_test.go index dea86cc67..d9a6593e0 100644 --- a/internal/controller/commitrequest_server_test.go +++ b/internal/controller/commitrequest_server_test.go @@ -29,7 +29,6 @@ import ( "k8s.io/client-go/dynamic" dynamicfake "k8s.io/client-go/dynamic/fake" clienttesting "k8s.io/client-go/testing" - "k8s.io/client-go/util/flowcontrol" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/event" @@ -558,39 +557,68 @@ func finishedSourceCommitRequest(name string) *unstructured.Unstructured { return u } -// throttledGets is a source cluster's client whose gets wait for a token-bucket rate limiter, as every -// call of a real client does, outside the fake's own lock, so a list and watch never wait behind them. +// orderedGets rate-limits a source cluster's gets, outside the fake's own lock, so a list and watch +// never wait behind them. Each get takes the next turn, interval after the one before, in the order +// the gets were made, and is recorded by name once it holds its turn. +type orderedGets struct { + interval time.Duration + + mu sync.Mutex + next time.Time + took map[string]int +} + +// turn records a get of name and waits for its turn. +func (o *orderedGets) turn(name string) { + o.mu.Lock() + at := time.Now() + if o.next.After(at) { + at = o.next + } + o.next = at.Add(o.interval) + o.took[name]++ + o.mu.Unlock() + time.Sleep(time.Until(at)) +} + +func (o *orderedGets) gets(name string) int { + o.mu.Lock() + defer o.mu.Unlock() + return o.took[name] +} + +// throttledGets is a source cluster's client whose gets take turns from limit. type throttledGets struct { dynamic.Interface - limiter flowcontrol.RateLimiter + limit *orderedGets } func (c throttledGets) Resource(gvr schema.GroupVersionResource) dynamic.NamespaceableResourceInterface { - return throttledResource{NamespaceableResourceInterface: c.Interface.Resource(gvr), limiter: c.limiter} + return throttledResource{NamespaceableResourceInterface: c.Interface.Resource(gvr), limit: c.limit} } type throttledResource struct { dynamic.NamespaceableResourceInterface - limiter flowcontrol.RateLimiter + limit *orderedGets } func (r throttledResource) Namespace(namespace string) dynamic.ResourceInterface { return throttledNamespace{ResourceInterface: r.NamespaceableResourceInterface.Namespace(namespace), - limiter: r.limiter} + limit: r.limit} } type throttledNamespace struct { dynamic.ResourceInterface - limiter flowcontrol.RateLimiter + limit *orderedGets } func (r throttledNamespace) Get( ctx context.Context, name string, options metav1.GetOptions, subresources ...string, ) (*unstructured.Unstructured, error) { - r.limiter.Accept() + r.limit.turn(name) return r.ResourceInterface.Get(ctx, name, options, subresources...) } @@ -604,42 +632,50 @@ func TestCommitRequestServer_ARelistDoesNotQueueANewRequestBehindTheFinishedOnes c := newCommitRequestClient(t, nil, mirroringTarget("edge"), provider) gvr := commitRequestGVR() stored := make([]runtime.Object, 0, finished) - finishedNames := map[string]bool{} for i := range finished { - name := fmt.Sprintf("finished-%02d", i) - finishedNames[name] = true - stored = append(stored, finishedSourceCommitRequest(name)) + stored = append(stored, finishedSourceCommitRequest(fmt.Sprintf("finished-%02d", i))) } source := dynamicfake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[schema.GroupVersionResource]string{gvr: "CommitRequestList"}, stored...) - var finishedGets atomic.Int32 - source.PrependReactor("get", "commitrequests", func(action clienttesting.Action) (bool, runtime.Object, error) { - if finishedNames[action.(clienttesting.GetAction).GetName()] { - finishedGets.Add(1) - } - return false, nil, nil - }) watching := make(chan struct{}) var watchOnce sync.Once source.PrependWatchReactor("commitrequests", func(clienttesting.Action) (bool, k8swatch.Interface, error) { watchOnce.Do(func() { close(watching) }) return false, nil, nil }) + limit := &orderedGets{interval: 100 * time.Millisecond, took: map[string]int{}} s := &CommitRequestServer{ Client: c, Finalizer: committed(), TTL: time.Hour, Log: logr.Discard(), Clusters: fakeClusters{ - dynamic: throttledGets{Interface: source, limiter: flowcontrol.NewTokenBucketRateLimiter(10, 1)}, + dynamic: throttledGets{Interface: source, limit: limit}, discovery: fakeDiscovery(nil, commitRequestResources("configbutler.ai/v1alpha3", "commitrequests")), }, } ctx, cancel := context.WithCancel(context.Background()) defer cancel() s.syncProviders(ctx) + + // The session serves every listed request before it opens the watch. Wait until each has either + // taken a turn for a get or finished its step, so the new request's turn comes after any of theirs. select { - case <-watching: // the list has been served, and any gets of it are queued + case <-watching: case <-time.After(5 * time.Second): t.Fatal("the session never watched") } + s.mu.Lock() + watcher := s.watchers[provider.Key()] + s.mu.Unlock() + require.NotNil(t, watcher) + require.Eventually(t, func() bool { + for _, u := range stored { + name := u.(*unstructured.Unstructured).GetName() + if _, serving := watcher.serving.Load(u.(*unstructured.Unstructured).GetUID()); serving && + limit.gets(name) == 0 { + return false + } + } + return true + }, 5*time.Second, time.Millisecond, "every listed request has taken a turn or finished its step") created := time.Now() require.NoError(t, source.Tracker().Create(gvr, sourceCommitRequest("new"), "default")) @@ -654,7 +690,10 @@ func TestCommitRequestServer_ARelistDoesNotQueueANewRequestBehindTheFinishedOnes assert.Eventually(t, claimed, 2*time.Second, 20*time.Millisecond, "the new request is claimed without waiting behind the finished ones") t.Logf("claimed %s after it was created", time.Since(created).Round(10*time.Millisecond)) - assert.Zero(t, finishedGets.Load(), "no finished request is read again after the list returned it") + for _, u := range stored { + name := u.(*unstructured.Unstructured).GetName() + assert.Zero(t, limit.gets(name), "finished request %s is not read again after the list returned it", name) + } } // An event can deliver a request older than the stored one: the write of its claim, arriving after the From 1779ee75eb06cfb21fc1a43316f89b690cb7fe66 Mon Sep 17 00:00:00 2001 From: Simon Koudijs Date: Sat, 28 Nov 2026 18:31:26 +0000 Subject: [PATCH 5/5] refactor(commitrequest): drop the UID-scoped forget from serving a delivered request serveDelivered no longer forgets a finished request from the in-flight requests. The step that wrote the outcome forgot it already, and Settle reads any request still remembered fresh and forgets a finished one without writing. With no forget from a possibly old object, the tracker needs no UID, and forgetObject and its test go. Co-Authored-By: Claude Opus 5.5 --- internal/controller/commitrequest_core.go | 7 +++-- internal/controller/commitrequest_settle.go | 30 +++---------------- .../controller/commitrequest_settle_test.go | 20 +------------ 3 files changed, 10 insertions(+), 47 deletions(-) diff --git a/internal/controller/commitrequest_core.go b/internal/controller/commitrequest_core.go index b8bbcd8bc..2cce7179b 100644 --- a/internal/controller/commitrequest_core.go +++ b/internal/controller/commitrequest_core.go @@ -145,13 +145,16 @@ func (c *commitRequestCore) serve( // stored one. A finished request is served from it: it never reopens, and each write or delete of one // is conditional on its resourceVersion, so a relist reads no finished request again. Any other is // read fresh first, because its step may attach it to a worker before any conditional write. +// +// A finished request is not forgotten from the in-flight requests here: an old object may carry the +// name of a newer request. The step that wrote its outcome forgot it already, and Settle reads any +// request still remembered fresh. func (c *commitRequestCore) serveDelivered( ctx context.Context, p commitRequestPath, delivered *configbutleraiv1alpha3.CommitRequest, ) (time.Duration, error) { if !commitRequestIsTerminal(delivered) || !delivered.DeletionTimestamp.IsZero() { return c.serve(ctx, p, client.ObjectKeyFromObject(delivered)) } - c.inFlight.forgetObject(p, delivered) return c.serveFinished(ctx, p, delivered) } @@ -529,7 +532,7 @@ func (c *commitRequestCore) drive( target *configbutleraiv1alpha3.GitTarget, provider *configbutleraiv1alpha3.KubeProvider, ) (time.Duration, error) { // Remembered before anything reaches a worker, so whatever it decides is written at shutdown. - c.inFlight.track(c, p, cr) + c.inFlight.track(c, p, client.ObjectKeyFromObject(cr)) attach := c.attachFor(cr) if target != nil && string(target.UID) != cr.Status.GitTargetUID { admitted, refusal, err := c.admit(ctx, p, cr, target, provider) diff --git a/internal/controller/commitrequest_settle.go b/internal/controller/commitrequest_settle.go index 0187aecc1..c0b045753 100644 --- a/internal/controller/commitrequest_settle.go +++ b/internal/controller/commitrequest_settle.go @@ -9,8 +9,6 @@ import ( "github.com/go-logr/logr" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - - configbutleraiv1alpha3 "github.com/ConfigButler/gitops-reverser/api/v1alpha3" ) // A save's outcome is decided by its branch worker and lives in the worker's memory until a step of @@ -44,19 +42,14 @@ type inFlightKey struct { request types.NamespacedName } -// inFlightRequest is how to take a step of a remembered request, and its UID. +// inFlightRequest is how to take a step of a remembered request. type inFlightRequest struct { core *commitRequestCore path commitRequestPath - uid types.UID } // track remembers a request p attaches. -func (f *CommitRequestsInFlight) track( - c *commitRequestCore, - p commitRequestPath, - cr *configbutleraiv1alpha3.CommitRequest, -) { +func (f *CommitRequestsInFlight) track(c *commitRequestCore, p commitRequestPath, key types.NamespacedName) { if f == nil { return } @@ -65,11 +58,10 @@ func (f *CommitRequestsInFlight) track( if f.requests == nil { f.requests = map[inFlightKey]inFlightRequest{} } - f.requests[inFlightKey{provider: p.provider, request: client.ObjectKeyFromObject(cr)}] = - inFlightRequest{core: c, path: p, uid: cr.UID} + f.requests[inFlightKey{provider: p.provider, request: key}] = inFlightRequest{core: c, path: p} } -// forget drops a request that finished, or is gone, as read fresh by its name. +// forget drops a request that finished, or is gone. func (f *CommitRequestsInFlight) forget(p commitRequestPath, key types.NamespacedName) { if f == nil { return @@ -79,20 +71,6 @@ func (f *CommitRequestsInFlight) forget(p commitRequestPath, key types.Namespace delete(f.requests, inFlightKey{provider: p.provider, request: key}) } -// forgetObject drops cr, which finished, only if the request remembered under its name has cr's UID: an -// old delivered object must not drop a newer request that reuses the name. -func (f *CommitRequestsInFlight) forgetObject(p commitRequestPath, cr *configbutleraiv1alpha3.CommitRequest) { - if f == nil { - return - } - f.mu.Lock() - defer f.mu.Unlock() - key := inFlightKey{provider: p.provider, request: client.ObjectKeyFromObject(cr)} - if remembered, ok := f.requests[key]; ok && remembered.uid == cr.UID { - delete(f.requests, key) - } -} - // remembered copies the requests out, for Settle to step through without the lock. func (f *CommitRequestsInFlight) remembered() map[inFlightKey]inFlightRequest { f.mu.Lock() diff --git a/internal/controller/commitrequest_settle_test.go b/internal/controller/commitrequest_settle_test.go index 0e5c25aa3..eee32aee7 100644 --- a/internal/controller/commitrequest_settle_test.go +++ b/internal/controller/commitrequest_settle_test.go @@ -281,30 +281,12 @@ func TestCommitRequestsInFlight_ASourceClusterRequestIsSettledOnItsCluster(t *te func TestCommitRequestsInFlight_Nil(t *testing.T) { var inFlight *CommitRequestsInFlight assert.NotPanics(t, func() { - inFlight.track(&commitRequestCore{}, commitRequestPath{}, newCommitRequest("save")) + inFlight.track(&commitRequestCore{}, commitRequestPath{}, types.NamespacedName{Name: "save"}) inFlight.forget(commitRequestPath{}, types.NamespacedName{Name: "save"}) - inFlight.forgetObject(commitRequestPath{}, newCommitRequest("save")) inFlight.Settle(context.Background()) }) } -// A finished object of a request that another of its name replaced, as a list or watch event may still -// deliver it, leaves the new request remembered: only that request's own object drops it. -func TestCommitRequestsInFlight_AnOldObjectOfAReplacedRequestLeavesTheNewOne(t *testing.T) { - inFlight := &CommitRequestsInFlight{} - p := commitRequestPath{provider: types.NamespacedName{Namespace: "default", Name: "edge"}} - replaced := newCommitRequest("save") - replacement := newCommitRequest("save") - replacement.UID = "uid-save-again" - inFlight.track(&commitRequestCore{}, p, replacement) - - inFlight.forgetObject(p, replaced) - assert.Len(t, inFlight.remembered(), 1, "the replaced request's object leaves the new one remembered") - - inFlight.forgetObject(p, replacement) - assert.Empty(t, inFlight.remembered(), "its own object drops it") -} - // A shutdown out of time writes nothing more: what is left is attached again by the next process. func TestCommitRequestsInFlight_OutOfTimeLeavesTheRest(t *testing.T) { c := newCommitRequestClient(t, nil, withInProgress(newCommitRequest("save")))