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
67 changes: 49 additions & 18 deletions mooncake-p2p-store/src/p2pstore/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"net"
"strconv"
"sync"
"time"
)

// When the data size larger than MAX_CHUNK_SIZE bytes, we split them into multiple buffers and registered separately.
Expand Down Expand Up @@ -475,34 +476,64 @@ func performTransferOnce(ctx context.Context, transport batchTransport, source u
return STATUS_FAILED, err
}

for isTransferInFlight(status) {
select {
case <-ctx.Done():
if _, drainErr := drainTransfer(transport, batchID); drainErr != nil {
return STATUS_FAILED, drainErr
}
return STATUS_FAILED, ctx.Err()
default:
status, _, err = transport.getTransferStatus(batchID, 0)
if err != nil {
return STATUS_FAILED, err
}
}
status, err = waitTransfer(ctx, transport, batchID)
if err != nil {
return STATUS_FAILED, err
}

return status, nil
}

// drainTransfer polls the batch until its task reaches a terminal state so
// the batch can be freed.
func drainTransfer(transport batchTransport, batchID BatchID) (int, error) {
// Polling schedule for waitTransfer. The first pollSpinBudget polls run
// back-to-back so short transfers still complete with no added latency;
// after that the poller backs off exponentially from pollMinInterval to
// pollMaxInterval. The cap stays small because some transports (for example
// the NVLink async transport) only advance completion state when polled.
const (
pollSpinBudget = 128
pollMinInterval = 100 * time.Microsecond
pollMaxInterval = time.Millisecond
)

// sleepFn is the sleep used between polls. Tests replace it to observe the
// backoff schedule without depending on wall-clock timing.
var sleepFn = time.Sleep

// waitTransfer polls task 0 of batchID until it reaches a terminal state.
// The task is always driven to a terminal state, even if ctx is cancelled
// (the engine refuses to free a batch with in-flight tasks). Cancellation
// is then authoritative: if ctx is done by the time the task is terminal,
// ctx.Err() is returned regardless of the observed status.
//
// doGetReplica starts one goroutine per shard, so for a checkpoint-sized
// payload hundreds of pollers may be active at once. Spinning them all at
// full speed for a transfer that takes seconds buys nothing in completion
// latency and saturates cores; the spin budget plus backoff keeps the
// fast path for small transfers while bounding CPU on large ones.
func waitTransfer(ctx context.Context, transport batchTransport, batchID BatchID) (int, error) {
status := STATUS_WAITING
for isTransferInFlight(status) {
interval := pollMinInterval
for polls := 0; ; polls++ {
Comment on lines +512 to +515
var err error
status, _, err = transport.getTransferStatus(batchID, 0)
if err != nil {
return STATUS_FAILED, err
}
if !isTransferInFlight(status) {
break
}
if polls < pollSpinBudget {
continue
}
sleepFn(interval)
if interval < pollMaxInterval {
interval *= 2
if interval > pollMaxInterval {
interval = pollMaxInterval
}
}
}
if err := ctx.Err(); err != nil {
return STATUS_FAILED, err
}
return status, nil
}
Expand Down
87 changes: 87 additions & 0 deletions mooncake-p2p-store/src/p2pstore/perform_transfer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"context"
"errors"
"testing"
"time"
)

var errBatchBusy = errors.New("BatchID cannot be freed until all tasks are done")
Expand Down Expand Up @@ -118,3 +119,89 @@ func TestPerformTransferOnceSubmitErrorFreesBatch(t *testing.T) {
t.Fatal("batch ID leaked on submit failure")
}
}

// recordSleeps swaps sleepFn for a recorder so tests can assert the exact
// backoff schedule instead of measuring wall-clock time.
func recordSleeps(t *testing.T) *[]time.Duration {
t.Helper()
var slept []time.Duration
prev := sleepFn
sleepFn = func(d time.Duration) { slept = append(slept, d) }
t.Cleanup(func() { sleepFn = prev })
return &slept
}

// TestWaitTransferBacksOffAfterSpinBudget checks the polling schedule: within
// the spin budget polls are back-to-back, after it every in-flight poll is
// followed by one sleep, growing 100µs, 200µs, 400µs, 800µs, then capped at 1ms.
func TestWaitTransferBacksOffAfterSpinBudget(t *testing.T) {
const extraPolls = 40
slept := recordSleeps(t)
fake := &fakeBatchTransport{pollsUntilDone: pollSpinBudget + extraPolls, finalStatus: STATUS_COMPLETED}
fake.submitted = true

status, err := waitTransfer(context.Background(), fake, BatchID(1))
if err != nil || status != STATUS_COMPLETED {
t.Fatalf("status=%d err=%v", status, err)
}
// The fake reports terminal state on poll number pollsUntilDone.
if fake.polls != pollSpinBudget+extraPolls {
t.Fatalf("polls = %d, want %d", fake.polls, pollSpinBudget+extraPolls)
}

var want []time.Duration
interval := pollMinInterval
for i := 0; i < extraPolls-1; i++ {
want = append(want, interval)
if interval < pollMaxInterval {
interval *= 2
if interval > pollMaxInterval {
interval = pollMaxInterval
}
}
}
if len(*slept) != len(want) {
t.Fatalf("sleep count = %d, want %d: %v", len(*slept), len(want), *slept)
}
for i := range want {
if (*slept)[i] != want[i] {
t.Fatalf("sleep[%d] = %v, want %v (schedule %v)", i, (*slept)[i], want[i], *slept)
}
}
if (*slept)[len(*slept)-1] != pollMaxInterval {
t.Fatalf("backoff did not reach the cap: last sleep %v", (*slept)[len(*slept)-1])
}
}

func TestWaitTransferWithinSpinBudgetDoesNotSleep(t *testing.T) {
slept := recordSleeps(t)
fake := &fakeBatchTransport{pollsUntilDone: pollSpinBudget / 2, finalStatus: STATUS_COMPLETED}
fake.submitted = true
if _, err := waitTransfer(context.Background(), fake, BatchID(1)); err != nil {
t.Fatal(err)
}
if len(*slept) != 0 {
t.Fatalf("spin-budget path slept %d time(s): %v", len(*slept), *slept)
}
}

// TestWaitTransferCancelledContextWinsOverTerminalStatus pins the edge case
// where ctx is already cancelled and the very first poll reports a terminal
// status: cancellation is authoritative and ctx.Err() is returned.
func TestWaitTransferCancelledContextWinsOverTerminalStatus(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
fake := &fakeBatchTransport{pollsUntilDone: 0, finalStatus: STATUS_COMPLETED}
fake.submitted = true

status, err := waitTransfer(ctx, fake, BatchID(1))
if !errors.Is(err, context.Canceled) {
t.Fatalf("err = %v, want context.Canceled", err)
}
if status != STATUS_FAILED {
t.Fatalf("status = %d, want STATUS_FAILED", status)
}
if fake.polls != 1 {
t.Fatalf("polls = %d, want 1 (terminal on first poll)", fake.polls)
}
}
Loading