Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 83 additions & 1 deletion cmd/reconciler/shared/batcher_retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ const (
minRetryBackoff = 250 * time.Millisecond // smallest delay before resending
maxRetryBackoff = 30 * time.Second // cap on exponential retry backoff
maxRetryAge = 5 * time.Minute // retry budget from first failure
// maxIsolatedWorkUnits caps work units resent individually per failed batch.
maxIsolatedWorkUnits = 32
// maxConsecutivePermanentFailures (work units) stops isolation as experiment-wide.
maxConsecutivePermanentFailures = 3

dropReasonPermanent = "permanent"
dropReasonRetryBudgetExhausted = "retry_budget_exhausted"
Expand Down Expand Up @@ -203,12 +207,32 @@ func updatePointers(batch []batchEntry) []*storagepkg.WorkUnitExecutionUpdate {
return updates
}

// handleFlushFailure requeues a transiently failed batch. A permanent failure
// drops a single-work-unit batch; otherwise up to maxIsolatedWorkUnits work
// units are resent one work unit at a time so a single bad work unit does not
// drop the others. Remaining work units are requeued, or dropped if isolation
// found the failure to be experiment-wide.
func (b *UpdateBatcher) handleFlushFailure(ctx context.Context, xid int64, batch []batchEntry, err error) {
if !IsPermanentStorageError(err) {
b.requeue(ctx, xid, batch, err)
return
}
b.recordDropped(ctx, xid, batch, dropReasonPermanent, err)
groups := groupByWorkUnit(batch)
if len(groups) == 1 {
b.recordDropped(ctx, xid, batch, dropReasonPermanent, err)
return
}
isolated := groups[:min(len(groups), maxIsolatedWorkUnits)]
experimentWide := b.isolatePermanentFailure(ctx, xid, isolated)
overflow := slices.Concat(groups[len(isolated):]...)
if len(overflow) == 0 {
return
}
if experimentWide {
b.recordDropped(ctx, xid, overflow, dropReasonPermanent, err)
return
}
b.requeue(ctx, xid, overflow, err)
Comment thread
VLukiantsev marked this conversation as resolved.
Resolved
}

func countWorkUnits(batch []batchEntry) int {
Expand All @@ -221,6 +245,64 @@ func countWorkUnits(batch []batchEntry) int {
return count
}

// groupByWorkUnit splits a batch sorted by WID into per-WID groups, ordered by
// descending max retry attempt (preserving ascending WID on ties) so previously
// requeued overflow work units are isolated ahead of fresh ones.
func groupByWorkUnit(batch []batchEntry) [][]batchEntry {
var groups [][]batchEntry
for i, entry := range batch {
if i == 0 || entry.update.WID != batch[i-1].update.WID {
groups = append(groups, nil)
}
groups[len(groups)-1] = append(groups[len(groups)-1], entry)
}
slices.SortStableFunc(groups, func(a, b []batchEntry) int {
return cmp.Compare(maxGroupAttempt(b), maxGroupAttempt(a))
})
return groups
}

func maxGroupAttempt(group []batchEntry) int {
maxAttempt := 0
for _, entry := range group {
maxAttempt = max(maxAttempt, entry.attempt)
}
return maxAttempt
}

// isolatePermanentFailure resends each work unit's updates in one call, at most
// once. It stops at the first transient failure or context cancellation,
// requeueing that work unit and all unsent ones. After
// maxConsecutivePermanentFailures work units in a row fail permanently, it drops
// the unsent ones and reports the failure as experiment-wide.
func (b *UpdateBatcher) isolatePermanentFailure(ctx context.Context, xid int64, groups [][]batchEntry) (experimentWide bool) {
consecutivePermanent := 0
// Requeueing must still run (and log) after ctx is cancelled.
cleanupCtx := context.WithoutCancel(ctx)
for i, group := range groups {
if ctx.Err() != nil {
b.requeue(cleanupCtx, xid, slices.Concat(groups[i:]...), ctx.Err())
return false
}
Comment thread
VLukiantsev marked this conversation as resolved.
Resolved
err := b.callUpdateWorkUnitExecutions(ctx, xid, updatePointers(group))
if err == nil {
consecutivePermanent = 0
continue
}
if !IsPermanentStorageError(err) {
b.requeue(cleanupCtx, xid, slices.Concat(groups[i:]...), err)
return false
}
Comment thread
VLukiantsev marked this conversation as resolved.
Resolved
b.recordDropped(ctx, xid, group, dropReasonPermanent, err)
consecutivePermanent++
if consecutivePermanent >= maxConsecutivePermanentFailures {
b.recordDropped(ctx, xid, slices.Concat(groups[i+1:]...), dropReasonPermanent, err)
return true
}
}
return false
}

func (b *UpdateBatcher) requeue(ctx context.Context, xid int64, entries []batchEntry, err error) {
if expired := b.scheduleRetries(xid, entries, b.currentTime()); len(expired) > 0 {
b.recordDropped(ctx, xid, expired, dropReasonRetryBudgetExhausted, err)
Expand Down
170 changes: 153 additions & 17 deletions cmd/reconciler/shared/batcher_retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -422,24 +422,160 @@ func TestRetry_InFlightRemoveAndAddSupersede(t *testing.T) {
}
}

func TestRetry_PermanentErrorsDroppedWithoutRetry(t *testing.T) {
for _, wids := range [][]int64{{1}, {1, 2, 3}} {
storage := &scriptedStorage{alwaysErr: grpcerr.ErrNotFound}
b, clock := newRetryTestBatcher(t, storage)
addRunning(t, b, retryTestXID, wids...)
b.processBatches(t.Context())
clock.advance(time.Minute)
b.processBatches(t.Context())
func TestRetry_PermanentSingleUpdateDroppedWithoutRetry(t *testing.T) {
storage := &scriptedStorage{alwaysErr: grpcerr.ErrNotFound}
b, clock := newRetryTestBatcher(t, storage)
addRunning(t, b, retryTestXID, 1)
b.processBatches(t.Context())
clock.advance(time.Minute)
b.processBatches(t.Context())

if got := storage.callCount(); got != 1 {
t.Errorf("wids=%v: storage calls = %d, want 1", wids, got)
}
if got := droppedCount(dropReasonPermanent); got != float64(len(wids)) {
t.Errorf("wids=%v: dropped{permanent} = %v, want %d", wids, got, len(wids))
}
if got := queuedRetries(b); got != 0 {
t.Errorf("wids=%v: queued retries = %d, want 0", wids, got)
}
if got := storage.callCount(); got != 1 {
t.Errorf("storage calls = %d, want 1 (no retry)", got)
}
if got := droppedCount(dropReasonPermanent); got != 1 {
t.Errorf("dropped{permanent} = %v, want 1", got)
}
if got := queuedRetries(b); got != 0 {
t.Errorf("queued retries = %d, want 0", got)
}
}

func TestRetry_PermanentMultiWorkUnitIsolation(t *testing.T) {
tests := []struct {
name string
numWorkUnits int
// multiSourceWID, if set, also gets Workload and KueueSync updates.
multiSourceWID int64
storage *scriptedStorage
cancelCtx bool
wantCalls int
wantDropped float64
wantQueue int
}{
{
name: "bad work unit dropped, others persisted",
numWorkUnits: 3,
storage: &scriptedStorage{errForWID: map[int64]error{2: grpcerr.ErrNotFound}},
wantCalls: 4, // batch + 3 work units
wantDropped: 1,
},
{
name: "all updates of a bad work unit go in one call",
numWorkUnits: 4,
multiSourceWID: 1,
storage: &scriptedStorage{errForWID: map[int64]error{1: grpcerr.ErrNotFound}},
wantCalls: 1 + 4,
wantDropped: 3, // Jobset, Workload, and KueueSync updates of WID 1
},
{
name: "consecutive permanent work units stop isolation",
numWorkUnits: 5,
storage: &scriptedStorage{alwaysErr: grpcerr.ErrNotFound},
wantCalls: 1 + maxConsecutivePermanentFailures,
wantDropped: 5,
},
{
name: "experiment-wide failure drops the overflow",
numWorkUnits: maxIsolatedWorkUnits + 8,
storage: &scriptedStorage{alwaysErr: grpcerr.ErrNotFound},
wantCalls: 1 + maxConsecutivePermanentFailures,
wantDropped: maxIsolatedWorkUnits + 8,
},
{
name: "non-consecutive permanent failures reset streak",
numWorkUnits: 5,
storage: &scriptedStorage{errForWID: map[int64]error{1: grpcerr.ErrNotFound, 2: grpcerr.ErrNotFound, 4: grpcerr.ErrNotFound}},
wantCalls: 1 + 5,
wantDropped: 3,
},
{
name: "transient failure aborts and requeues the rest",
numWorkUnits: 3,
storage: &scriptedStorage{errs: []error{grpcerr.ErrNotFound, nil, grpcerr.ErrUnavailable}},
wantCalls: 3, // batch + WID 1 (succeeds) + WID 2 (transient error)
wantQueue: 2, // WID 2 and WID 3 requeued; WID 1 already persisted
},
{
name: "fan-out capped, overflow requeued",
numWorkUnits: maxIsolatedWorkUnits + 8,
storage: &scriptedStorage{errs: []error{grpcerr.ErrNotFound}},
wantCalls: 1 + maxIsolatedWorkUnits,
wantQueue: 8,
},
{
name: "cancelled context requeues without isolated calls",
numWorkUnits: 3,
storage: &scriptedStorage{errs: []error{grpcerr.ErrNotFound}},
cancelCtx: true,
wantCalls: 1,
wantQueue: 3,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
b, _ := newRetryTestBatcher(t, tc.storage)
for wid := range tc.numWorkUnits {
addRunning(t, b, retryTestXID, int64(wid+1))
}
if tc.multiSourceWID != 0 {
for _, source := range []UpdateSource{WorkloadSource, KueueSyncSource} {
b.Add(t.Context(), retryTestXID, testUpdate(tc.multiSourceWID, 1, stateRunning), source)
}
}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
if tc.cancelCtx {
cancel()
}

b.processBatches(ctx)

if got := tc.storage.callCount(); got != tc.wantCalls {
t.Errorf("storage calls = %d, want %d", got, tc.wantCalls)
}
if got := droppedCount(dropReasonPermanent); got != tc.wantDropped {
t.Errorf("dropped{permanent} = %v, want %v", got, tc.wantDropped)
}
if got := queuedRetries(b); got != tc.wantQueue {
t.Errorf("queued retries = %d, want %d", got, tc.wantQueue)
}
})
}
}

func TestRetry_IsolationPrioritizesRequeuedOverflow(t *testing.T) {
badWID := int64(maxIsolatedWorkUnits + 8)
storage := &scriptedStorage{errForWID: map[int64]error{badWID: grpcerr.ErrInvalidArgument}}
b, _ := newRetryTestBatcher(t, storage)
for wid := range badWID {
addRunning(t, b, retryTestXID, wid+1)
}

// Tick 1: batch of 40 fails; WID 1..32 isolated and succeed, WID 33..40 requeued (attempt=1).
b.processBatches(t.Context())
if got := queuedRetries(b); got != 8 {
t.Fatalf("after tick 1: queued retries = %d, want 8", got)
}

// Tick 2: WID 1..32 emit fresh updates (attempt=0). Requeued WID 33..40 (attempt=1)
// must be isolated first so WID 33..39 persist and WID 40 is dropped.
for wid := range int64(maxIsolatedWorkUnits) {
addRunning(t, b, retryTestXID, wid+1)
}
b.processBatches(t.Context())

if got := droppedCount(dropReasonPermanent); got != 1 {
t.Errorf("after tick 2: dropped{permanent} = %v, want 1 (WID %d)", got, badWID)
}
if got := queuedRetries(b); got != 8 {
t.Errorf("after tick 2: queued retries = %d, want 8 (fresh WID 25..32 overflow)", got)
}
b.UpdatesMu.Lock()
_, badStillQueued := b.retries[slotKey{xid: retryTestXID, wid: badWID, source: JobsetSource}]
b.UpdatesMu.Unlock()
if badStillQueued {
t.Errorf("WID %d still queued in retries after tick 2, want isolated and dropped", badWID)
}
}

Expand Down
29 changes: 22 additions & 7 deletions docs/flows/reconciliation.md
Original file line number Diff line number Diff line change
Expand Up @@ -294,8 +294,15 @@ sequenceDiagram
Storage-->>Batcher: map[WID] WorkUnitExecution (or error)
alt Transient error
Batcher->>Batcher: Queue each update for retry with backoff
else Permanent error
Batcher->>Batcher: Drop the batch (reason=permanent)
else Permanent error, single work unit
Batcher->>Batcher: Drop the work unit's updates (reason=permanent)
else Permanent error, more than one work unit
loop Up to 32 work units (requeued first), one work unit per call
Batcher->>Storage: UpdateWorkUnitExecutions(xid, updates of one WID)
Note over Batcher: Transient error or cancelled: requeue it and the rest, stop
Note over Batcher: 3 work units failing permanently in a row: drop the rest, stop
end
Batcher->>Batcher: Work units beyond 32: drop if experiment-wide, else requeue
Comment thread
VLukiantsev marked this conversation as resolved.
Resolved
end
```

Expand Down Expand Up @@ -337,10 +344,18 @@ When a flush fails, the batcher classifies the error the same way the JobSet fin
`(xid, wid, source)`. The retry waits with exponential backoff, starting at the tick duration
(at least 250 ms), doubling per attempt, and capped at 30 s. An update that is still failing
more than 5 minutes after its first failure is dropped.
- **Permanent** (`NotFound`, `InvalidArgument`, `FailedPrecondition`, `PermissionDenied`): retrying
cannot help, so the whole batch is dropped and counted with `reason="permanent"`. Requeued
updates are charged a backoff attempt and, if they expire, are counted as
`retry_budget_exhausted`.
- **Permanent, single work unit:** the work unit's updates are dropped.
- **Permanent, multiple work units:** one bad work unit fails the whole per-experiment transaction,
so up to 32 work units are resent on their own, one work unit (all of its sources' updates) per
call, since Storage reports missing rows per work unit. Work units that succeed are persisted and
those that fail permanently are dropped. Isolation stops early at the first transient failure or
context cancellation (that work unit and all unsent ones are requeued), and after 3 work units in
a row fail permanently, which is treated as experiment-wide (the unsent work units are dropped).
Work units beyond the first 32 are dropped if the failure was experiment-wide and requeued
otherwise, draining over later ticks. Requeued updates, including this overflow, are charged a
backoff attempt and, if they expire, are counted as `retry_budget_exhausted`. Isolated writes are
separate transactions, so they can record intermediate status-history rows that a single batched
write would not.

On each tick, queued retries are merged with the new pending updates slot by slot
(`(xid, wid, source)`), mirroring `Add`:
Expand All @@ -365,7 +380,7 @@ Metrics:
updates.
- `batcher_updates_retried_total{xid}` counts retries merged back into a flush.
- `batcher_retry_queue_size` is the current retry-queue length.
- `xmc_actuator_batcher_update_calls_total` now includes retried calls, and
- `xmc_actuator_batcher_update_calls_total` now includes retried and isolated calls, and
`batcher_updates_processed_total` counts a retried update again each time it is flushed.

The batcher is still an in-memory buffer, and it makes the usual trade: if the Reconciler pod dies
Expand Down
Loading