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
5 changes: 5 additions & 0 deletions internal/service/cache_job_failed_retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ func TestModelScopeFailedTaskRetriesPinnedCache(t *testing.T) {
defer release()
msConfig(t, upstream.URL)
config.SysConfig.Download.RemoteFileRangeSize = 0
// This test drives the failed -> manual resume path; keep the job from
// recovering on its own first.
oldBackoff := task.PreheatRetryBackoff
task.PreheatRetryBackoff = nil
defer func() { task.PreheatRetryBackoff = oldBackoff }()
key := repository.RepoKey{Namespace: repository.ModelScope, RepoType: "models", Repo: "owner/model"}
provider := NewModelscopeService()
e := echo.New()
Expand Down
52 changes: 50 additions & 2 deletions internal/service/task/preheat_cache_task.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"math"
"net/http"
"sync"
"sync/atomic"
"time"
Expand All @@ -14,6 +15,7 @@ import (
"dingospeed/internal/model/query"
"dingospeed/pkg/config"
"dingospeed/pkg/consts"
myerr "dingospeed/pkg/error"
"dingospeed/pkg/hfprojection"
"dingospeed/pkg/repository"
"dingospeed/pkg/transfersettings"
Expand Down Expand Up @@ -96,7 +98,7 @@ func (p *PreheatCacheTask) DoTask() {
defer close(progressDone)
p.realTimeSpeed(ctx)
}()
err = p.preheatProcess(orgRepo)
err = p.preheatWithRetry(orgRepo)
// Stop sampling before recording the terminal progress; a late tick must
// not overwrite 100% with the last in-flight percentage.
cancelFunc()
Expand Down Expand Up @@ -126,6 +128,49 @@ func (p *PreheatCacheTask) DoTask() {
p.SchedulerDao.ExecUpdateCacheJobStatus(p.TaskNo, consts.RunningStatusJobComplete, p.Job.InstanceId, p.Job.Namespace, p.Job.Repo, "", p.StockProcess)
}

// PreheatRetryBackoff spaces out reruns of a failed manifest; empty disables
// retries. Preheat jobs run for hours through shared exits: one dropped
// connection or metadata timeout used to fail a 1.7 TB job at 87%. A rerun
// skips completed files and resumes partial ones from their cached offset, so
// retrying is cheap.
var PreheatRetryBackoff = []time.Duration{30 * time.Second, time.Minute, 2 * time.Minute, 5 * time.Minute,
10 * time.Minute, 10 * time.Minute, 10 * time.Minute, 10 * time.Minute}

func (p *PreheatCacheTask) preheatWithRetry(orgRepo string) error {
for attempt := 0; ; attempt++ {
err := p.preheatProcess(orgRepo)
if err == nil || attempt >= len(PreheatRetryBackoff) || !retryablePreheatError(p.Ctx, err) {
return err
}
zap.S().Warnf("preheat job %d (%s) failed, retry %d/%d in %s: %v",
p.TaskNo, orgRepo, attempt+1, len(PreheatRetryBackoff), PreheatRetryBackoff[attempt], err)
select {
case <-p.Ctx.Done():
return err
case <-time.After(PreheatRetryBackoff[attempt]):
}
// The rerun counts cached offsets again as it walks the manifest.
p.stockLen.Store(0)
}
}

// retryablePreheatError reports whether a failed manifest is worth rerunning:
// not when the job itself was stopped, canceled or shut down, and not when the
// upstream refused or lacks the repository.
func retryablePreheatError(jobCtx context.Context, err error) bool {
if jobCtx.Err() != nil {
return false
}
var appErr myerr.Error
if errors.As(err, &appErr) {
switch appErr.StatusCode() {
case http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound:
return false
}
}
return true
}

// preheatFileConcurrency bounds how many files a preheat job transfers at once.
// Eight pairs with the default download.goroutineMaxNumPerFile of 8 for 64
// connections in flight, which is where measured upstream throughput plateaus.
Expand Down Expand Up @@ -271,7 +316,10 @@ func (p *PreheatCacheTask) realTimeSpeed(ctx context.Context) {
select {
case <-ticker.C:
currentBytes := p.stockLen.Load()
delta := currentBytes - lastBytes
delta := uint64(0)
if currentBytes > lastBytes { // a retry restarts the count
delta = currentBytes - lastBytes
}
p.progressMu.Lock()
p.StockSpeed = formatSpeed(delta, 1*time.Second) // 采样间隔 1 秒
// 计算下载进度(百分比)
Expand Down
80 changes: 80 additions & 0 deletions internal/service/task/preheat_retry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package task

import (
"context"
"errors"
"io"
"net/http"
"sync/atomic"
"testing"
"time"

myerr "dingospeed/pkg/error"
)

func fastPreheatRetries(t *testing.T, n int) {
t.Helper()
old := PreheatRetryBackoff
t.Cleanup(func() { PreheatRetryBackoff = old })
PreheatRetryBackoff = make([]time.Duration, n)
for i := range PreheatRetryBackoff {
PreheatRetryBackoff[i] = time.Millisecond
}
}

// 2026-10-13: a burst of dropped connections failed a 1.7 TB job at 87% and a
// single metadata timeout failed CulturaX; both only needed another pass.
func TestPreheatRetriesTransientFailures(t *testing.T) {
fastPreheatRetries(t, 3)
p := preheatFixture(t, 3)
var calls, failures atomic.Int32
p.transfer = func(_, _, fileName, _, _, _ string, _, _ int64) error {
calls.Add(1)
if fileName == "shard-01.bin" && failures.Add(1) <= 2 {
return io.ErrUnexpectedEOF
}
return nil
}
if err := p.preheatWithRetry("huggingface/owner/model"); err != nil {
t.Fatalf("transient failures not retried: %v", err)
}
if failures.Load() != 3 {
t.Fatalf("failing file attempted %d times, want 3", failures.Load())
}
}

func TestPreheatRetryGivesUp(t *testing.T) {
cases := map[string]struct {
err error
attempts int32
cancel bool
}{
"exhausted": {io.ErrUnexpectedEOF, 3, false},
"forbidden": {myerr.NewAppendCode(http.StatusForbidden, "gated"), 1, false},
"not found": {myerr.WrapCode(http.StatusNotFound, "gone", errors.New("404")), 1, false},
"job stopped": {io.ErrUnexpectedEOF, 1, true},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
fastPreheatRetries(t, 2)
p := preheatFixture(t, 1)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
p.Ctx = ctx
var calls atomic.Int32
p.transfer = func(_, _, _, _, _, _ string, _, _ int64) error {
calls.Add(1)
if c.cancel {
cancel()
}
return c.err
}
if err := p.preheatWithRetry("huggingface/owner/model"); err == nil {
t.Fatal("failure swallowed")
}
if calls.Load() != c.attempts {
t.Fatalf("attempted %d times, want %d", calls.Load(), c.attempts)
}
})
}
}
Loading