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
52 changes: 38 additions & 14 deletions internal/dao/downloader_dao.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,20 +79,7 @@ func (d *DownloaderDao) FileDownload(startPos, endPos int64, isInnerRequest bool
defer func() {
wg.Done()
}()
for i := 0; i < len(tasks); i++ {
if taskParam.Context.Err() != nil {
break
}
task := tasks[i]
if i == 0 {
select {
case task.GetResponseChan() <- []byte{}:
case <-taskParam.Context.Done():
return
}
}
task.OutResult()
}
drainOutputs(taskParam.Context, tasks, taskParam.Unordered)
}()
if len(tasks) > 0 {
wg.Add(1)
Expand Down Expand Up @@ -438,3 +425,40 @@ func peerFileURI(p *downloader.TaskParam) string {
q := url.Values{"repo": {p.RepoKey.Repo}, "revision": {p.Revision}, "path": {p.FileName}}
return "/api/repositories/" + url.PathEscape(p.RepoKey.RepoType) + "/" + url.PathEscape(p.RepoKey.Namespace) + "/file?" + q.Encode()
}

// drainOutputs moves every range task's output into the shared response channel.
//
// A client needs the file in byte order, so ranges are drained one after
// another. The cost is that a later range can buffer only
// download.remoteFileBufferSize before it blocks behind the ranges ahead of it,
// which serialises a split download back into roughly one stream per file.
// Consumers that ignore order (Unordered) drain every range concurrently so
// each range keeps its connection busy.
func drainOutputs(ctx context.Context, tasks []common.DownloadTask, unordered bool) {
if len(tasks) == 0 || ctx.Err() != nil {
return
}
select {
case tasks[0].GetResponseChan() <- []byte{}:
case <-ctx.Done():
return
}
if !unordered {
for _, task := range tasks {
if ctx.Err() != nil {
return
}
task.OutResult()
}
return
}
var wg sync.WaitGroup
for _, task := range tasks {
wg.Add(1)
go func(task common.DownloadTask) {
defer wg.Done()
task.OutResult()
}(task)
}
wg.Wait()
}
97 changes: 97 additions & 0 deletions internal/dao/drain_outputs_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// Copyright 2026 DataCanvas Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package dao

import (
"context"
"testing"
"time"

"dingospeed/pkg/common"
)

// fakeRange stands in for one range task. OutResult waits for hold (when set)
// before emitting, modelling an earlier range whose transfer is still running.
type fakeRange struct {
resp chan []byte
out string
hold chan struct{}
}

func (f *fakeRange) GetTaskNo() int { return 0 }
func (f *fakeRange) DoTask() {}
func (f *fakeRange) GetCancelFun() context.CancelFunc { return func() {} }
func (f *fakeRange) SetTaskSize(int) {}
func (f *fakeRange) GetResponseChan() chan []byte { return f.resp }
func (f *fakeRange) OutResult() {
if f.hold != nil {
<-f.hold
}
f.resp <- []byte(f.out)
}

func nextChunk(t *testing.T, ch chan []byte, within time.Duration) (string, bool) {
t.Helper()
select {
case b := <-ch:
return string(b), true
case <-time.After(within):
return "", false
}
}

// TestDrainOutputsUnorderedDoesNotWaitForEarlierRanges is why splitting a file
// into ranges only paid off for client downloads: drained in order, a later
// range blocks behind the earlier ones once its buffer fills, so a preheat that
// ignores order still moved about one stream per file.
func TestDrainOutputsUnorderedDoesNotWaitForEarlierRanges(t *testing.T) {
resp := make(chan []byte, 8)
hold := make(chan struct{})
tasks := []common.DownloadTask{&fakeRange{resp, "first", hold}, &fakeRange{resp, "second", nil}}

go drainOutputs(context.Background(), tasks, true)
if got, _ := nextChunk(t, resp, time.Second); got != "" {
t.Fatalf("expected the leading empty chunk, got %q", got)
}
if got, ok := nextChunk(t, resp, time.Second); !ok || got != "second" {
t.Fatalf("a later range must drain while an earlier one is still running, got %q ok=%v", got, ok)
}
close(hold)
if got, ok := nextChunk(t, resp, time.Second); !ok || got != "first" {
t.Fatalf("the held range must still be delivered, got %q ok=%v", got, ok)
}
}

// TestDrainOutputsOrderedKeepsFileOrder guards client downloads, which must see
// bytes in file order.
func TestDrainOutputsOrderedKeepsFileOrder(t *testing.T) {
resp := make(chan []byte, 8)
hold := make(chan struct{})
tasks := []common.DownloadTask{&fakeRange{resp, "first", hold}, &fakeRange{resp, "second", nil}}

go drainOutputs(context.Background(), tasks, false)
if got, _ := nextChunk(t, resp, time.Second); got != "" {
t.Fatalf("expected the leading empty chunk, got %q", got)
}
if got, ok := nextChunk(t, resp, 200*time.Millisecond); ok {
t.Fatalf("ordered drain delivered %q before the first range finished", got)
}
close(hold)
for _, want := range []string{"first", "second"} {
if got, ok := nextChunk(t, resp, time.Second); !ok || got != want {
t.Fatalf("want %q in order, got %q ok=%v", want, got, ok)
}
}
}
38 changes: 21 additions & 17 deletions internal/downloader/cache_task.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,23 +35,27 @@ type TaskParam struct {
CacheResult chan error // Optional buffered terminal result, sent after cache writes finish.
OnCacheComplete func()
Peer bool
Revision string
RepoKey repository.RepoKey
Context context.Context
DingFile *DingCache
TaskNo int
TaskSize int
BlobsFile string
FileName string
FileSize int64
ResponseChan chan []byte
OrgRepo string
Authorization string
Domain string
Uri string
DataType string
Etag string
Cancel context.CancelFunc
// Unordered lets range outputs reach ResponseChan as they arrive. Only for
// consumers that ignore byte order, such as a cache-only preheat that just
// counts bytes; client downloads must keep file order.
Unordered bool
Revision string
RepoKey repository.RepoKey
Context context.Context
DingFile *DingCache
TaskNo int
TaskSize int
BlobsFile string
FileName string
FileSize int64
ResponseChan chan []byte
OrgRepo string
Authorization string
Domain string
Uri string
DataType string
Etag string
Cancel context.CancelFunc
}

type DownloadTask struct {
Expand Down
6 changes: 5 additions & 1 deletion internal/service/task/preheat_cache_task.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"dingospeed/pkg/consts"
"dingospeed/pkg/hfprojection"
"dingospeed/pkg/repository"
"dingospeed/pkg/transfersettings"

"go.uber.org/zap"
"golang.org/x/sync/errgroup"
Expand Down Expand Up @@ -217,7 +218,9 @@ func (p *PreheatCacheTask) preheatProcess(orgRepo string) error {
}

func (p *PreheatCacheTask) startPreheat(hfUri, orgRepo, fileName, commit, etag, authorization string, fileSize, offset int64) error {
bgCtx := context.WithValue(p.Ctx, consts.PromSource, "localhost")
// Preheat is background work: it must leave transfer slots to interactive
// downloads, and it only counts bytes, so its ranges may complete out of order.
bgCtx := transfersettings.WithBackground(context.WithValue(p.Ctx, consts.PromSource, "localhost"))
responseChan := make(chan []byte, config.SysConfig.Download.RespChanSize)
blobsFile := dao.BlobPath(p.Job.Datatype, orgRepo, etag)
filesPath := dao.ResolvePath(p.Job.Datatype, orgRepo, commit, fileName)
Expand All @@ -239,6 +242,7 @@ func (p *PreheatCacheTask) startPreheat(hfUri, orgRepo, fileName, commit, etag,
DataType: p.Job.Datatype,
Etag: etag,
CacheResult: make(chan error, 1),
Unordered: true,
}
taskParam.Context = bgCtx
taskParam.ResponseChan = responseChan
Expand Down
92 changes: 92 additions & 0 deletions pkg/transfersettings/background_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Copyright 2026 DataCanvas Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package transfersettings

import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"

"dingospeed/pkg/config"
)

// TestBackgroundLeavesForegroundSlots pins the reservation that lets a preheat
// job raise its concurrency without starving interactive downloads.
//
// On hd-04 a preheat held every HuggingFace transfer slot and a user's
// download of a not-yet-cached file waited 150s behind it.
func TestBackgroundLeavesForegroundSlots(t *testing.T) {
old := config.SysConfig
t.Cleanup(func() { config.SysConfig = old })
config.SysConfig = &config.Config{Server: config.ServerConfig{Repos: t.TempDir()}}

release := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.(http.Flusher).Flush()
select {
case <-release:
case <-r.Context().Done():
}
}))
t.Cleanup(server.Close)
var open []*http.Response
t.Cleanup(func() {
close(release)
for _, r := range open {
_ = r.Body.Close()
}
})

