|
| 1 | +package downloader_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/rand" |
| 6 | + "crypto/sha256" |
| 7 | + "fmt" |
| 8 | + "net/http" |
| 9 | + "net/http/httptest" |
| 10 | + "os" |
| 11 | + "path/filepath" |
| 12 | + "strconv" |
| 13 | + "strings" |
| 14 | + "sync" |
| 15 | + "time" |
| 16 | + |
| 17 | + . "github.com/onsi/ginkgo/v2" |
| 18 | + . "github.com/onsi/gomega" |
| 19 | + |
| 20 | + "github.com/mudler/LocalAI/pkg/downloader" |
| 21 | +) |
| 22 | + |
| 23 | +// flakyRangeServer serves payload, honours Range requests, and aborts the |
| 24 | +// connection part-way through the body for the first failUntil GET requests. |
| 25 | +// Aborting mid-body is how a peer-cancelled HTTP/2 stream or a dropped |
| 26 | +// connection presents to the client: the read fails, the write never does. |
| 27 | +func flakyRangeServer(payload []byte, failUntil int) (*httptest.Server, func() []string) { |
| 28 | + var mu sync.Mutex |
| 29 | + var seenRanges []string |
| 30 | + gets := 0 |
| 31 | + |
| 32 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 33 | + if r.Method == http.MethodHead { |
| 34 | + w.Header().Set("Accept-Ranges", "bytes") |
| 35 | + w.WriteHeader(http.StatusOK) |
| 36 | + return |
| 37 | + } |
| 38 | + |
| 39 | + rangeHeader := r.Header.Get("Range") |
| 40 | + mu.Lock() |
| 41 | + gets++ |
| 42 | + attempt := gets |
| 43 | + seenRanges = append(seenRanges, rangeHeader) |
| 44 | + mu.Unlock() |
| 45 | + |
| 46 | + start := 0 |
| 47 | + if strings.HasPrefix(rangeHeader, "bytes=") { |
| 48 | + n, err := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rangeHeader, "bytes="), "-")) |
| 49 | + Expect(err).ToNot(HaveOccurred()) |
| 50 | + start = n |
| 51 | + } |
| 52 | + body := payload[start:] |
| 53 | + |
| 54 | + w.Header().Set("Content-Length", strconv.Itoa(len(body))) |
| 55 | + if start > 0 { |
| 56 | + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, len(payload)-1, len(payload))) |
| 57 | + w.WriteHeader(http.StatusPartialContent) |
| 58 | + } else { |
| 59 | + w.WriteHeader(http.StatusOK) |
| 60 | + } |
| 61 | + |
| 62 | + if attempt <= failUntil { |
| 63 | + // Send a prefix, then kill the connection: the client's Read fails |
| 64 | + // with an unexpected EOF while the local file write succeeded. |
| 65 | + _, _ = w.Write(body[:len(body)/2]) |
| 66 | + if f, ok := w.(http.Flusher); ok { |
| 67 | + f.Flush() |
| 68 | + } |
| 69 | + panic(http.ErrAbortHandler) |
| 70 | + } |
| 71 | + _, _ = w.Write(body) |
| 72 | + })) |
| 73 | + |
| 74 | + return srv, func() []string { |
| 75 | + mu.Lock() |
| 76 | + defer mu.Unlock() |
| 77 | + return append([]string(nil), seenRanges...) |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +var _ = Describe("download failure diagnostics", func() { |
| 82 | + var ( |
| 83 | + payload []byte |
| 84 | + payloadSHA string |
| 85 | + destDir string |
| 86 | + destPath string |
| 87 | + noProgress = func(string, string, string, float64) {} |
| 88 | + ) |
| 89 | + |
| 90 | + BeforeEach(func() { |
| 91 | + payload = make([]byte, 65536) |
| 92 | + _, err := rand.Read(payload) |
| 93 | + Expect(err).ToNot(HaveOccurred()) |
| 94 | + sum := sha256.Sum256(payload) |
| 95 | + payloadSHA = fmt.Sprintf("%x", sum[:]) |
| 96 | + |
| 97 | + destDir = GinkgoT().TempDir() |
| 98 | + destPath = filepath.Join(destDir, "model.gguf") |
| 99 | + }) |
| 100 | + |
| 101 | + // Defect 1: io.Copy folds read and write failures into a single error, and |
| 102 | + // the download path labelled every one of them "failed to write file". |
| 103 | + // A peer-cancelled stream then reads as a filesystem problem, which is |
| 104 | + // exactly the wrong place to look. |
| 105 | + It("does not report a failed response read as a write failure", func() { |
| 106 | + server, _ := flakyRangeServer(payload, 1) |
| 107 | + DeferCleanup(server.Close) |
| 108 | + |
| 109 | + err := downloader.URI(server.URL).DownloadFile(destPath, payloadSHA, 1, 1, noProgress) |
| 110 | + Expect(err).To(HaveOccurred()) |
| 111 | + Expect(err.Error()).ToNot(ContainSubstring("failed to write file"), |
| 112 | + "the local write succeeded; only the response body read failed") |
| 113 | + Expect(err.Error()).To(ContainSubstring(server.URL), |
| 114 | + "a read-side failure should name the source it was reading from") |
| 115 | + }) |
| 116 | + |
| 117 | + // The partial, not the final blob path, is the file actually being written. |
| 118 | + It("names the partial file when the local write is the side that failed", func() { |
| 119 | + // A directory in place of the partial makes every write fail while the |
| 120 | + // response body stays healthy. |
| 121 | + Expect(os.MkdirAll(destPath+downloader.PartialFileSuffix, 0750)).To(Succeed()) |
| 122 | + |
| 123 | + server, _ := flakyRangeServer(payload, 0) |
| 124 | + DeferCleanup(server.Close) |
| 125 | + |
| 126 | + err := downloader.URI(server.URL).DownloadFile(destPath, payloadSHA, 1, 1, noProgress) |
| 127 | + Expect(err).To(HaveOccurred()) |
| 128 | + Expect(err.Error()).To(ContainSubstring(destPath + downloader.PartialFileSuffix)) |
| 129 | + }) |
| 130 | +}) |
| 131 | + |
| 132 | +var _ = Describe("DownloadFilesWithContext retries", func() { |
| 133 | + var ( |
| 134 | + payload []byte |
| 135 | + payloadSHA string |
| 136 | + destPath string |
| 137 | + ) |
| 138 | + |
| 139 | + BeforeEach(func() { |
| 140 | + payload = make([]byte, 65536) |
| 141 | + _, err := rand.Read(payload) |
| 142 | + Expect(err).ToNot(HaveOccurred()) |
| 143 | + sum := sha256.Sum256(payload) |
| 144 | + payloadSHA = fmt.Sprintf("%x", sum[:]) |
| 145 | + |
| 146 | + destPath = filepath.Join(GinkgoT().TempDir(), "model.gguf") |
| 147 | + |
| 148 | + original := downloader.DownloadRetryBaseDelay |
| 149 | + downloader.DownloadRetryBaseDelay = time.Millisecond |
| 150 | + DeferCleanup(func() { downloader.DownloadRetryBaseDelay = original }) |
| 151 | + }) |
| 152 | + |
| 153 | + // Defect 2: one cancelled stream half-way through a multi-file plan threw |
| 154 | + // away every file already fetched. The .partial resume machinery existed |
| 155 | + // but nothing retried, so it was unreachable. |
| 156 | + It("retries a transient stream failure and resumes from the partial", func() { |
| 157 | + server, ranges := flakyRangeServer(payload, 2) |
| 158 | + DeferCleanup(server.Close) |
| 159 | + |
| 160 | + err := downloader.DownloadFilesWithContext(context.Background(), []downloader.FileTask{{ |
| 161 | + URI: downloader.URI(server.URL), |
| 162 | + Destination: destPath, |
| 163 | + SHA256: payloadSHA, |
| 164 | + FileIndex: 1, |
| 165 | + TotalFiles: 1, |
| 166 | + }}, nil) |
| 167 | + Expect(err).ToNot(HaveOccurred()) |
| 168 | + |
| 169 | + got, err := os.ReadFile(destPath) |
| 170 | + Expect(err).ToNot(HaveOccurred()) |
| 171 | + Expect(got).To(Equal(payload)) |
| 172 | + |
| 173 | + seen := ranges() |
| 174 | + Expect(seen).To(HaveLen(3), "expected two failed attempts and one success, got %v", seen) |
| 175 | + Expect(seen[0]).To(BeEmpty()) |
| 176 | + for _, r := range seen[1:] { |
| 177 | + Expect(r).To(HavePrefix("bytes="), "retries must resume, not restart: %v", seen) |
| 178 | + Expect(r).ToNot(Equal("bytes=0-"), "retries must resume, not restart: %v", seen) |
| 179 | + } |
| 180 | + }) |
| 181 | + |
| 182 | + It("does not retry a permanent failure", func() { |
| 183 | + attempts := 0 |
| 184 | + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 185 | + attempts++ |
| 186 | + w.WriteHeader(http.StatusNotFound) |
| 187 | + })) |
| 188 | + DeferCleanup(server.Close) |
| 189 | + |
| 190 | + err := downloader.DownloadFilesWithContext(context.Background(), []downloader.FileTask{{ |
| 191 | + URI: downloader.URI(server.URL), |
| 192 | + Destination: destPath, |
| 193 | + FileIndex: 1, |
| 194 | + TotalFiles: 1, |
| 195 | + }}, nil) |
| 196 | + Expect(err).To(HaveOccurred()) |
| 197 | + Expect(attempts).To(Equal(1), "a 404 is permanent and must not be retried") |
| 198 | + }) |
| 199 | + |
| 200 | + It("does not retry once the caller's context is cancelled", func() { |
| 201 | + ctx, cancel := context.WithCancel(context.Background()) |
| 202 | + attempts := 0 |
| 203 | + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 204 | + if r.Method == http.MethodHead { |
| 205 | + w.Header().Set("Accept-Ranges", "bytes") |
| 206 | + w.WriteHeader(http.StatusOK) |
| 207 | + return |
| 208 | + } |
| 209 | + attempts++ |
| 210 | + cancel() |
| 211 | + w.Header().Set("Content-Length", strconv.Itoa(len(payload))) |
| 212 | + w.WriteHeader(http.StatusOK) |
| 213 | + _, _ = w.Write(payload[:len(payload)/2]) |
| 214 | + if f, ok := w.(http.Flusher); ok { |
| 215 | + f.Flush() |
| 216 | + } |
| 217 | + panic(http.ErrAbortHandler) |
| 218 | + })) |
| 219 | + DeferCleanup(server.Close) |
| 220 | + |
| 221 | + err := downloader.DownloadFilesWithContext(ctx, []downloader.FileTask{{ |
| 222 | + URI: downloader.URI(server.URL), |
| 223 | + Destination: destPath, |
| 224 | + SHA256: payloadSHA, |
| 225 | + FileIndex: 1, |
| 226 | + TotalFiles: 1, |
| 227 | + }}, nil) |
| 228 | + Expect(err).To(HaveOccurred()) |
| 229 | + Expect(attempts).To(Equal(1), "a cancelled caller must not be retried through") |
| 230 | + }) |
| 231 | +}) |
0 commit comments