ronantakizawa/codereview-bench huggingface dataset:
Repository: ollama/ollama
File: server/routes.go (Go)

Code before:
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
			return
		}
		defer f.Close()

		sr = f
	}

	f, err := parser.ParseFile(sr)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	ch := make(chan any)
	go func() {
		defer close(ch)
		fn := func(resp api.ProgressResponse) {
			ch <- resp
		}

		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

		quantization := cmp.Or(r.Quantize, r.Quantization)
		if err := CreateModel(ctx, name, filepath.Dir(r.Path), strings.ToUpper(quantization), f, fn); errors.Is(err, errBadTemplate) {
			ch <- gin.H{"error": err.Error(), "status": http.StatusBadRequest}
		} else if err != nil {
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if r.Stream != nil && !*r.Stream {
		waitForStream(c, ch)
		return
	}

	streamResponse(c, ch)
}

func (s *Server) DeleteModelHandler(c *gin.Context) {
	var r api.DeleteRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	} else if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	n := model.ParseName(cmp.Or(r.Model, r.Name))

Review comment (suggestion):
I would make this a condition in `err != nil` for clarity:

```
if err := CreateModel(ctx, name, filepath.Dir(r.Path), strings.ToUpper(quantization), f, fn); err != nil {
  if errors.Is(err, errBadTemplate) {
    ch <- gin.H{"error": err.Error(), "status": http.StatusBadRequest}
  }
  ch <- gin.H{"error": err.Error()}
}
```

Code after:
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
			return
		}
		defer f.Close()

		sr = f
	}

	f, err := parser.ParseFile(sr)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	ch := make(chan any)
	go func() {
		defer close(ch)
		fn := func(resp api.ProgressResponse) {
			ch <- resp
		}

		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

		quantization := cmp.Or(r.Quantize, r.Quantization)
		if err := CreateModel(ctx, name, filepath.Dir(r.Path), strings.ToUpper(quantization), f, fn); err != nil {
			if errors.Is(err, errBadTemplate) {
			  ch <- gin.H{"error": err.Error(), "status": http.StatusBadRequest}
			}
			ch <- gin.H{"error": err.Error()}
		  }
	}()

	if r.Stream != nil && !*r.Stream {
		waitForStream(c, ch)
		return
	}

	streamResponse(c, ch)
}

func (s *Server) DeleteModelHandler(c *gin.Context) {
	var r api.DeleteRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	} else if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
Repository: ollama/ollama
File: server/model.go (Go)

Code before:
	var objs []map[string]any
	for offset := 0; offset < len(s); {
		var obj map[string]any
		decoder := json.NewDecoder(strings.NewReader(s[offset:]))
		if err := decoder.Decode(&obj); errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
			break
		} else if syntax := &(json.SyntaxError{}); errors.As(err, &syntax) {
			// skip over any syntax errors
			offset += int(syntax.Offset)
		} else if unmarshalType := &(json.UnmarshalTypeError{}); errors.As(err, &unmarshalType) {
			// skip over any unmarshalable types
			offset += int(unmarshalType.Offset)
		} else if err != nil {
			slog.Error("parseToolCalls", "error", err)
			return nil, false
		} else {
			offset += int(decoder.InputOffset())
			objs = append(objs, collect(obj)...)
		}
	}

	var toolCalls []api.ToolCall
	for _, kv := range objs {
		n, nameOk := kv[name].(string)
		a, argumentsOk := kv[arguments].(map[string]any)
		if nameOk && argumentsOk {
			call := api.ToolCall{
				Function: api.ToolCallFunction{
					Name:      n,
					Arguments: a,
				},
			}
			toolCalls = append(toolCalls, call)
		}
	}

	return toolCalls, len(toolCalls) > 0
}


Review comment (suggestion):
AFAIK `arguments` is not optional, so this checks for both in the returned tool call to avoid false positives

Code after:
			// collect all nested objects
			var collect func(any) []map[string]any
			collect = func(obj any) (all []map[string]any) {
				switch o := obj.(type) {
				case map[string]any:
					all = append(all, o)
					for _, v := range o {
						all = append(all, collect(v)...)
					}
				case []any:
					for _, v := range o {
						all = append(all, collect(v)...)
					}
				}

				return all
			}
			objs = append(objs, collect(obj)...)
		}
	}

	var toolCalls []api.ToolCall
	for _, kv := range objs {
		n, nok := kv[name].(string)
		a, aok := kv[arguments].(map[string]any)
		if nok && aok {
			toolCalls = append(toolCalls, api.ToolCall{
				Function: api.ToolCallFunction{
					Name:      n,
					Arguments: a,
				},
			})
		}
	}

	return toolCalls, len(toolCalls) > 0
}
Repository: ollama/ollama
File: server/model.go (Go)

