Interrupted multipart download can remove a part and leave file handles open
Summary
A multipart download interrupted at a timeout boundary can treat an incomplete part as successful. Merging then produces a shorter file and removes another part. Retrying the same download can fail because that part is missing. On Windows, cleanup can also fail because a remaining part is still open.
Reproduced locally with getparty v1.26.3 and v1.28.2 on Windows.
Client-visible errors (redacted)
The observed error sequence is a short download, a missing multipart file on retry, and a file-in-use error during cleanup:
run: ContentLength mismatch: expected <expected-bytes> got <actual-bytes>
run: open <download-directory>\<download-file>.zip.06: The system cannot find the file specified.
Cannot remove item <download-directory>\<download-file>.zip.01: The process cannot access the file '<download-file>.zip.01' because it is being used by another process.
Paths, filenames, and byte counts are replaced with placeholders. Timestamps, URLs, identifiers, and application-specific logging context are omitted. The standalone reproduction below uses a separate generic payload.
Reproduction
This uses a local HTTP server and a 64 KiB payload, with no external service. The debug writer delays the first part immediately after its response headers to exercise the timeout boundary.
Save the following as main.go in an empty directory:
package main
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/vbauerster/getparty"
)
type delayedWriter struct{ once sync.Once }
func (w *delayedWriter) Write(p []byte) (int, error) {
s := string(p)
if strings.Contains(s, "[P01:R00]") && strings.Contains(s, "Response Status:") {
w.once.Do(func() { time.Sleep(1500 * time.Millisecond) })
}
return len(p), nil
}
func main() {
payload := bytes.Repeat([]byte("abcdefgh"), 8192)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.ServeContent(w, r, "payload.bin", time.Time{}, bytes.NewReader(payload))
}))
defer server.Close()
dir, err := os.MkdirTemp("", "getparty-repro-")
if err != nil {
panic(err)
}
fmt.Println("Artifacts:", dir)
dest := filepath.Join(dir, "payload.bin")
writer := new(delayedWriter)
for attempt := 1; attempt <= 2; attempt++ {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
cmd := &getparty.Cmd{Ctx: ctx, Out: io.Discard, Err: writer}
err := cmd.Run([]string{
server.URL, "--parts=2", "--output.name=" + dest,
"--output.overwrite", "--timeout=1", "--debug",
}, "", "")
cancel()
fmt.Printf("Attempt %d: %v\n", attempt, err)
}
fmt.Printf("Remove .01: %v\n", os.Remove(dest+".01"))
}
Run:
go mod init example.com/getparty-repro
go get github.com/vbauerster/[email protected]
go run .
The temporary directory is intentionally retained for inspecting the part files.
Actual behavior
In the controlled reproduction:
- First attempt reports a length mismatch: expected 65536 bytes, got 32768.
- Second attempt fails to open the missing
.02part. - On Windows, removing
.01fails because the file is being used by another process.
Expected behavior
Retry the incomplete part or return a download error before destructive merging. Preserve unmerged part files on validation failure and release file handles before returning an error.
You did meticulous job to reproduce, thanks. However I hope you don't use such slow debug writer in production. My recent commits should fix this, you're welcome to recheck.
Out of curiosity why do you self retry in a loop? Is it just for reproduction sake or is it how do you really use it? It's not my business but I would rather provide --max-retry=0 (infinite retry) or as a last resort increase its value if you're not big fun of infinity.
This is just for repro. we directly use getparty in our code.
Thanks for the fixes. Understood on keeping the change narrow.
I rechecked fca5109 / ef7f68e0e68e300620c0b3c43e057f77a822e85a on Windows:
| Check | Result |
|---|---|
| Timeout before the first copy | Pass: the incomplete part is retried |
| Normal three-part and ten-part downloads | Pass: complete, byte-exact payload |
| Separately injected merge-length error | Fail: after Cmd.Run returns the error, .01 cannot be removed because a handle remains open |
The original timeout behavior is fixed in these checks. The last row is a separate error-path cleanup case, not a claim that the timeout fix failed.
Standalone reproduction for the third case
This is a deliberately fault-injected, local-only probe. It truncates .01 to one byte after both parts report download completion, to force a merge-length error. It does not show spontaneous file corruption in a normal download. There is no slow debug writer, no outer retry loop, and just one call to Cmd.Run. The expected property is only that an error return releases its file handles; transactional merge recovery is not required.
Save this as main.go in an empty directory:
package main
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/vbauerster/getparty"
)
type mergeFaultWriter struct {
mu sync.Mutex
destination string
finished map[string]bool
injected bool
injectErr error
}
func (w *mergeFaultWriter) Write(data []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
text := string(data)
if strings.Contains(text, "Return err: <nil>") {
for _, part := range []string{"[P01:", "[P02:"} {
if strings.Contains(text, part) {
w.finished[part] = true
}
}
if len(w.finished) == 2 && !w.injected {
w.injected = true
w.injectErr = os.Truncate(w.destination+".01", 1)
}
}
return len(data), nil
}
func run() error {
payload := bytes.Repeat([]byte("abcdefgh"), 8192)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.ServeContent(w, r, "payload.bin", time.Time{}, bytes.NewReader(payload))
}))
defer server.Close()
dir, err := os.MkdirTemp("", "getparty-merge-repro-")
if err != nil {
return err
}
destination := filepath.Join(dir, "payload.bin")
writer := &mergeFaultWriter{destination: destination, finished: make(map[string]bool)}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := &getparty.Cmd{Ctx: ctx, Out: io.Discard, Err: writer}
downloadErr := cmd.Run([]string{
server.URL, "--parts=2", "--output.name=" + destination,
"--output.overwrite", "--debug",
}, "", "")
writer.mu.Lock()
injected, injectErr := writer.injected, writer.injectErr
writer.mu.Unlock()
fmt.Printf("Fault injected: %t\n", injected)
if !injected || injectErr != nil {
return fmt.Errorf("fault injection failed: injected=%t, error=%v", injected, injectErr)
}
if downloadErr == nil {
return errors.New("expected a merge-length error, got successful download")
}
redacted := strings.ReplaceAll(downloadErr.Error(), dir, "<download-directory>")
redacted = strings.ReplaceAll(redacted, strings.ReplaceAll(dir, `\`, `\\`), "<download-directory>")
fmt.Printf("Run returned: %s\n", redacted)
removeErr := os.Remove(destination + ".01")
if removeErr == nil {
fmt.Println("Remove .01: success (handle released)")
} else {
var pathErr *os.PathError
if errors.As(removeErr, &pathErr) {
fmt.Printf("Remove .01: %v\n", pathErr.Err)
} else {
return removeErr
}
}
fmt.Println("This probe intentionally retains its temporary directory for inspection.")
return nil
}
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
Run:
go mod init example.com/getparty-merge-repro
go get github.com/vbauerster/getparty@ef7f68e0e68e300620c0b3c43e057f77a822e85a
go run .
Observed on Windows:
Fault injected: true
Run returned: run: ContentLength mismatch: expected 65536 got 32769
Remove .01: The process cannot access the file because it is being used by another process.
This probe intentionally retains its temporary directory for inspection.
As a control, the same probe against the handle-release changes in the closed PR's commit 8a6c236e304297ad64a722c708ee6c727b2c61a6 still returns a validation error, but reports Remove .01: success (handle released).
Would a separate, minimal output-handle cleanup fix and regression test be appropriate? This keeps it distinct from your timeout fix and from the broader pre-merge validation changes in #38.
Master 9b5495dd50201054008ce94499529b5859b67da5 should address your Separately injected merge-length error check.
Thanks for the follow-up fixes. Revalidated on Windows against latest master, 61add54f4f8e941d19df076948818d3198138555, which includes 9b5495dd50201054008ce94499529b5859b67da5.
- Timeout before the first copy: PASS in three repetitions.
- Separately injected merge-length error: PASS in three repetitions; the download returns an error, handles are released, artifacts can be removed, and a subsequent clean download succeeds.
- Normal three-part and ten-part downloads: PASS in three repetitions, with byte-exact output and no leftover part/session files.
- The exact standalone merge-error reproduction posted above now returns the expected validation error and reports
Remove .01: success (handle released). - Unmodified upstream
go test ./... -count=1: PASS.
As a positive failing control, the unchanged standalone merge-error reproduction against ef7f68e0e68e300620c0b3c43e057f77a822e85a still reports the Windows file-in-use error. The merge-length case remains deliberate fault injection, not evidence of spontaneous corruption during normal downloads.
Both reported reproduction paths are fixed in the tested master revision. Closing as completed. Thank you!