Skip to content

Commit cfc61c2

Browse files
committed
refactor(flowcontrol): address non-blocking review feedback from llm-d#1354
No functional change. Picks up review nits left on llm-d#1354: - ensureFlowInfrastructure: drop the redundant priority-band existence check. buildFlowComponents already re-checks the same map under its own read lock and returns the identical ErrPriorityBandNotFound, so fold the not-found case into that single critical section (one lock acquisition instead of two on a flow's first request). - Rename the priority-0 fallback from "demotion" to "fallback" (withConnectionWithFallback / fallbackRequest / fallbackKey). Relative to the requested priority, falling back to 0 is a demotion for positive priorities but a promotion for negative ones, so the neutral name is more accurate; note the semantics in the doc comment and log at priority-0. - SubmitDesiredPriorities: rename the local map to avoid shadowing the builtin copy. - ApplyDesiredPriorities: reword the post-idle re-check comment. Holding fr.mu does not exclude a concurrent lock-free pin; the check is a cheap best-effort guard and the real safety net is pinLeasedResource's stale-object protection plus the priority-0 fallback and self-healing GC. Signed-off-by: Luke Van Drie <lukevandrie@google.com>
1 parent 019e1a8 commit cfc61c2

3 files changed

Lines changed: 35 additions & 36 deletions

File tree