Code before:
				layers = append(layers, &layerGGML{tmpl, nil})
			}
		}
	}

	return layers, nil
}

func detectContentType(r io.Reader) (string, error) {
	var b bytes.Buffer
	if _, err := io.Copy(&b, r); err != nil {
		return "", err
	}

	if contentType := llm.DetectGGMLType(b.Bytes()); contentType != "" {
		return contentType, nil
	}

	if contentType := http.DetectContentType(b.Bytes()); contentType != "application/octet-stream" {
		return contentType, nil
	}

	return "unknown", nil
}

func collect(obj any) []map[string]any {
	var result []map[string]any

	switch o := obj.(type) {
	case map[string]any:
		result = append(result, o)
		for _, v := range o {
			result = append(result, collect(v)...)
		}
	case []any:
		for _, v := range o {
			result = append(result, collect(v)...)
		}
	}

	return result
}

// parseToolCalls attempts to parse a JSON string into a slice of ToolCalls.
// mxyng: this only really works if the input contains tool calls in some JSON format
func (m *Model) parseToolCalls(s string) ([]api.ToolCall, bool) {
	// create a subtree from the node that ranges over .ToolCalls
	tmpl := m.Template.Subtree(func(n parse.Node) bool {
		if t, ok := n.(*parse.RangeNode); ok {
			return slices.Contains(template.Identifiers(t.Pipe), "ToolCalls")
		}

Review comment (suggestion):
nit

```suggestion
func collect(obj any) (result []map[string]any) {
```

Code after:
				layers = append(layers, &layerGGML{tmpl, nil})
			}
		}
	}

	return layers, nil
}

func detectContentType(r io.Reader) (string, error) {
	var b bytes.Buffer
	if _, err := io.Copy(&b, r); err != nil {
		return "", err
	}

	if contentType := llm.DetectGGMLType(b.Bytes()); contentType != "" {
		return contentType, nil
	}

	if contentType := http.DetectContentType(b.Bytes()); contentType != "application/octet-stream" {
		return contentType, nil
	}

	return "unknown", nil
}

// parseToolCalls attempts to parse a JSON string into a slice of ToolCalls.
// mxyng: this only really works if the input contains tool calls in some JSON format
func (m *Model) parseToolCalls(s string) ([]api.ToolCall, bool) {
	// create a subtree from the node that ranges over .ToolCalls
	tmpl := m.Template.Subtree(func(n parse.Node) bool {
		if t, ok := n.(*parse.RangeNode); ok {
			return slices.Contains(template.Identifiers(t.Pipe), "ToolCalls")
		}

		return false
	})

	if tmpl == nil {
		return nil, false
	}

	var b bytes.Buffer
	if err := tmpl.Execute(&b, map[string][]api.ToolCall{
		"ToolCalls": {
			{
				Function: api.ToolCallFunction{
					Name: "@@name@@",
					Arguments: api.ToolCallFunctionArguments{
						"@@argument@@": 1,
					},
				},
Repository: ollama/ollama
File: server/model.go (Go)

Code before:
			// skip over any syntax errors
			offset += int(syntax.Offset)
		} else if unmarshalType := &(json.UnmarshalTypeError{}); errors.As(err, &unmarshalType) {
			// skip over any unmarshalable types
			offset += int(unmarshalType.Offset)
		} else if err != nil {
			slog.Error("parseToolCalls", "error", err)
			return nil, false
		} else {
			offset += int(decoder.InputOffset())
			objs = append(objs, collect(obj)...)
		}
	}

	var toolCalls []api.ToolCall
	for _, kv := range objs {
		n, nameOk := kv[name].(string)
		a, argumentsOk := kv[arguments].(map[string]any)
		if nameOk && argumentsOk {
			call := api.ToolCall{
				Function: api.ToolCallFunction{
					Name:      n,
					Arguments: a,
				},
			}
			toolCalls = append(toolCalls, call)
		}
	}

	return toolCalls, len(toolCalls) > 0
}


Review comment (suggestion):
```suggestion
			toolCalls = append(toolCalls, api.ToolCall{
				Function: api.ToolCallFunction{
					Name: n,
					Arguments: a,
				},
			})
```

Code after:
						all = append(all, collect(v)...)
					}
				case []any:
					for _, v := range o {
						all = append(all, collect(v)...)
					}
				}

				return all
			}
			objs = append(objs, collect(obj)...)
		}
	}

	var toolCalls []api.ToolCall
	for _, kv := range objs {
		n, nok := kv[name].(string)
		a, aok := kv[arguments].(map[string]any)
		if nok && aok {
			toolCalls = append(toolCalls, api.ToolCall{
				Function: api.ToolCallFunction{
					Name:      n,
					Arguments: a,
				},
			})
		}
	}

	return toolCalls, len(toolCalls) > 0
}
Repository: ollama/ollama
File: server/model.go (Go)

