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)
}
if err != nil {
removeQuiet(ctx, fsys, tmp)
if rerr := removeQuiet(ctx, fsys, tmp); rerr != nil {
return "", &leftoverError{path: tmp, err: err}
}
return "", err
}
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 {
caps := fsys.Caps()
perm := o.Perm
@ -158,9 +171,14 @@ func commit(ctx context.Context, fsys vfs.FS, tmp, path string, replace bool) er
return nil
}
// removeQuiet deletes a temp file even when ctx is already cancelled.
func removeQuiet(ctx context.Context, fsys vfs.FS, p string) {
_ = fsys.Remove(context.WithoutCancel(ctx), p)
// removeQuiet deletes a temp file even when ctx is already cancelled. A
// file that is already gone is not an error.
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

View file

@ -5,6 +5,8 @@ import (
"errors"
"os"
"path/filepath"
"strings"
"sync/atomic"
"syscall"
"testing"
"time"
@ -245,3 +247,42 @@ func TestReportCounts(t *testing.T) {
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)
dirFix []dirFix
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
crossVol bool
}
@ -116,6 +117,10 @@ func (e *executor) run() {
// fills the report.
func (e *executor) finish() {
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-- {
d := e.dirFix[i]
caps := e.to.Caps()
@ -393,11 +398,16 @@ func (e *executor) doFile(it Item, open func() (io.ReadCloser, error)) error {
e.finishFile(it, true)
return nil
}
var lo *leftoverError
if errors.As(err, &lo) {
e.leftovers = append(e.leftovers, lo.path)
}
if isCancel(e.ctx, err) {
return errStop
}
switch r := e.handleError(it, op, err); r {
case errRetry:
e.cleanLeftovers() // e.g. the pool reconnected inside OnError
continue
case nil:
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)
if !errors.Is(err, vfs.ErrExist) || *replace {
if err != nil {
removeQuiet(e.ctx, e.to, tmp)
e.dropTemp(tmp)
}
return err
}
fi, lerr := e.to.Lstat(e.ctx, dst)
if lerr != nil {
removeQuiet(e.ctx, e.to, tmp)
e.dropTemp(tmp)
return lerr
}
a, derr := e.decide(it, rel, fi)
if derr != nil {
removeQuiet(e.ctx, e.to, tmp)
e.dropTemp(tmp)
return derr
}
switch a {
case ResolveSkip:
removeQuiet(e.ctx, e.to, tmp)
e.dropTemp(tmp)
return errSkipItem
case ResolveOverwrite:
*replace = true
}
}
removeQuiet(e.ctx, e.to, tmp)
e.dropTemp(tmp)
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
}
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 tmp, "write", nil
@ -551,3 +561,21 @@ func sortedKeys(m map[string]bool) []string {
sort.Strings(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>.
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
// 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
@ -157,9 +153,9 @@ func splitRel(rel string) (parent, name string) {
return rel[:i], rel[i+1:]
}
// findExisting fills Existing and Conflicts. Target directories are listed
// only when they exist as real directories that a source directory merges
// into — one ReadDir per directory (N-P2-4/5).
// findExisting fills Existing and Conflicts. ToDir and the target
// directories a source directory merges into are listed — one ReadDir per
// directory, never a stat per file (N-P2-4/5).
func findExisting(ctx context.Context, plan *Plan) error {
to, toDir := plan.Req.To, plan.Req.ToDir
listings := map[string]map[string]vfs.FileInfo{}
@ -181,16 +177,11 @@ func findExisting(ctx context.Context, plan *Plan) error {
return nil
}
roots := 0
for _, it := range plan.Items {
if !strings.Contains(it.Rel, "/") {
roots++
}
}
if roots > rootLstatMax {
if err := list("", toDir); err != nil {
return err
}
// ToDir is always listed once: it gives Existing for every root without
// a stat per root and reveals temp files left by an interrupted transfer
// (a dead connection cannot remove them).
if err := list("", toDir); err != nil {
return err
}
for i := range plan.Items {
@ -206,14 +197,6 @@ func findExisting(ctx context.Context, plan *Plan) error {
if fi, ok := l[name]; ok {
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
if existing == nil {

View file

@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"path/filepath"
"strings"
"testing"
"vcom/internal/testutil/fstree"
@ -146,14 +147,14 @@ func TestPrepareReadDirPerDirNotPerFile(t *testing.T) {
if len(plan.Conflicts) != 500 {
t.Fatalf("%d conflicts", len(plan.Conflicts))
}
if n := c.get(vfstest.OpReadDir); n != 1 {
t.Fatalf("%d ReadDir calls on the target, want 1 (N-P2-4/5)", n)
if n := c.get(vfstest.OpReadDir); n != 2 { // ToDir and d
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 {
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 names []string
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 {
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))
}
}
@ -212,3 +213,15 @@ func TestPrepareRejectsBadTargets(t *testing.T) {
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"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
@ -143,16 +144,26 @@ func TestOverwriteThenDrop(t *testing.T) {
if err != nil || !bytes.Equal(now, old) {
t.Fatalf("old destination damaged: %d bytes, err %v", len(now), err)
}
// The temp file cannot be removed over a dead connection: a hidden
// .vcom-part-* may stay (see 04-dev-log-B.md, 3.7). It never replaces the
// target, and a retry after reconnect writes a fresh temp file.
if parts := partFiles(t, dir); len(parts) > 0 {
t.Logf("temp left after the cut: %v", parts)
// The temp file cannot be removed over a dead connection; the next plan
// for this directory must report it.
parts := partFiles(t, dir)
if len(parts) != 1 || len(rep.Warnings) != 1 || !strings.Contains(rep.Warnings[0], parts[0]) {
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 {
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 {
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
// through two aliases of one server was truncated to zero.
func TestSameFileViaAliasRejected(t *testing.T) {