fix(transfer): clean up temp files left by a dead connection

A failed write whose temp file cannot be removed (the connection is gone)
is remembered by the executor and removed again on Retry (typically after
the pool reconnected inside OnError) and at the end of Execute; whatever
still cannot be removed is named in Report.Warnings. Prepare now always
lists ToDir once (instead of a Lstat per root), so leftovers next to a
single top-level file are reported too. TestOverwriteThenDrop checks this
strictly, TestOverwriteThenDropRetryLeavesNoTemp covers the retry path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-11-01 04:15:40 +03:00
parent 2b1b9b0e95
commit edf196a149
6 changed files with 180 additions and 46 deletions

View file

@ -105,12 +105,25 @@ func writeTemp(ctx context.Context, fsys vfs.FS, path string, o WriteOptions, fi
err = finishMeta(ctx, fsys, tmp, o) err = finishMeta(ctx, fsys, tmp, o)
} }
if err != nil { if err != nil {
removeQuiet(ctx, fsys, tmp) if rerr := removeQuiet(ctx, fsys, tmp); rerr != nil {
return "", &leftoverError{path: tmp, err: err}
}
return "", err return "", err
} }
return tmp, nil return tmp, nil
} }
// leftoverError: the operation failed and its temp file could not be
// removed either (typically a dead connection). The executor removes it
// later — on a retry or at the end of the transfer.
type leftoverError struct {
path string
err error
}
func (e *leftoverError) Error() string { return e.err.Error() }
func (e *leftoverError) Unwrap() error { return e.err }
func finishMeta(ctx context.Context, fsys vfs.FS, p string, o WriteOptions) error { func finishMeta(ctx context.Context, fsys vfs.FS, p string, o WriteOptions) error {
caps := fsys.Caps() caps := fsys.Caps()
perm := o.Perm perm := o.Perm
@ -158,9 +171,14 @@ func commit(ctx context.Context, fsys vfs.FS, tmp, path string, replace bool) er
return nil return nil
} }
// removeQuiet deletes a temp file even when ctx is already cancelled. // removeQuiet deletes a temp file even when ctx is already cancelled. A
func removeQuiet(ctx context.Context, fsys vfs.FS, p string) { // file that is already gone is not an error.
_ = fsys.Remove(context.WithoutCancel(ctx), p) func removeQuiet(ctx context.Context, fsys vfs.FS, p string) error {
err := fsys.Remove(context.WithoutCancel(ctx), p)
if err == nil || errors.Is(err, vfs.ErrNotExist) {
return nil
}
return err
} }
// ctxWriter stops writing once ctx is done and keeps the File's ReadFrom // ctxWriter stops writing once ctx is done and keeps the File's ReadFrom

View file

@ -5,6 +5,8 @@ import (
"errors" "errors"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"sync/atomic"
"syscall" "syscall"
"testing" "testing"
"time" "time"
@ -245,3 +247,42 @@ func TestReportCounts(t *testing.T) {
t.Fatalf("missing affected %v", wantAffected) t.Fatalf("missing affected %v", wantAffected)
} }
} }
// A write fails and its temp cannot be removed (dead connection): the
// executor remembers the temp and removes it on the retry (3.7 finding).
func TestRetryRemovesTempOfFailedAttempt(t *testing.T) {
src, dst := layout(t, fstree.Spec{fstree.File("a", "").WithSize(200 << 10)}, nil)
var dead atomic.Bool
dead.Store(true)
wrote := 0
to := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error {
switch {
case op == vfstest.OpWrite && dead.Load():
if wrote++; wrote == 2 {
return vfs.ErrConnLost
}
case op == vfstest.OpRemove && dead.Load():
return vfs.ErrConnLost
}
return nil
}}
_, rep := run(t, req(Copy, local, join(src, "a"), to, dst), Hooks{
OnError: func(context.Context, ItemError) (ErrorAction, error) {
dead.Store(false) // "reconnected"
return ErrorRetry, nil
},
})
if rep.Done != 1 || len(rep.Warnings) != 0 {
t.Fatalf("%+v", rep)
}
noLeftovers(t, dst)
// Without a working connection until the end, the leftover is reported.
dead.Store(true)
wrote = 0
_, dst2 := layout(t, nil, nil)
_, rep = run(t, req(Copy, local, join(src, "a"), to, dst2, skipAll), Hooks{})
if rep.Failed != 1 || len(rep.Warnings) != 1 || !strings.Contains(rep.Warnings[0], partPrefix) {
t.Fatalf("%+v", rep)
}
}