Code before:
			arguments = k
		}
	}

	if name == "" || arguments == "" {
		return nil, false
	}

	var objs []map[string]any
	for offset := 0; offset < len(s); {
		var obj map[string]any
		decoder := json.NewDecoder(strings.NewReader(s[offset:]))
		if err := decoder.Decode(&obj); errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
			break
		} else if syntax := &(json.SyntaxError{}); errors.As(err, &syntax) {
			// skip over any syntax errors
			offset += int(syntax.Offset)
		} else if unmarshalType := &(json.UnmarshalTypeError{}); errors.As(err, &unmarshalType) {
			// skip over any unmarshalable types
			offset += int(unmarshalType.Offset)
		} else if err != nil {
			slog.Error("parseToolCalls", "error", err)
			return nil, false
		} else {
			offset += int(decoder.InputOffset())
			objs = append(objs, collect(obj)...)
		}
	}

	var toolCalls []api.ToolCall
	for _, kv := range objs {
		n, nameOk := kv[name].(string)
		a, argumentsOk := kv[arguments].(map[string]any)
		if nameOk && argumentsOk {
			call := api.ToolCall{
				Function: api.ToolCallFunction{
					Name:      n,
					Arguments: a,
				},
			}
			toolCalls = append(toolCalls, call)
		}
	}

	return toolCalls, len(toolCalls) > 0
}


Review comment (suggestion):
For readability and to keep the function defined close to where it's being used, it would be better to define a (named) anonymous function

```go
			var collect func(any) []map[string]any
			collect = func(obj any) (result []map[string]any {
			}

			objs = append(objs, collect(obj)...)
```

Code after:
			// skip over any unmarshalable types
			offset += int(unmarshalType.Offset)
		} else if err != nil {
			slog.Error("parseToolCalls", "error", err)
			return nil, false
		} else {
			offset += int(decoder.InputOffset())

			// collect all nested objects
			var collect func(any) []map[string]any
			collect = func(obj any) (all []map[string]any) {
				switch o := obj.(type) {
				case map[string]any:
					all = append(all, o)
					for _, v := range o {
						all = append(all, collect(v)...)
					}
				case []any:
					for _, v := range o {
						all = append(all, collect(v)...)
					}
				}

				return all
			}
			objs = append(objs, collect(obj)...)
		}
	}

	var toolCalls []api.ToolCall
	for _, kv := range objs {
		n, nok := kv[name].(string)
		a, aok := kv[arguments].(map[string]any)
		if nok && aok {
			toolCalls = append(toolCalls, api.ToolCall{
				Function: api.ToolCallFunction{
					Name:      n,
					Arguments: a,
				},
			})
		}
	}

	return toolCalls, len(toolCalls) > 0
}
Repository: ollama/ollama
File: server/model.go (Go)

Code before:
		return nil, err
	}

	var offset int64
	for offset < stat.Size() {
		ggml, n, err := llm.DecodeGGML(file, 0)
		if errors.Is(err, io.EOF) {
			break
		} else if err != nil {
			return nil, err
		}

		mediatype := "application/vnd.ollama.image.model"
		if ggml.Name() == "ggla" {
			mediatype = "application/vnd.ollama.image.adapter"
		} else if ggml.KV().Architecture() == "clip" {
			mediatype = "application/vnd.ollama.image.projector"
		}

		var layer *Layer
		if digest != "" && n == stat.Size() && offset == 0 {
			layer, err = NewLayerFromLayer(digest, mediatype, file.Name())
		} 
		if err != nil {
			layer = nil
			slog.Warn(fmt.Sprintf("NewLayerFromLayer failed: %v", err))
		}

		// Fallback to creating layer from file copy (either NewLayerFromLayer failed, or digest empty/n != stat.Size())
		if layer == nil {
			layer, err = NewLayer(io.NewSectionReader(file, offset, n), mediatype)
		}
		if err != nil {
			return nil, err
		}

		layers = append(layers, &layerGGML{layer, ggml})
		offset = n
	}

	return detectChatTemplate(layers)
}