pkg/epp/flowcontrol/controller/controller.go

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ func (fc *FlowController) EnqueueAndWait(
239239

240240
// 2. Acquire a lease for the Flow.
241241
// We hold this lease for the entire duration of the request (Distribution + Queueing).
242-
err := fc.withConnectionWithDemotion(req, func(conn contracts.ActiveFlowConnection, effectiveReq flowcontrol.FlowControlRequest) error {
242+
err := fc.withConnectionWithFallback(req, func(conn contracts.ActiveFlowConnection, effectiveReq flowcontrol.FlowControlRequest) error {
243243

244244
select { // Non-blocking check on controller lifecycle.
245245
case <-fc.parentCtx.Done():
@@ -249,7 +249,7 @@ func (fc *FlowController) EnqueueAndWait(
249249
}
250250

251251
// Attempt to distribute the request once, passing the active connection.
252-
// effectiveReq carries the demoted flow key when the requested band was not provisioned, so the
252+
// effectiveReq carries the fallback flow key when the requested band was not provisioned, so the
253253
// item is enqueued under the band that was actually leased.
254254
item, err := fc.tryDistribution(reqCtx, effectiveReq, enqueueTime, conn)
255255
if err != nil {
@@ -280,19 +280,22 @@ func (fc *FlowController) EnqueueAndWait(
280280
return finalOutcome, err
281281
}
282282

283-
// demotedRequest wraps a FlowControlRequest to override its flow key, so a request demoted to a fallback
283+
// fallbackRequest wraps a FlowControlRequest to override its flow key, so a request that falls back to a different
284284
// priority is enqueued under the band that was actually leased rather than its original (unprovisioned) band.
285-
type demotedRequest struct {
285+
type fallbackRequest struct {
286286
flowcontrol.FlowControlRequest
287287
key flowcontrol.FlowKey
288288
}
289289

290-
func (d demotedRequest) FlowKey() flowcontrol.FlowKey { return d.key }
290+
func (r fallbackRequest) FlowKey() flowcontrol.FlowKey { return r.key }
291291

292-
// withConnectionWithDemotion acquires a flow connection, demoting to priority 0 when the requested band is not yet
293-
// provisioned. On demotion, the callback receives a request whose FlowKey reports the demoted priority, ensuring the
294-
// item is leased, distributed, and enqueued consistently under priority 0; otherwise it receives the original request.
295-
func (fc *FlowController) withConnectionWithDemotion(
292+
// withConnectionWithFallback acquires a flow connection, falling back to priority 0 when the requested band is not yet
293+
// provisioned. On fallback, the callback receives a request whose FlowKey reports priority 0, ensuring the item is
294+
// leased, distributed, and enqueued consistently under priority 0; otherwise it receives the original request.
295+
//
296+
// Note: relative to the requested priority this is a demotion for positive priorities but a promotion for negative
297+
// ones. It is an availability-first fallback for the brief window before the control plane provisions the band.
298+
func (fc *FlowController) withConnectionWithFallback(
296299
req flowcontrol.FlowControlRequest,
297300
fn func(conn contracts.ActiveFlowConnection, effectiveReq flowcontrol.FlowControlRequest) error,
298301
) error {
@@ -305,15 +308,15 @@ func (fc *FlowController) withConnectionWithDemotion(
305308
}
306309

307310
fc.logger.V(logutil.DEFAULT).Info(
308-
"Priority band not provisioned, demoting request to priority 0",
311+
"Priority band not provisioned, falling back to priority 0",
309312
"originalPriority", key.Priority,
310313
"flowID", key.ID,
311314
)
312-
demotedKey := key
313-
demotedKey.Priority = 0
314-
demoted := demotedRequest{FlowControlRequest: req, key: demotedKey}
315-
return fc.registry.WithConnection(demotedKey, func(conn contracts.ActiveFlowConnection) error {
316-
return fn(conn, demoted)
315+
fallbackKey := key
316+
fallbackKey.Priority = 0
317+
fallback := fallbackRequest{FlowControlRequest: req, key: fallbackKey}
318+
return fc.registry.WithConnection(fallbackKey, func(conn contracts.ActiveFlowConnection) error {
319+
return fn(conn, fallback)
317320
})
318321
}
319322

pkg/epp/flowcontrol/controller/controller_test.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1071,11 +1071,11 @@ func TestFlowController_Concurrency_Backpressure(t *testing.T) {
10711071
"all concurrent requests should be dispatched successfully even under high contention and zero buffer capacity")
10721072
}
10731073

1074-
// TestFlowController_EnqueueAndWait_DemotionRewritesItemPriority verifies that when the requested priority band is not
1074+
// TestFlowController_EnqueueAndWait_FallbackRewritesItemPriority verifies that when the requested priority band is not
10751075
// provisioned, the request is not only leased at the fallback priority (0) but also enqueued there: the FlowItem handed
1076-
// to the processor must report the demoted flow key, not the original (unprovisioned) priority. Without this, the
1077-
// processor looks up a managed queue at the missing band and rejects the demoted request.
1078-
func TestFlowController_EnqueueAndWait_DemotionRewritesItemPriority(t *testing.T) {
1076+
// to the processor must report the fallback flow key, not the original (unprovisioned) priority. Without this, the
1077+
// processor looks up a managed queue at the missing band and rejects the request.
1078+
func TestFlowController_EnqueueAndWait_FallbackRewritesItemPriority(t *testing.T) {
10791079
t.Parallel()
10801080

10811081
ctx, cancel := context.WithCancel(context.Background())
@@ -1094,7 +1094,7 @@ func TestFlowController_EnqueueAndWait_DemotionRewritesItemPriority(t *testing.T
10941094

10951095
registry := &mockRegistryClient{FlowRegistryDataPlane: &mocks.MockRegistryDataPlane{}}
10961096
registry.WithConnectionFunc = func(key flowcontrol.FlowKey, fn func(conn contracts.ActiveFlowConnection) error) error {
1097-
// Only priority 0 is provisioned; any other band is rejected, forcing demotion.
1097+
// Only priority 0 is provisioned; any other band is rejected, forcing the fallback.
10981098
if key.Priority != 0 {
10991099
return fmt.Errorf("band %d: %w", key.Priority, contracts.ErrPriorityBandNotFound)
11001100
}
@@ -1105,9 +1105,9 @@ func TestFlowController_EnqueueAndWait_DemotionRewritesItemPriority(t *testing.T
11051105

11061106
outcome, err := h.fc.EnqueueAndWait(ctx, newTestRequest(flowcontrol.FlowKey{ID: "batch", Priority: originalPriority}))
11071107

1108-
require.NoError(t, err, "demoted request should be dispatched, not rejected")
1108+
require.NoError(t, err, "fallback request should be dispatched, not rejected")
11091109
assert.Equal(t, types.QueueOutcomeDispatched, outcome)
11101110
assert.Equal(t, 0, capturedKey.Priority,
1111-
"demoted request must be enqueued at priority 0, not its original unprovisioned priority")
1112-
assert.Equal(t, "batch", capturedKey.ID, "demotion must preserve the flow ID")
1111+
"fallback request must be enqueued at priority 0, not its original unprovisioned priority")
1112+
assert.Equal(t, "batch", capturedKey.ID, "fallback must preserve the flow ID")
11131113
}

pkg/epp/flowcontrol/registry/registry.go

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -202,9 +202,9 @@ func (fr *FlowRegistry) SubmitDesiredPriorities(desired map[int]struct{}) {
202202
if desired == nil {
203203
desired = map[int]struct{}{}
204204
}
205-
copy := make(map[int]struct{}, len(desired))
205+
desiredCopy := make(map[int]struct{}, len(desired))
206206
for priority := range desired {
207-
copy[priority] = struct{}{}
207+
desiredCopy[priority] = struct{}{}
208208
}
209209

210210
// Drain any stale pending update so only the latest state is queued.
@@ -214,7 +214,7 @@ func (fr *FlowRegistry) SubmitDesiredPriorities(desired map[int]struct{}) {
214214
}
215215

216216
// After draining, the channel always has capacity; this send never blocks.
217-
fr.priorityBandUpdateCh <- copy
217+
fr.priorityBandUpdateCh <- desiredCopy
218218
}
219219

220220
// PriorityBandUpdateChannel returns the channel carrying desired priority topology updates.
@@ -256,8 +256,10 @@ func (fr *FlowRegistry) ApplyDesiredPriorities(desired map[int]struct{}) {
256256
if !fr.isPriorityBandIdle(priority) {
257257
continue
258258
}
259-
// Re-verify under the lock: a concurrent request may have pinned the band
260-
// in the window between isPriorityBandIdle and this check.
259+
// Cheap best-effort guard against tearing down a band that just became active. Holding fr.mu does
260+
// not actually exclude a concurrent pin: pinLeasedResource is lock-free and never takes fr.mu. The
261+
// removal is safe regardless, since pinLeasedResource's stale-object protection backs off a racing
262+
// pin and the priority-0 fallback plus the next reconcile/GC cycle self-heal.
261263
if val, ok := fr.priorityBandStates.Load(priority); ok {
262264
if val.(*priorityBandState).isActive() {
263265
continue
@@ -342,14 +344,8 @@ func (fr *FlowRegistry) WithConnection(key flowcontrol.FlowKey, fn func(conn con
342344
//
343345
// NOTE: The caller (WithConnection) must already hold a lease on the priority band to prevent GC during this operation.
344346
func (fr *FlowRegistry) ensureFlowInfrastructure(key flowcontrol.FlowKey) error {
345-
fr.mu.RLock()
346-
_, exists := fr.config.PriorityBands[key.Priority]
347-
fr.mu.RUnlock()
348-
349-
if !exists {
350-
return fmt.Errorf("priority band %d not found: %w", key.Priority, contracts.ErrPriorityBandNotFound)
351-
}
352-
347+
// buildFlowComponents validates that the priority band exists (returning ErrPriorityBandNotFound if not)
348+
// under the same read lock it uses to read the topology, so a single acquisition covers both.
353349
fr.mu.RLock()
354350
components, err := fr.buildFlowComponents(key)
355351
fr.mu.RUnlock()

0 commit comments

Comments
 (0)