Files
seaweedfs/weed/util/http/chunk_read_hedge.go
T
9a98047e2a util/http: hedge a chunk read whose location goes quiet (#12917)
* util/http: hedge a chunk read whose location goes quiet

A chunk read tried its locations one at a time and read each answer to the
end. A response that stops arriving holds the read for as long as TCP takes
to recover: on a lossy path a lost segment costs at least the 200 ms
retransmission timeout, doubled for every further loss, and nothing gives
up on the connection meanwhile. A sequential reader waits for its chunks in
order, so one stalled chunk stops it, although a replica could send the
chunk in milliseconds. A location that never answers holds the read for the
transport's response header timeout.

In production this showed up as 13 GB checkpoint verifications, read back
serially with O_DIRECT through weed mount, crawling at 25-65 MB/s instead
of 300 MB/s and more, while the hosts of the volume servers saw 2-5% TCP
retransmissions. The volume servers' own GET latency stayed at a few
milliseconds: the stall is on the wire, after the handler has written the
chunk into the socket buffer.

hedgedChunkPass keeps the order and the move-on-at-failure of the old
loops. In addition, once every request in flight has been quiet for longer
than it may be, the read is asked of the next location as well, or, once
every location has been asked, again over a new connection of a location
whose server answered. A request may be quiet for 200 ms before its
response headers, while the server may still be reading the needle from a
busy disk, and for 100 ms in the body, which a healthy server sends without
pauses: half the minimum retransmission timeout, ahead of every wait for a
retransmission, while shorter pauses that recover on their own go by. The first complete answer wins, and the other requests are
cancelled. A read hedges at most twice.

The first request reads straight into the caller's buffer, as before.
Hedges read into pooled buffers, and a winning hedge is copied over only
after the request writing the caller's buffer has ended, so the buffer has
one writer at a time and is not written after the call returns.

Hedging is budgeted: every read earns a tenth of a token, a hedge spends
one, and at most ten are saved up, so hedges stay below about a tenth of
the reads when the whole cluster is slow. A location that had sent no
response headers when another one delivered the chunk is recorded as
unreachable, which leaves it to the background probe of #12776 to put it
first again, and counts as a failure for the location refresh. A body that
stalled after its headers does neither.

Measured with two volume servers whose outgoing links drop packets (netem,
MTU 1500, 0.2 ms delay), reading a 1 GiB file of 2 MiB chunks through weed
mount with dd iflag=direct bs=4M, before and after:

  bursty loss ~2.3% on both replicas   26-76 MB/s   162-193 MB/s
  random loss 3% on both replicas     106-119 MB/s  147-170 MB/s
  random loss 5% on one replica only   71-81 MB/s   157-158 MB/s
  no loss                             no change, 0-2 hedges per 512 reads

Under loss 4-8% of the chunk reads were hedged. A 50 ms body limit did
better on random loss (179-220 MB/s with 3% on both) but worse and less
steadily on bursty loss (108-206 MB/s), where it spent the hedge budget on
pauses that recover by themselves.

Callers: RetriedFetchChunkData on the streaming and the direct path, which
weed mount, the S3 gateway and the WebDAV server read chunks through.
Readers that stream a chunk to a writer as it arrives are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: account hedge buffers, go past a throttled hedge, cap hedges per read

Three review findings:

- A hedge reads into a buffer of its own, which weed mount's reader cache
  budget did not see, so stalled downloads could hold twice the configured
  memory. The reader cache now passes its budget in the context
  (WithScratchBudget), and a hedge first takes room for its buffer with
  ReaderCacheBudget.TryReserveScratch. Like a download, that evicts idle
  chunks no stream is positioned in, but it never waits and never evicts a
  pinned chunk or a download in flight: a hedge that does not fit is not
  sent. The room is returned when the buffer is freed, also for requests
  abandoned in the background.

- A hedge answered with 429 ended the asking, so the read waited out the
  stalled request although a third location was idle. The download limit
  behind a 429 is local to that server, so a throttled hedge now moves on to
  the next location; the 429 is still returned when nothing else delivers.

- Each retry pass earned a new budget share and started a new count of two
  hedges. Both now belong to the read (readHedges) and carry over its passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: note an error's headers as an answer, take a hedge token before room

Second round of review findings:

- A location that sent the headers of an error response (a 500, say) and
  then stalled its body was still taken for one that had not answered while
  StatusError waited for that body. Had another location delivered the chunk
  meanwhile, it was recorded as unreachable and the location list refreshed.
  The response headers are now noted as soon as Do returns, before the
  status is looked at.

- A hedge took room for its buffer before its token, and room can evict
  cached chunks. With no token left the room was given back, but the chunks
  were gone. The token now comes first, and is given back when there is no
  room.

- TestReaderCacheBudgetLendsScratchToHedges opens the gate of the download
  it holds in a defer, so a failed assertion cannot leave the cache's
  teardown waiting on it. TestChunkReadHedgeCapCoversRetries also checks that
  the read earned its budget share once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: do not take a location asked again for unreachable

A location whose response stalled is asked again over a new connection.
When the first request then recovered and delivered the chunk, the new
request had not answered yet, so the host that just served the chunk was
recorded as unreachable and the location list refreshed. A location any
request of the read heard from is no longer counted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-23 13:29:07 -08:00

472 lines
14 KiB
Go

package http
import (
"context"
"errors"
"io"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/util/mem"
)
// A chunk read whose location goes quiet is asked of another location as
// well. A volume server sends a chunk without pauses once it has answered, so
// a body that stops arriving for chunkReadStallDelay is waiting for a lost TCP
// segment: the retransmission timeout is at least 200 ms and doubles with
// every further loss, so on a lossy path one chunk can hold up a sequential
// reader for seconds, while a fresh request takes milliseconds. Half the
// minimum retransmission timeout still gets ahead of every such wait, and
// lets the shorter pauses that recover on their own go by without a hedge.
// Before the response headers the server is still reading the needle, which
// can take a while on a busy disk, so a location gets chunkReadAnswerDelay to
// answer; one silent for that long is on a hung or dead host, or its answer
// was lost. Tests shorten both.
var (
chunkReadAnswerDelay = 200 * time.Millisecond
chunkReadStallDelay = 100 * time.Millisecond
)
// maxHedgesPerRead caps the extra requests a single chunk read can make.
const maxHedgesPerRead = 2
// errNoAnswer marks a location that had not even sent its response headers by
// the time another location delivered the chunk.
var errNoAnswer = errors.New("no response headers before another location delivered the chunk")
// Hedging is budgeted so that a cluster that is slow everywhere is not asked
// for every chunk twice: every chunk read earns a tenth of a token, every
// hedge spends a whole one, and at most hedgeTokenBurst tokens are saved up.
// Hedges therefore stay below a tenth of the reads, apart from a burst of ten.
const (
hedgeTokenScale = 1000 // tokens are counted in thousandths
hedgeTokenEarn = hedgeTokenScale / 10
hedgeTokenBurst = 10 * hedgeTokenScale
)
var hedgeTokens = func() *atomic.Int64 {
var tokens atomic.Int64
tokens.Store(hedgeTokenBurst)
return &tokens
}()
func earnHedgeToken() {
for {
tokens := hedgeTokens.Load()
if tokens >= hedgeTokenBurst || hedgeTokens.CompareAndSwap(tokens, min(tokens+hedgeTokenEarn, hedgeTokenBurst)) {
return
}
}
}
// refundHedgeToken gives back the token of a hedge that was not sent after all.
func refundHedgeToken() {
for {
tokens := hedgeTokens.Load()
if hedgeTokens.CompareAndSwap(tokens, min(tokens+hedgeTokenScale, hedgeTokenBurst)) {
return
}
}
}
func spendHedgeToken() bool {
for {
tokens := hedgeTokens.Load()
if tokens < hedgeTokenScale {
return false
}
if hedgeTokens.CompareAndSwap(tokens, tokens-hedgeTokenScale) {
return true
}
}
}
// chunkProgress is what a chunk read reports while it runs: when something
// last arrived, and whether the response headers did. A nil one ignores it.
type chunkProgress struct {
lastArrival atomic.Int64 // unix nanoseconds
answered atomic.Bool
}
func (p *chunkProgress) arrived() {
if p != nil {
p.lastArrival.Store(time.Now().UnixNano())
}
}
func (p *chunkProgress) answer() {
if p != nil {
p.answered.Store(true)
p.arrived()
}
}
// progressReader reports every piece of a response body that arrives.
type progressReader struct {
reader io.Reader
progress *chunkProgress
}
func (r progressReader) Read(p []byte) (int, error) {
n, err := r.reader.Read(p)
if n > 0 {
r.progress.arrived()
}
return n, err
}
// chunkAttempt reads a chunk from one location into dst and returns how many
// bytes it read. It reports to progress what arrives, and stops when ctx ends.
// A failure comes with whether another location is worth asking.
type chunkAttempt func(ctx context.Context, url string, dst []byte, progress *chunkProgress) (n int, retryable bool, err error)
// ScratchBudget accounts for the buffers that hedged chunk reads borrow. A
// caller that bounds the memory of its chunk buffers passes one in the
// context with WithScratchBudget, and a hedge that does not fit is not sent.
type ScratchBudget interface {
// TryReserveScratch takes size bytes without waiting, or reports that
// they do not fit.
TryReserveScratch(size int) bool
// ReleaseScratch returns what TryReserveScratch took.
ReleaseScratch(size int)
}
type scratchBudgetKey struct{}
// WithScratchBudget makes the chunk reads under ctx account the buffers of
// their hedges to budget.
func WithScratchBudget(ctx context.Context, budget ScratchBudget) context.Context {
return context.WithValue(ctx, scratchBudgetKey{}, budget)
}
// ScratchBudgetFrom returns the budget WithScratchBudget put in ctx, or nil.
func ScratchBudgetFrom(ctx context.Context) ScratchBudget {
budget, _ := ctx.Value(scratchBudgetKey{}).(ScratchBudget)
return budget
}
// readHedges is what one chunk read has spent on hedges, across the passes of
// its retries.
type readHedges struct {
earned bool // the read has added its share to the hedge budget
sent int
}
type hedgedAttempt struct {
url string
dst []byte
scratch bool // dst is not the caller's buffer and is freed when the attempt ends
hedge bool // sent because the requests before it went quiet
cancel context.CancelFunc
started time.Time
progress chunkProgress
finished bool
abandoned bool
}
type attemptResult struct {
attempt *hedgedAttempt
n int
retryable bool
err error
}
// hedgedChunkPass makes one pass over urls for a chunk read into buffer.
//
// Like a plain loop over the locations it asks them in order and moves on to
// the next one as soon as one fails. Unlike it, it does not wait out a location
// that goes quiet: once every request in flight has been quiet for longer than
// it may be (chunkReadAnswerDelay before its response headers arrive,
// chunkReadStallDelay after), the read is asked of the next location as well.
// Once every location has been asked, a location whose server answered and
// then went quiet is asked again over another connection: the server is up,
// and only that connection is stuck. A location that has not answered is left
// alone then, as it was before. Whichever request delivers the whole chunk
// first wins, and the others are cancelled. hedging carries what the read has
// spent on hedges over to the passes of its retries.
//
// Only one request at a time reads into buffer; the others read into buffers
// of their own, accounted to the ScratchBudget in ctx if there is one, and a
// winner's data is copied over once the request reading into buffer has
// ended. buffer is not written after hedgedChunkPass returns.
//
// It returns the number of bytes read, whether a location failed or did not
// answer at all on the way, which says the caller's location list may be
// stale, and the error of the pass with whether it is worth another pass. A
// failure that another location would not fix stops the asking, though a
// request already in flight may still deliver the chunk. A hedge throttled by
// its server is not such a failure: that server is only busy.
func hedgedChunkPass(ctx context.Context, urls []string, buffer []byte, hedging *readHedges, attempt chunkAttempt) (n int, failed bool, retryable bool, err error) {
if len(urls) == 0 {
return 0, false, false, nil
}
if !hedging.earned {
earnHedgeToken()
hedging.earned = true
}
budget := ScratchBudgetFrom(ctx)
results := make(chan attemptResult, len(urls)+maxHedgesPerRead)
var (
attempts []*hedgedAttempt
owner *hedgedAttempt // the request reading into buffer
running int
next int // the next location not asked yet
hedgeOff bool // no budget or memory left for a hedge in this pass
stopAsking bool
finalErr error
throttled error // a hedge's server was too busy to serve it
)
// destination is where a new request reads: the caller's buffer when no
// other request reads into it, otherwise a buffer of its own, if the
// scratch budget has room for one.
destination := func() (dst []byte, scratch bool, ok bool) {
if owner == nil {
return buffer, false, true
}
if budget != nil && !budget.TryReserveScratch(len(buffer)) {
return nil, false, false
}
return mem.Allocate(len(buffer)), true, true
}
size := len(buffer)
freeScratch := func(dst []byte) {
mem.Free(dst)
if budget != nil {
budget.ReleaseScratch(size)
}
}
start := func(url string, dst []byte, scratch, hedge bool) {
a := &hedgedAttempt{url: url, dst: dst, scratch: scratch, hedge: hedge, started: time.Now()}
if !scratch {
owner = a
}
attemptCtx, cancel := context.WithCancel(ctx)
a.cancel = cancel
a.progress.arrived()
attempts = append(attempts, a)
running++
go func() {
m, r, e := attempt(attemptCtx, url, a.dst, &a.progress)
results <- attemptResult{attempt: a, n: m, retryable: r, err: e}
}()
}
// askNext asks the next location not asked yet, as the plain loop did
// after a failure. When the request reading into buffer is still running
// and there is no room for another buffer, its own failure asks it later.
askNext := func() {
if stopAsking || next >= len(urls) {
return
}
dst, scratch, ok := destination()
if !ok {
return
}
start(urls[next], dst, scratch, false)
next++
}
// settle takes in the result of a request that ended.
settle := func(r attemptResult) {
running--
r.attempt.finished = true
r.attempt.cancel()
if r.attempt == owner {
owner = nil
}
}
// end cancels the requests still running and waits for the one reading
// into buffer. The others release their buffers in the background.
end := func() {
for _, a := range attempts {
if !a.finished {
a.abandoned = true
a.cancel()
}
}
for owner != nil {
r := <-results
settle(r)
if r.attempt.scratch {
freeScratch(r.attempt.dst)
}
}
if running > 0 {
go func(left int) {
for ; left > 0; left-- {
if r := <-results; r.attempt.scratch {
freeScratch(r.attempt.dst)
}
}
}(running)
}
}
// hedgeAt is when every request in flight will have been quiet for longer
// than it may be, unless something arrives first.
hedgeAt := func() time.Time {
var at time.Time
for _, a := range attempts {
if a.finished {
continue
}
quietLimit := chunkReadAnswerDelay
if a.progress.answered.Load() {
quietLimit = chunkReadStallDelay
}
if t := time.Unix(0, a.progress.lastArrival.Load()).Add(quietLimit); t.After(at) {
at = t
}
}
return at
}
// stuckAnswered is the request that answered and has been quiet the
// longest, if any: its location is worth asking again.
stuckAnswered := func() *hedgedAttempt {
var pick *hedgedAttempt
for _, a := range attempts {
if !a.finished && a.progress.answered.Load() &&
(pick == nil || a.progress.lastArrival.Load() < pick.progress.lastArrival.Load()) {
pick = a
}
}
return pick
}
askNext()
timer := time.NewTimer(chunkReadAnswerDelay)
defer timer.Stop()
for running > 0 {
var hedge <-chan time.Time
if !stopAsking && !hedgeOff && hedging.sent < maxHedgesPerRead {
// A request that answers meanwhile may be quiet only for the
// shorter chunkReadStallDelay from then on: look again by then.
wait := chunkReadStallDelay
if next < len(urls) || stuckAnswered() != nil {
wait = min(time.Until(hedgeAt()), wait)
}
timer.Reset(max(wait, time.Millisecond))
hedge = timer.C
}
select {
case <-ctx.Done():
end()
return 0, failed, false, ctx.Err()
case <-hedge:
if time.Now().Before(hedgeAt()) {
continue // something arrived meanwhile
}
// a location not asked yet, or again one whose answer got stuck
var url string
unasked := next < len(urls)
if unasked {
url = urls[next]
} else if stuck := stuckAnswered(); stuck != nil {
url = stuck.url
} else {
continue // nowhere worth asking yet
}
// The token comes first: room for a buffer may evict cached
// chunks, which is only worth it for a hedge that is sent.
if !spendHedgeToken() {
hedgeOff = true
continue
}
dst, scratch, ok := destination()
if !ok {
refundHedgeToken()
hedgeOff = true // no room for another buffer
continue
}
if unasked {
next++
}
hedging.sent++
glog.V(1).InfofCtx(ctx, "chunk read went quiet, asking %s as well", url)
start(url, dst, scratch, true)
case r := <-results:
settle(r)
a := r.attempt
if a.abandoned {
if a.scratch {
freeScratch(a.dst)
}
continue
}
if ctxErr := ctx.Err(); ctxErr != nil {
if a.scratch {
freeScratch(a.dst)
}
end()
return 0, failed, false, ctxErr
}
if r.err == nil {
// The chunk is here. A location that has not even answered by
// now is tried last for a while, like one that cannot be
// reached, and the location list it came from may be stale.
// A request asked again where the server answered is only
// waiting for a connection.
answered := make(map[string]bool, len(attempts))
for _, other := range attempts {
if other.progress.answered.Load() {
answered[other.url] = true
}
}
for _, other := range attempts {
if !other.finished && !answered[other.url] && time.Since(other.started) >= chunkReadAnswerDelay {
recordUnreachable(hostOf(other.url), errNoAnswer)
failed = true
}
}
end()
if a.scratch {
copy(buffer, a.dst[:r.n])
freeScratch(a.dst)
}
return r.n, failed, false, nil
}
if a.scratch {
freeScratch(a.dst)
}
if !r.retryable {
if a.hedge && errors.Is(r.err, ErrTooManyRequests) {
// that server is busy; another location may still serve it
if throttled == nil {
throttled = r.err
}
askNext()
continue
}
if finalErr == nil {
finalErr = r.err
}
stopAsking = true
continue
}
failed = true
err, retryable = r.err, true
glog.V(0).InfofCtx(ctx, "read %s failed, err: %v", a.url, r.err)
askNext()
}
}
if finalErr != nil {
return 0, failed, false, finalErr
}
if err == nil && throttled != nil {
return 0, failed, false, throttled
}
return 0, failed, retryable, err
}