func detectChatTemplate(layers []*layerGGML) ([]*layerGGML, error) {
	for _, layer := range layers {
		if s := layer.GGML.KV().ChatTemplate(); s != "" {
			if t, err := template.Named(s); err != nil {
				slog.Debug("template detection", "error", err)
			} else {
				tmpl, err := NewLayer(t.Reader(), "application/vnd.ollama.image.template")
				if err != nil {

Review comment (bug):
```suggestion
			slog.Debug("could not create new layer from layer", "error", err))
```

Code after:
			}
		}
	}

	return layers, nil
}

func detectContentType(r io.Reader) (string, error) {
	var b bytes.Buffer
	if _, err := io.Copy(&b, r); err != nil {
		return "", err
	}

	if contentType := llm.DetectGGMLType(b.Bytes()); contentType != "" {
		return contentType, nil
	}

	if contentType := http.DetectContentType(b.Bytes()); contentType != "application/octet-stream" {
		return contentType, nil
	}

	return "unknown", nil
}

// parseToolCalls attempts to parse a JSON string into a slice of ToolCalls.
// mxyng: this only really works if the input contains tool calls in some JSON format
func (m *Model) parseToolCalls(s string) ([]api.ToolCall, bool) {
	// create a subtree from the node that ranges over .ToolCalls
	tmpl := m.Template.Subtree(func(n parse.Node) bool {
		if t, ok := n.(*parse.RangeNode); ok {
			return slices.Contains(template.Identifiers(t.Pipe), "ToolCalls")
		}

		return false
	})

	if tmpl == nil {
		return nil, false
	}

	var b bytes.Buffer
	if err := tmpl.Execute(&b, map[string][]api.ToolCall{
		"ToolCalls": {
			{
				Function: api.ToolCallFunction{
					Name: "@@name@@",
					Arguments: api.ToolCallFunctionArguments{
						"@@argument@@": 1,
					},
				},
			},
Repository: ollama/ollama
File: server/model_test.go (Go)

Code before:
				}
			})

			t.Run("parse", func(t *testing.T) {
				m := &Model{Template: tmpl}
				actual, ok := m.parseToolCalls(tt.output)
				if ok != tt.ok {
					t.Fatalf("expected %t, got %t", tt.ok, ok)
				}

				if tt.ok {
					if diff := cmp.Diff(actual, calls); diff != "" {
						t.Errorf("mismatch (-got +want):\n%s", diff)
					}
				}
			})
		})
	}
}

func TestParseFromFileFromLayer(t *testing.T) {
	tempModels := t.TempDir()
	t.Setenv("OLLAMA_MODELS", tempModels)
	digest := "sha256-fb9d435dc2c4fe681ce63917c062c91022524e9ce57474c9b10ef5169495d902"

	if _, err := GetBlobsPath(digest); err != nil {
		t.Fatalf("failed to get blobs path: %v", err)
	}

	file, err := os.CreateTemp(tempModels+"/blobs", digest)
	if err != nil {
		t.Fatalf("failed to open file: %v", err)
	}
	defer file.Close()
	if err := llm.WriteGGUF(file, llm.KV{"general.architecture": "gemma"}, []llm.Tensor{}); err != nil {
		t.Fatalf("failed to write gguf: %v", err)
	}

	if _, err := file.Seek(0, io.SeekStart); err != nil {
		t.Fatalf("failed to seek to start: %v", err)
	}

	layers, err := parseFromFile(context.Background(), file, digest, func(api.ProgressResponse) {})
	if err != nil {
		t.Fatalf("failed to parse from file: %v", err)
	}

	if len(layers) != 1 {
		t.Fatalf("got %d != want 1", len(layers))
	}


Review comment (suggestion):
There's no reason to check this. I don't think this does what you think it does. `GetBlobsPath` only resolves a digest to a path but doesn't check if the blob itself exists.

Code after:
				}
			})

			t.Run("parse", func(t *testing.T) {
				m := &Model{Template: tmpl}
				actual, ok := m.parseToolCalls(tt.output)
				if ok != tt.ok {
					t.Fatalf("expected %t, got %t", tt.ok, ok)
				}

				if tt.ok {
					if diff := cmp.Diff(actual, calls); diff != "" {
						t.Errorf("mismatch (-got +want):\n%s", diff)
					}
				}
			})
		})
	}
}