limit := Current().HuggingFace
bgLimit := backgroundLimitFor(kindIndex("huggingface"))()
if bgLimit >= limit {
t.Fatalf("background limit %d leaves nothing of %d for foreground", bgLimit, limit)
}
get := func(ctx context.Context) (*http.Response, error) {
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, server.URL, nil)
return Do("huggingface", server.Client(), req)
}

for i := 0; i < bgLimit; i++ {
resp, err := get(WithBackground(context.Background()))
if err != nil {
t.Fatalf("background transfer %d of %d: %v", i+1, bgLimit, err)
}
open = append(open, resp)
}

// Control: background is capped, so one more must wait.
ctx, cancel := context.WithTimeout(WithBackground(context.Background()), 300*time.Millisecond)
defer cancel()
if resp, err := get(ctx); err == nil {
open = append(open, resp)
t.Fatalf("background exceeded its limit of %d", bgLimit)
}

for i := 0; i < limit-bgLimit; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
start := time.Now()
resp, err := get(ctx)
cancel()
if err != nil {
t.Fatalf("foreground transfer starved with background at its cap: %v", err)
}
open = append(open, resp)
t.Logf("foreground %d/%d admitted in %v with %d background transfers open", i+1, limit-bgLimit, time.Since(start), bgLimit)
}
}
Loading
Loading