View file

@ -41,7 +41,8 @@ type executor struct {
incomplete map[string]bool // rel of source dirs that keep content (move) incomplete map[string]bool // rel of source dirs that keep content (move)
dirFix []dirFix dirFix []dirFix
affected map[string]bool affected map[string]bool
srcDirs []Item // move: source directories, removed post-order leftovers []string // temp files whose removal failed (dead connection)
srcDirs []Item // move: source directories, removed post-order
srcDirsAffected map[string]bool srcDirsAffected map[string]bool
crossVol bool crossVol bool
} }
@ -116,6 +117,10 @@ func (e *executor) run() {
// fills the report. // fills the report.
func (e *executor) finish() { func (e *executor) finish() {
bg := context.WithoutCancel(e.ctx) bg := context.WithoutCancel(e.ctx)
e.cleanLeftovers()
for _, p := range e.leftovers {
e.rep.Warnings = append(e.rep.Warnings, p+": temp file of a failed write could not be removed")
}
for i := len(e.dirFix) - 1; i >= 0; i-- { for i := len(e.dirFix) - 1; i >= 0; i-- {
d := e.dirFix[i] d := e.dirFix[i]
caps := e.to.Caps() caps := e.to.Caps()
@ -393,11 +398,16 @@ func (e *executor) doFile(it Item, open func() (io.ReadCloser, error)) error {
e.finishFile(it, true) e.finishFile(it, true)
return nil return nil
} }
var lo *leftoverError
if errors.As(err, &lo) {
e.leftovers = append(e.leftovers, lo.path)
}
if isCancel(e.ctx, err) { if isCancel(e.ctx, err) {
return errStop return errStop
} }
switch r := e.handleError(it, op, err); r { switch r := e.handleError(it, op, err); r {
case errRetry: case errRetry:
e.cleanLeftovers() // e.g. the pool reconnected inside OnError
continue continue
case nil: case nil:
e.finishFile(it, false) e.finishFile(it, false)
@ -441,29 +451,29 @@ func (e *executor) commitItem(it Item, rel *string, tmp string, replace *bool) e
err := commit(e.ctx, e.to, tmp, dst, *replace) err := commit(e.ctx, e.to, tmp, dst, *replace)
if !errors.Is(err, vfs.ErrExist) || *replace { if !errors.Is(err, vfs.ErrExist) || *replace {
if err != nil { if err != nil {
removeQuiet(e.ctx, e.to, tmp) e.dropTemp(tmp)
} }
return err return err
} }
fi, lerr := e.to.Lstat(e.ctx, dst) fi, lerr := e.to.Lstat(e.ctx, dst)
if lerr != nil { if lerr != nil {
removeQuiet(e.ctx, e.to, tmp) e.dropTemp(tmp)
return lerr return lerr
} }
a, derr := e.decide(it, rel, fi) a, derr := e.decide(it, rel, fi)
if derr != nil { if derr != nil {
removeQuiet(e.ctx, e.to, tmp) e.dropTemp(tmp)
return derr return derr
} }
switch a { switch a {
case ResolveSkip: case ResolveSkip:
removeQuiet(e.ctx, e.to, tmp) e.dropTemp(tmp)
return errSkipItem return errSkipItem
case ResolveOverwrite: case ResolveOverwrite:
*replace = true *replace = true
} }
} }
removeQuiet(e.ctx, e.to, tmp) e.dropTemp(tmp)
return fmt.Errorf("%s: target keeps changing", *rel) return fmt.Errorf("%s: target keeps changing", *rel)
} }
@ -516,7 +526,7 @@ func (e *executor) writeItem(it Item, dst string, replace bool, open func() (io.
return "", op, err return "", op, err
} }
if e.move && pr.n != it.Size { if e.move && pr.n != it.Size {
removeQuiet(e.ctx, e.to, tmp) e.dropTemp(tmp)
return "", "read", fmt.Errorf("source changed during the move: read %d of %d bytes", pr.n, it.Size) return "", "read", fmt.Errorf("source changed during the move: read %d of %d bytes", pr.n, it.Size)
} }
return tmp, "write", nil return tmp, "write", nil
@ -551,3 +561,21 @@ func sortedKeys(m map[string]bool) []string {
sort.Strings(out) sort.Strings(out)
return out return out
} }
// dropTemp removes a temp file, remembering it if that fails.
func (e *executor) dropTemp(p string) {
if removeQuiet(e.ctx, e.to, p) != nil {
e.leftovers = append(e.leftovers, p)
}
}
// cleanLeftovers retries the removal of temp files from failed attempts.
func (e *executor) cleanLeftovers() {
keep := e.leftovers[:0]
for _, p := range e.leftovers {
if removeQuiet(e.ctx, e.to, p) != nil {
keep = append(keep, p)
}
}
e.leftovers = keep
}

View file

@ -12,10 +12,6 @@ import (
// partPrefix names temp files of WriteAtomic: <dir>/.vcom-part-<8hex>-<name>. // partPrefix names temp files of WriteAtomic: <dir>/.vcom-part-<8hex>-<name>.
const partPrefix = ".vcom-part-" const partPrefix = ".vcom-part-"
// rootLstatMax: with more roots than this, the target directory is listed
// once instead of one Lstat per root.
const rootLstatMax = 4
// Prepare validates req and builds the plan (design §4.2): the target is // Prepare validates req and builds the plan (design §4.2): the target is
// writable and a directory; no root is the same file as its target and no // writable and a directory; no root is the same file as its target and no
// directory is copied into itself (SameFile/Within, through symlinks); the // directory is copied into itself (SameFile/Within, through symlinks); the
@ -157,9 +153,9 @@ func splitRel(rel string) (parent, name string) {
return rel[:i], rel[i+1:] return rel[:i], rel[i+1:]
} }
// findExisting fills Existing and Conflicts. Target directories are listed // findExisting fills Existing and Conflicts. ToDir and the target
// only when they exist as real directories that a source directory merges // directories a source directory merges into are listed — one ReadDir per
// into — one ReadDir per directory (N-P2-4/5). // directory, never a stat per file (N-P2-4/5).
func findExisting(ctx context.Context, plan *Plan) error { func findExisting(ctx context.Context, plan *Plan) error {
to, toDir := plan.Req.To, plan.Req.ToDir to, toDir := plan.Req.To, plan.Req.ToDir
listings := map[string]map[string]vfs.FileInfo{} listings := map[string]map[string]vfs.FileInfo{}
@ -181,16 +177,11 @@ func findExisting(ctx context.Context, plan *Plan) error {
return nil return nil
} }
roots := 0 // ToDir is always listed once: it gives Existing for every root without
for _, it := range plan.Items { // a stat per root and reveals temp files left by an interrupted transfer
if !strings.Contains(it.Rel, "/") { // (a dead connection cannot remove them).
roots++ if err := list("", toDir); err != nil {
} return err
}
if roots > rootLstatMax {
if err := list("", toDir); err != nil {
return err
}
} }
for i := range plan.Items { for i := range plan.Items {
@ -206,14 +197,6 @@ func findExisting(ctx context.Context, plan *Plan) error {
if fi, ok := l[name]; ok { if fi, ok := l[name]; ok {
existing = &fi existing = &fi
} }
} else if parent == "" {
fi, err := to.Lstat(ctx, dstPath(to, toDir, it.Rel))
switch {
case err == nil:
existing = &fi
case !errors.Is(err, vfs.ErrNotExist):
return err
}
} }
it.Existing = existing it.Existing = existing
if existing == nil { if existing == nil {

View file

@ -5,6 +5,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"vcom/internal/testutil/fstree" "vcom/internal/testutil/fstree"
@ -146,14 +147,14 @@ func TestPrepareReadDirPerDirNotPerFile(t *testing.T) {
if len(plan.Conflicts) != 500 { if len(plan.Conflicts) != 500 {
t.Fatalf("%d conflicts", len(plan.Conflicts)) t.Fatalf("%d conflicts", len(plan.Conflicts))
} }
if n := c.get(vfstest.OpReadDir); n != 1 { if n := c.get(vfstest.OpReadDir); n != 2 { // ToDir and d
t.Fatalf("%d ReadDir calls on the target, want 1 (N-P2-4/5)", n) t.Fatalf("%d ReadDir calls on the target, want 2: one per directory (N-P2-4/5)", n)
} }
if n := c.get(vfstest.OpLstat) + c.get(vfstest.OpStat); n > 4 { if n := c.get(vfstest.OpLstat) + c.get(vfstest.OpStat); n > 4 {
t.Fatalf("%d stat calls on the target", n) t.Fatalf("%d stat calls on the target", n)
} }
// Many roots: one listing of ToDir instead of a Lstat per root. // Many roots: one listing of ToDir, no stat per root.
var roots fstree.Spec var roots fstree.Spec
var names []string var names []string
for i := range 50 { for i := range 50 {
@ -167,7 +168,7 @@ func TestPrepareReadDirPerDirNotPerFile(t *testing.T) {
if _, err := Prepare(bg, req(Copy, local, join(src, names...), to, dst), nil); err != nil { if _, err := Prepare(bg, req(Copy, local, join(src, names...), to, dst), nil); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if c.get(vfstest.OpReadDir) != 1 || c.get(vfstest.OpLstat) > 2 { if c.get(vfstest.OpReadDir) != 1 || c.get(vfstest.OpLstat) > 0 {
t.Fatalf("many roots: readdir=%d lstat=%d", c.get(vfstest.OpReadDir), c.get(vfstest.OpLstat)) t.Fatalf("many roots: readdir=%d lstat=%d", c.get(vfstest.OpReadDir), c.get(vfstest.OpLstat))
} }
} }
@ -212,3 +213,15 @@ func TestPrepareRejectsBadTargets(t *testing.T) {
t.Fatalf("move from read-only: %v", err) t.Fatalf("move from read-only: %v", err)
} }
} }
func TestPrepareWarnsAboutLeftoversInToDir(t *testing.T) {
src, dst := layout(t, fstree.Spec{fstree.File("important.db", "new")},
fstree.Spec{fstree.File("important.db", "old"), fstree.File(".vcom-part-0badc0de-important.db", "half")})
plan, err := Prepare(bg, req(Copy, local, join(src, "important.db"), local, dst, overwrite), nil)
if err != nil {
t.Fatal(err)
}
if len(plan.Warnings) != 1 || !strings.Contains(plan.Warnings[0], ".vcom-part-0badc0de-important.db") {
t.Fatalf("warnings %v: a leftover next to a single root must be reported", plan.Warnings)
}
}

View file

@ -12,6 +12,7 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"strconv" "strconv"
"strings"
"sync" "sync"
"sync/atomic" "sync/atomic"
"testing" "testing"
@ -143,16 +144,26 @@ func TestOverwriteThenDrop(t *testing.T) {
if err != nil || !bytes.Equal(now, old) { if err != nil || !bytes.Equal(now, old) {
t.Fatalf("old destination damaged: %d bytes, err %v", len(now), err) t.Fatalf("old destination damaged: %d bytes, err %v", len(now), err)
} }
// The temp file cannot be removed over a dead connection: a hidden // The temp file cannot be removed over a dead connection; the next plan
// .vcom-part-* may stay (see 04-dev-log-B.md, 3.7). It never replaces the // for this directory must report it.
// target, and a retry after reconnect writes a fresh temp file. parts := partFiles(t, dir)
if parts := partFiles(t, dir); len(parts) > 0 { if len(parts) != 1 || len(rep.Warnings) != 1 || !strings.Contains(rep.Warnings[0], parts[0]) {
t.Logf("temp left after the cut: %v", parts) t.Fatalf("temp after the cut: %v; the report must name it: %v", parts, rep.Warnings)
} }
if err := s.pool.Reconnect(bg, remote.Conn().Key()); err != nil { if err := s.pool.Reconnect(bg, remote.Conn().Key()); err != nil {
t.Fatal(err) t.Fatal(err)
} }
rep = Execute(bg, prepare(t, req(Copy, local, join(srcDir, "important.db"), remote, dir, overwrite)), Hooks{}) plan = prepare(t, req(Copy, local, join(srcDir, "important.db"), remote, dir, overwrite))
for _, p := range parts {
found := false
for _, w := range plan.Warnings {
found = found || strings.Contains(w, p)
}
if !found {
t.Errorf("leftover %s not reported by Prepare: %v", p, plan.Warnings)
}
}
rep = Execute(bg, plan, Hooks{})
if rep.Done != 1 { if rep.Done != 1 {
t.Fatalf("copy after reconnect: %+v", rep) t.Fatalf("copy after reconnect: %+v", rep)
} }
@ -161,6 +172,46 @@ func TestOverwriteThenDrop(t *testing.T) {
} }
} }
// The same cut, but the caller answers the error with reconnect + Retry
// inside one Execute: the temp of the failed attempt is removed on the new
// connection, nothing is left behind.
func TestOverwriteThenDropRetryLeavesNoTemp(t *testing.T) {
s := newRStand(t)
px := s.proxy()
remote := s.fs(px.Addr, "")
dir := t.TempDir()
dst := filepath.Join(dir, "important.db")
sshtest.WriteRandom(t, dst, 2<<20, 0o644)
srcDir := t.TempDir()
want := sshtest.WriteRandom(t, filepath.Join(srcDir, "important.db"), 8<<20, 0o644)
plan := prepare(t, req(Copy, local, join(srcDir, "important.db"), remote, dir, overwrite))
px.CutAfter(1 << 20)
retries := 0
rep := Execute(bg, plan, Hooks{OnError: func(ctx context.Context, e ItemError) (ErrorAction, error) {
if !errors.Is(e.Err, vfs.ErrConnLost) || retries > 0 {
return ErrorStop, nil
}
retries++
if err := s.pool.Reconnect(ctx, remote.Conn().Key()); err != nil {
return ErrorStop, err
}
return ErrorRetry, nil
}})
if rep.Done != 1 || rep.Failed != 0 || retries != 1 {
t.Fatalf("report = %+v, retries %d", rep, retries)
}
if now, _ := os.ReadFile(dst); !bytes.Equal(now, want) {
t.Fatalf("target after retry: %d bytes", len(now))
}
if parts := partFiles(t, dir); len(parts) != 0 {
t.Fatalf("temp files left after a successful retry: %v", parts)
}
if len(rep.Warnings) != 0 {
t.Fatalf("warnings %v", rep.Warnings)
}
}
// Ported from TestSameFileViaAliasTruncates (B4), N-P0-5: the same file // Ported from TestSameFileViaAliasTruncates (B4), N-P0-5: the same file
// through two aliases of one server was truncated to zero. // through two aliases of one server was truncated to zero.
func TestSameFileViaAliasRejected(t *testing.T) { func TestSameFileViaAliasRejected(t *testing.T) {