func TestParseFromFileFromLayer(t *testing.T) {
	tempModels := t.TempDir()

	file, err := os.CreateTemp(tempModels, "")
	if err != nil {
		t.Fatalf("failed to open file: %v", err)
	}
	defer file.Close()
	if err := llm.WriteGGUF(file, llm.KV{"general.architecture": "gemma"}, []llm.Tensor{}); err != nil {
		t.Fatalf("failed to write gguf: %v", err)
	}

	if _, err := file.Seek(0, io.SeekStart); err != nil {
		t.Fatalf("failed to seek to start: %v", err)
	}

	layers, err := parseFromFile(context.Background(), file, "", func(api.ProgressResponse) {})
	if err != nil {
		t.Fatalf("failed to parse from file: %v", err)
	}

	if len(layers) != 1 {
		t.Fatalf("got %d != want 1", len(layers))
	}

	if _, err := file.Seek(0, io.SeekStart); err != nil {
		t.Fatalf("failed to seek to start: %v", err)
	}

	layers2, err := parseFromFile(context.Background(), file, layers[0].Digest, func(api.ProgressResponse) {})
	if err != nil {
Repository: ollama/ollama
File: server/model_test.go (Go)

Code before:
				m := &Model{Template: tmpl}
				actual, ok := m.parseToolCalls(tt.output)
				if ok != tt.ok {
					t.Fatalf("expected %t, got %t", tt.ok, ok)
				}

				if tt.ok {
					if diff := cmp.Diff(actual, calls); diff != "" {
						t.Errorf("mismatch (-got +want):\n%s", diff)
					}
				}
			})
		})
	}
}

func TestParseFromFileFromLayer(t *testing.T) {
	tempModels := t.TempDir()
	t.Setenv("OLLAMA_MODELS", tempModels)
	digest := "sha256-fb9d435dc2c4fe681ce63917c062c91022524e9ce57474c9b10ef5169495d902"

	if _, err := GetBlobsPath(digest); err != nil {
		t.Fatalf("failed to get blobs path: %v", err)
	}

	file, err := os.CreateTemp(tempModels+"/blobs", digest)
	if err != nil {
		t.Fatalf("failed to open file: %v", err)
	}
	defer file.Close()
	if err := llm.WriteGGUF(file, llm.KV{"general.architecture": "gemma"}, []llm.Tensor{}); err != nil {
		t.Fatalf("failed to write gguf: %v", err)
	}

	if _, err := file.Seek(0, io.SeekStart); err != nil {
		t.Fatalf("failed to seek to start: %v", err)
	}

	layers, err := parseFromFile(context.Background(), file, digest, func(api.ProgressResponse) {})
	if err != nil {
		t.Fatalf("failed to parse from file: %v", err)
	}

	if len(layers) != 1 {
		t.Fatalf("got %d != want 1", len(layers))
	}

	t.Run("2x gguf", func(t *testing.T) {
		digest := "sha256-fb9d435dc2c4fe681ce63917c062c91022524e9ce57474c9b10ef5169495d903"

		if _, err := GetBlobsPath(digest); err != nil {

Review comment (suggestion):
Similarly, this doesn't create a file with path `{tempModels}/blobs/{digest}`. It create a temporary file in `{tempModels}/blobs` with a prefix of `digest`

Code after:
				m := &Model{Template: tmpl}
				actual, ok := m.parseToolCalls(tt.output)
				if ok != tt.ok {
					t.Fatalf("expected %t, got %t", tt.ok, ok)
				}

				if tt.ok {
					if diff := cmp.Diff(actual, calls); diff != "" {
						t.Errorf("mismatch (-got +want):\n%s", diff)
					}
				}
			})
		})
	}
}

func TestParseFromFileFromLayer(t *testing.T) {
	tempModels := t.TempDir()

	file, err := os.CreateTemp(tempModels, "")
	if err != nil {
		t.Fatalf("failed to open file: %v", err)
	}
	defer file.Close()
	if err := llm.WriteGGUF(file, llm.KV{"general.architecture": "gemma"}, []llm.Tensor{}); err != nil {
		t.Fatalf("failed to write gguf: %v", err)
	}

	if _, err := file.Seek(0, io.SeekStart); err != nil {
		t.Fatalf("failed to seek to start: %v", err)
	}

	layers, err := parseFromFile(context.Background(), file, "", func(api.ProgressResponse) {})
	if err != nil {
		t.Fatalf("failed to parse from file: %v", err)
	}

	if len(layers) != 1 {
		t.Fatalf("got %d != want 1", len(layers))
	}

	if _, err := file.Seek(0, io.SeekStart); err != nil {
		t.Fatalf("failed to seek to start: %v", err)
	}

	layers2, err := parseFromFile(context.Background(), file, layers[0].Digest, func(api.ProgressResponse) {})
	if err != nil {
		t.Fatalf("failed to parse from file: %v", err)
	}
	if len(layers2) != 1 {
		t.Fatalf("got %d != want 1", len(layers2))
Repository: ollama/ollama
File: server/download.go (Go)

Code before:
			return ctx.Err()
		case <-t.C:
			return nil
		}
	}
}

func (b *blobDownload) run(ctx context.Context, requestURL *url.URL, opts *registryOptions) error {
	defer blobDownloadManager.Delete(b.Digest)
	ctx, b.CancelFunc = context.WithCancel(ctx)

	file, err := os.OpenFile(b.Name+"-partial", os.O_CREATE|os.O_RDWR, 0o644)
	if err != nil {
		return err
	}
	defer file.Close()

	_ = file.Truncate(b.Total)

	directURL, err := func() (*url.URL, error) {
		ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
		defer cancel()

		backoff := newBackoff(10 * time.Second)
		for {
			// shallow close opts to be used in the closure
			// without affecting the outer opts.
			newOpts := new(registryOptions)
			*newOpts = *opts

			newOpts.CheckRedirect = func(req *http.Request, via []*http.Request) error {
				if len(via) > 10 {
					return errors.New("maxium redirects exceeded (10) for directURL")
				}

				// if the hostname is the same, allow the redirect
				if req.URL.Hostname() == requestURL.Hostname() {
					return nil
				}

				// stop at the first redirect that is not
				// the same hostname as the original
				// request.
				return http.ErrUseLastResponse
			}

			resp, err := makeRequestWithRetry(ctx, http.MethodGet, requestURL, nil, nil, newOpts)
			if err != nil {
				slog.Warn("failed to get direct URL; backing off and retrying", "err", err)
				if err := backoff(ctx); err != nil {
					return nil, err

Review comment (suggestion):
```suggestion
			// shallow clone opts to be used in the closure
```

Code after:
			return ctx.Err()
		case <-t.C:
			return nil
		}
	}
}

func (b *blobDownload) run(ctx context.Context, requestURL *url.URL, opts *registryOptions) error {
	defer blobDownloadManager.Delete(b.Digest)
	ctx, b.CancelFunc = context.WithCancel(ctx)

	file, err := os.OpenFile(b.Name+"-partial", os.O_CREATE|os.O_RDWR, 0o644)
	if err != nil {
		return err
	}
	defer file.Close()

	_ = file.Truncate(b.Total)

	directURL, err := func() (*url.URL, error) {
		ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
		defer cancel()

		backoff := newBackoff(10 * time.Second)
		for {
			// shallow clone opts to be used in the closure
			// without affecting the outer opts.
			newOpts := new(registryOptions)
			*newOpts = *opts

			newOpts.CheckRedirect = func(req *http.Request, via []*http.Request) error {
				if len(via) > 10 {
					return errors.New("maxium redirects exceeded (10) for directURL")
				}

				// if the hostname is the same, allow the redirect
				if req.URL.Hostname() == requestURL.Hostname() {
					return nil
				}

				// stop at the first redirect that is not
				// the same hostname as the original
				// request.
				return http.ErrUseLastResponse
			}

			resp, err := makeRequestWithRetry(ctx, http.MethodGet, requestURL, nil, nil, newOpts)
			if err != nil {
				slog.Warn("failed to get direct URL; backing off and retrying", "err", err)
				if err := backoff(ctx); err != nil {
					return nil, err