From bdc773523ca809278a08ef4bdcb4d821c7b48a1a Mon Sep 17 00:00:00 2001 From: Emilio Del Tessandoro Date: Thu, 26 Nov 2026 15:58:58 +0100 Subject: [PATCH 1/7] feat(volumes): stream put parts and make upload concurrency tunable `volumes put` sends --concurrency parts at once (1 to 64, default 32; it was fixed at 4). Each part streams from the file through the new volumeformat.PartSealer.StreamReader, so a part in flight holds about 1 MiB instead of its whole plaintext of about 64 MiB. StreamReader's output is byte for byte what Seal and Reader return; the wire format is unchanged. The hashing pre-pass records each part's SHA-256 with the file's, from the same read, and the hash cache keeps both (form 3, so older entries are a miss). The sender hashes each part as it streams and seals the part's last segment only once the bytes match the recorded digest, so a part that changed after hashing is never acknowledged and put aborts. Before a file's last part, put also checks that the file's size and times have not moved. A resumed upload rehashes its files instead of trusting the cache, since it does not read its acknowledged parts again, and aborts when a part's digest differs from the one journalled before. An error for a changed part names the part once, cause first. The help and the missing organization error say to add a top-level `organization: ` line to ~/.runware/config.yaml, which config set cannot set, or to set RUNWARE_ORGANIZATION. --- internal/cmd/serverless/volumes.go | 22 +- internal/cmd/serverless/volumes_test.go | 143 +++++++- internal/volumes/put/api.go | 11 + internal/volumes/put/behavior_test.go | 14 +- internal/volumes/put/dedup_test.go | 3 +- internal/volumes/put/hashcache.go | 194 +++++++++-- internal/volumes/put/hashcache_test.go | 76 +++-- internal/volumes/put/help.go | 9 + internal/volumes/put/part_digest_test.go | 409 +++++++++++++++++++++++ internal/volumes/put/part_retry_test.go | 29 +- internal/volumes/put/part_stream_test.go | 176 ++++++++++ internal/volumes/put/parts.go | 195 ++++++----- internal/volumes/put/put_test.go | 78 ++++- internal/volumes/put/resume.go | 27 +- internal/volumes/put/resume_test.go | 286 ++++++++++++++-- internal/volumes/put/run.go | 22 +- internal/volumes/put/sealer.go | 4 +- internal/volumes/put/transport.go | 2 +- internal/volumes/put/transport_test.go | 2 +- internal/volumes/put/walk.go | 17 +- pkg/volumeformat/part.go | 140 +++++++- pkg/volumeformat/stream_test.go | 391 ++++++++++++++++++++++ 22 files changed, 2009 insertions(+), 241 deletions(-) create mode 100644 internal/volumes/put/part_digest_test.go create mode 100644 internal/volumes/put/part_stream_test.go create mode 100644 pkg/volumeformat/stream_test.go diff --git a/internal/cmd/serverless/volumes.go b/internal/cmd/serverless/volumes.go index 3f2b9e6a..442872d9 100644 --- a/internal/cmd/serverless/volumes.go +++ b/internal/cmd/serverless/volumes.go @@ -23,7 +23,8 @@ import ( ) const ( - toFlag = "to" + toFlag = "to" + concurrencyFlag = "concurrency" // volumesStateDir is the directory under the CLI config directory that // holds the statement sequence record, the hash cache and the upload // journals. @@ -79,7 +80,10 @@ func newVolumesCmd(logger *log.Logger) *cobra.Command { } func newVolumesPutCmd(logger *log.Logger) *cobra.Command { - var to string + var ( + to string + concurrency int + ) cmd := &cobra.Command{ Use: "put ...", Short: put.HelpShort, @@ -87,6 +91,9 @@ func newVolumesPutCmd(logger *log.Logger) *cobra.Command { Example: put.HelpExample, Args: cobra.MinimumNArgs(2), RunE: func(cmd *cobra.Command, args []string) error { + if err := validatePutConcurrency(concurrency); err != nil { + return err + } // Before anything that could hold key material exists. if err := coredump.Disable(); err != nil { return err @@ -118,6 +125,7 @@ func newVolumesPutCmd(logger *log.Logger) *cobra.Command { API: client.VolumeUploads(), Keys: keys, Transport: newPartTransport(baseURL, debug), + Parallelism: concurrency, Progress: stderr, ProgressTTY: isTerminal(stderr), Logger: debug, @@ -129,10 +137,20 @@ func newVolumesPutCmd(logger *log.Logger) *cobra.Command { }, } cmd.Flags().StringVar(&to, toFlag, "", "Directory in the Volume the paths land under (default the Volume root)") + cmd.Flags().IntVar(&concurrency, concurrencyFlag, put.DefaultParallelism, + fmt.Sprintf("Parts to upload at once (1-%d); each part in flight holds about 1 MiB of memory", put.MaxParallelism)) addEnvironmentFlag(cmd, cmd.Flags(), logger, "Environment the Volume belongs to "+environmentFlagDefault) return cmd } +// validatePutConcurrency checks --concurrency against the range the upload engine runs. +func validatePutConcurrency(n int) error { + if n < 1 || n > put.MaxParallelism { + return fmt.Errorf("--%s must be between 1 and %d", concurrencyFlag, put.MaxParallelism) + } + return nil +} + // printPutSummary writes the summary as JSON or YAML, or as text with one line // per file, so every format carries the same values. func printPutSummary(w io.Writer, format output.Format, s put.Summary) error { diff --git a/internal/cmd/serverless/volumes_test.go b/internal/cmd/serverless/volumes_test.go index 4a4069c7..5f8cbc15 100644 --- a/internal/cmd/serverless/volumes_test.go +++ b/internal/cmd/serverless/volumes_test.go @@ -7,17 +7,21 @@ import ( "errors" "fmt" "io" + "log/slog" "maps" "net/http" "os" "path/filepath" "slices" + "strconv" "strings" + "sync" "testing" "time" "github.com/charmbracelet/log" "github.com/runware/runware-cli/internal/cmdutil" + "github.com/runware/runware-cli/internal/config" "github.com/runware/runware-cli/internal/output" "github.com/runware/runware-cli/internal/volumes/put" "gopkg.in/yaml.v3" @@ -89,7 +93,7 @@ func TestVolumesPutIsRegisteredInTheHiddenVolumesGroup(t *testing.T) { if !put.Parent().Hidden { t.Error("the volumes group is not hidden") } - for _, flag := range []string{toFlag, environmentFlag} { + for _, flag := range []string{toFlag, concurrencyFlag, environmentFlag} { if put.Flags().Lookup(flag) == nil { t.Errorf("volumes put has no --%s", flag) } @@ -99,6 +103,141 @@ func TestVolumesPutIsRegisteredInTheHiddenVolumesGroup(t *testing.T) { } } +func TestVolumesPutConcurrencyDefaultsToTheEngineDefault(t *testing.T) { + root := NewCmd(log.New(io.Discard)) + cmd, _, err := root.Find([]string{segVolumes, putUse}) + if err != nil { + t.Fatal(err) + } + flag := cmd.Flags().Lookup(concurrencyFlag) + if flag == nil { + t.Fatalf("volumes put has no --%s", concurrencyFlag) + } + if want := strconv.Itoa(put.DefaultParallelism); flag.DefValue != want { + t.Errorf("--%s defaults to %s, want %s", concurrencyFlag, flag.DefValue, want) + } + if err := cmd.Flags().Set(concurrencyFlag, "not-a-number"); err == nil { + t.Errorf("--%s accepted a value that is not a number", concurrencyFlag) + } +} + +func TestValidatePutConcurrency(t *testing.T) { + for _, n := range []int{1, 2, put.DefaultParallelism, put.MaxParallelism} { + if err := validatePutConcurrency(n); err != nil { + t.Errorf("--%s %d: %v", concurrencyFlag, n, err) + } + } + want := fmt.Sprintf("--%s must be between 1 and %d", concurrencyFlag, put.MaxParallelism) + for _, n := range []int{-1, 0, put.MaxParallelism + 1, 1000} { + err := validatePutConcurrency(n) + if err == nil || err.Error() != want { + t.Errorf("--%s %d: error %v, want %q", concurrencyFlag, n, err, want) + } + } +} + +func TestVolumesPutRefusesConcurrencyOutOfRangeBeforeAnyRequest(t *testing.T) { + f := newPutFake(t) + f.newVolume("", testVolume) + dir := newTree(t, testTree) + for _, value := range []string{"0", strconv.Itoa(put.MaxParallelism + 1)} { + r := f.run(formatJSON, false, testVolume, dir, "--"+concurrencyFlag, value) + requireOneLine(t, r.err, "--"+concurrencyFlag, "between 1 and") + } + if calls := f.callLog(); len(calls) != 0 { + t.Errorf("a refused --%s made requests: %v", concurrencyFlag, calls) + } +} + +// overlapTransport counts the parts in flight. The first part waits until a second one starts, or +// until wait passes, so a put that may send two parts at once does. +type overlapTransport struct { + inner put.Transport + wait time.Duration + mu sync.Mutex + inFlight int + most int + calls int + second chan struct{} + closed bool // second is closed; in flight can reach 2 again after dropping to 1 +} + +func (o *overlapTransport) PutPart(ctx context.Context, target put.Target, body io.Reader, length int64) (put.Secret, error) { + o.mu.Lock() + o.calls++ + first := o.calls == 1 + o.inFlight++ + o.most = max(o.most, o.inFlight) + if o.inFlight > 1 && !o.closed { + close(o.second) + o.closed = true + } + o.mu.Unlock() + if first { + select { + case <-o.second: + case <-time.After(o.wait): + } + } + defer func() { + o.mu.Lock() + o.inFlight-- + o.mu.Unlock() + }() + return o.inner.PutPart(ctx, target, body, length) +} + +// concurrencyCase is a --concurrency value, whether two parts may be in flight at once, and how long +// the first part waits for a second. Where a second must start, the wait only bounds a failing run, so +// it is long enough for a slow runner. Where none may start, every run spends the whole wait, so it is +// short: long enough for a second part to start when the flag does not reach the engine. +type concurrencyCase struct { + concurrency string + overlap bool + wait time.Duration +} + +// TestVolumesPutConcurrencyBoundsThePartsInFlight: --concurrency reaches the upload engine, so with 1 +// no second part starts while the first is in flight, and with more than 1 a second one does. +func TestVolumesPutConcurrencyBoundsThePartsInFlight(t *testing.T) { + for _, tc := range []concurrencyCase{ + { + concurrency: "1", + overlap: false, + wait: 100 * time.Millisecond, + }, + { + concurrency: "4", + overlap: true, + wait: 5 * time.Second, + }, + } { + t.Run(tc.concurrency, func(t *testing.T) { + f := newPutFake(t) + f.newVolume("", testVolume) + dir := newTree(t, testTree) + gate := &overlapTransport{ + wait: tc.wait, + second: make(chan struct{}), + } + inner := newPartTransport + newPartTransport = func(baseURL string, logger *slog.Logger) put.Transport { + gate.inner = inner(baseURL, logger) + return gate + } + + got := mustPut(t, f.run(formatJSON, false, testVolume, dir, "--"+concurrencyFlag, tc.concurrency)) + + if got.Added != len(testTree) || gate.calls != len(testTree) { + t.Fatalf("summary = %+v after %d part uploads, want %d files", got, gate.calls, len(testTree)) + } + if overlap := gate.most > 1; overlap != tc.overlap { + t.Errorf("with --%s %s, at most %d parts were in flight", concurrencyFlag, tc.concurrency, gate.most) + } + }) + } +} + func TestVolumesPutHelpDescribesAdditiveUploads(t *testing.T) { root := NewCmd(log.New(io.Discard)) cmd, _, err := root.Find([]string{segVolumes, putUse}) @@ -106,7 +245,7 @@ func TestVolumesPutHelpDescribesAdditiveUploads(t *testing.T) { t.Fatal(err) } help := strings.ToLower(cmd.Long) - for _, want := range []string{"additive", "workers that start after an upload get the new files", "rolling an app back", "create a new volume", "run the same command again to continue the upload"} { + for _, want := range []string{"additive", "workers that start after an upload get the new files", "rolling an app back", "create a new volume", "run the same command again to continue the upload", "organization id", `"organization: "`, "top level of ~/.runware/config.yaml (config set cannot set it)", strings.ToLower(config.OrganizationFromEnvVar), "--" + concurrencyFlag} { if !strings.Contains(help, want) { t.Errorf("help does not say %q", want) } diff --git a/internal/volumes/put/api.go b/internal/volumes/put/api.go index 8e6a8461..7aba7f86 100644 --- a/internal/volumes/put/api.go +++ b/internal/volumes/put/api.go @@ -158,6 +158,17 @@ func (e *FileError) Error() string { return e.Path + ": " + e.Err.Error() } func (e *FileError) Unwrap() error { return e.Err } +// sourceChangedError is ErrSourceChanged with its cause first: what no longer matches, then the advice. +type sourceChangedError struct { + cause string +} + +func (e sourceChangedError) Error() string { + return e.cause + ", so nothing from this upload was published; run put again" +} + +func (e sourceChangedError) Is(target error) bool { return target == ErrSourceChanged } + func fileErr(path string, err error) error { return &FileError{ Path: path, diff --git a/internal/volumes/put/behavior_test.go b/internal/volumes/put/behavior_test.go index d6d5e2a6..7c0b39ff 100644 --- a/internal/volumes/put/behavior_test.go +++ b/internal/volumes/put/behavior_test.go @@ -284,15 +284,15 @@ func TestParallelismBoundsPartRequestsAcrossFiles(t *testing.T) { } } -// TestParallelismIsBounded: zero or less runs four parts at once, and no more than sixteen run however many are asked for. +// TestParallelismIsBounded: zero or less runs the default number of parts at once, and no more than the most run however many are asked for. func TestParallelismIsBounded(t *testing.T) { for asked, want := range map[int]int{ - -3: 4, - 0: 4, - 1: 1, - 16: 16, - 17: 16, - 1000: 16, + -3: DefaultParallelism, + 0: DefaultParallelism, + 1: 1, + MaxParallelism: MaxParallelism, + MaxParallelism + 1: MaxParallelism, + 1000: MaxParallelism, } { r, err := newRunner(Options{ Organization: uuid.NewString(), diff --git a/internal/volumes/put/dedup_test.go b/internal/volumes/put/dedup_test.go index 1c8173a8..674b0890 100644 --- a/internal/volumes/put/dedup_test.go +++ b/internal/volumes/put/dedup_test.go @@ -284,7 +284,8 @@ func saveLegacyDeclarations(t *testing.T, opts Options) { if err != nil { t.Fatal(err) } - if err := hashSources(ctx, sources, loadHashCache(r.stateDir), r.progress, nil); err != nil { + r.o.onHash = nil + if err := r.hashSources(ctx, sources, loadHashCache(r.stateDir)); err != nil { t.Fatal(err) } sess, err := r.openKeys(ctx) diff --git a/internal/volumes/put/hashcache.go b/internal/volumes/put/hashcache.go index 6f4ce047..6d4f2d62 100644 --- a/internal/volumes/put/hashcache.go +++ b/internal/volumes/put/hashcache.go @@ -7,28 +7,35 @@ import ( "encoding/hex" "encoding/json" "fmt" + "hash" "io" "maps" "os" "path/filepath" "slices" "time" + + "github.com/runware/runware-cli/pkg/volumeformat" ) const ( - stateDirName = "volumes" - hashCacheFile = "hashes.json" - hashCacheForm = 2 + stateDirName = "volumes" + hashCacheFile = "hashes.json" + // Any change to PlanLayout's part boundaries must bump hashCacheForm, or cached part digests go stale. + hashCacheForm = 3 // 3 adds the part digests; an entry of an earlier form is a miss hashBufBytes = 1 << 20 maxCachedHashes = 100_000 ) +// cacheEntry is a file's digest and the digest of each of its parts. Parts is empty for a file of one +// part, whose part digest is the file's. type cacheEntry struct { - Size int64 `json:"size"` - ModTime int64 `json:"modTimeUnixNano"` - Change int64 `json:"changeTimeUnixNano"` - SHA256 string `json:"sha256"` - StoredAt int64 `json:"storedAtUnixNano,omitempty"` + Size int64 `json:"size"` + ModTime int64 `json:"modTimeUnixNano"` + Change int64 `json:"changeTimeUnixNano"` + SHA256 string `json:"sha256"` + Parts []string `json:"parts,omitempty"` + StoredAt int64 `json:"storedAtUnixNano,omitempty"` } type cacheFile struct { @@ -36,11 +43,14 @@ type cacheFile struct { Files map[string]cacheEntry `json:"files"` } -// hashCache remembers file digests by path, size, modification time and change time; a zero change time is never trusted. +// hashCache remembers file and part digests by path, size, modification time and change time; a zero change time is never trusted. type hashCache struct { path string entries map[string]cacheEntry dirty bool + // bypassLookup makes every lookup a miss while store still records fresh entries. A resume sets it: + // its acknowledged parts are never read again, so their digests must come from the file as it is now. + bypassLookup bool } // loadHashCache reads the cache; a missing or unreadable file is an empty cache. @@ -62,24 +72,62 @@ func loadHashCache(stateDir string) *hashCache { return c } -func (c *hashCache) lookup(abs string, size int64, modTime time.Time, change int64) ([32]byte, bool) { +// lookup returns the file's digest and its part digests. An entry without a digest for every part of +// the format's layout for size is a miss, so a hit never needs another read of the file. +func (c *hashCache) lookup(abs string, size int64, modTime time.Time, change int64) ([32]byte, [][32]byte, bool) { + if c.bypassLookup { + return [32]byte{}, nil, false + } e, ok := c.entries[abs] if !ok || change == 0 || e.Size != size || e.ModTime != modTime.UnixNano() || e.Change != change { - return [32]byte{}, false + return [32]byte{}, nil, false + } + sum, ok := decodeDigest(e.SHA256) + if !ok { + return [32]byte{}, nil, false + } + layout, err := volumeformat.PlanLayout(size) + if err != nil { + return sum, nil, len(e.Parts) == 0 + } + if layout.PartCount == 1 { + return sum, [][32]byte{sum}, len(e.Parts) == 0 + } + if int64(len(e.Parts)) != layout.PartCount { + return [32]byte{}, nil, false + } + parts := make([][32]byte, len(e.Parts)) + for i, s := range e.Parts { + if parts[i], ok = decodeDigest(s); !ok { + return [32]byte{}, nil, false + } } - raw, err := hex.DecodeString(e.SHA256) + return sum, parts, true +} + +func decodeDigest(s string) ([32]byte, bool) { + raw, err := hex.DecodeString(s) if err != nil || len(raw) != sha256.Size { return [32]byte{}, false } return [32]byte(raw), true } -func (c *hashCache) store(abs string, size int64, modTime time.Time, change int64, sum [32]byte) { +// store remembers the file's digest and its part digests; a file of one part keeps only the file's. +func (c *hashCache) store(abs string, size int64, modTime time.Time, change int64, sum [32]byte, parts [][32]byte) { + var hexParts []string + if len(parts) > 1 { + hexParts = make([]string, len(parts)) + for i := range parts { + hexParts[i] = hex.EncodeToString(parts[i][:]) + } + } c.entries[abs] = cacheEntry{ Size: size, ModTime: modTime.UnixNano(), Change: change, SHA256: hex.EncodeToString(sum[:]), + Parts: hexParts, StoredAt: time.Now().UnixNano(), } c.dirty = true @@ -154,38 +202,41 @@ func writeFileAtomic(dir, name string, data []byte) error { return err } -// hashSources sets each source's digest from the cache or by reading the file. -func hashSources(ctx context.Context, sources []Source, cache *hashCache, p *progress, onHash func(string)) error { +// hashSources sets each source's digest and part digests from the cache or by reading the file once. +func (r *runner) hashSources(ctx context.Context, sources []Source, cache *hashCache) error { var total int64 for i := range sources { total += sources[i].Size } + p := r.progress p.begin("hashing", len(sources), total) defer p.end() buf := make([]byte, hashBufBytes) for i := range sources { s := &sources[i] - if sum, ok := cache.lookup(s.Abs, s.Size, s.ModTime, s.Change); ok { - s.SHA256 = sum + if sum, parts, ok := cache.lookup(s.Abs, s.Size, s.ModTime, s.Change); ok { + s.SHA256, s.Parts = sum, parts p.addBytes(s.Size) p.fileDone() continue } - if onHash != nil { - onHash(s.Abs) + if r.o.onHash != nil { + r.o.onHash(s.Abs) } - if err := hashFile(ctx, s, buf, p); err != nil { + if err := hashFile(ctx, s, buf, p, r.openSource); err != nil { return err } - cache.store(s.Abs, s.Size, s.ModTime, s.Change, s.SHA256) + cache.store(s.Abs, s.Size, s.ModTime, s.Change, s.SHA256, s.Parts) p.fileDone() } return nil } -// hashFile hashes the file in one read; a file that changes while it is read is an error. -func hashFile(ctx context.Context, s *Source, buf []byte, p *progress) error { - f, err := os.Open(s.Abs) +// hashFile hashes the file and each part of its layout in one read; a file that changes while it is +// read is an error. A size the format has no layout for gets no part digests: no layout is approved +// for it, so none of its parts is ever sent. +func hashFile(ctx context.Context, s *Source, buf []byte, p *progress, open func(string) (sourceFile, error)) error { + f, err := open(s.Abs) if err != nil { return fileErr(s.Abs, err) } @@ -194,9 +245,16 @@ func hashFile(ctx context.Context, s *Source, buf []byte, p *progress) error { if err != nil { return fileErr(s.Abs, err) } - change := changeTime(s.Abs, before) - h := sha256.New() - n, err := io.CopyBuffer(h, &hashReader{ + change := fileChangeTime(s.Abs, before) + whole := sha256.New() + var w io.Writer = whole + layout, layoutErr := volumeformat.PlanLayout(before.Size()) + var parts *partHasher + if layoutErr == nil && layout.PartCount > 1 { + parts = newPartHasher(layout) + w = io.MultiWriter(whole, parts) + } + n, err := io.CopyBuffer(w, &hashReader{ ctx: ctx, r: f, p: p, @@ -208,14 +266,62 @@ func hashFile(ctx context.Context, s *Source, buf []byte, p *progress) error { if err != nil { return fileErr(s.Abs, err) } - if n != before.Size() || after.Size() != before.Size() || !after.ModTime().Equal(before.ModTime()) || changeTime(s.Abs, after) != change { + if n != before.Size() || after.Size() != before.Size() || !after.ModTime().Equal(before.ModTime()) || fileChangeTime(s.Abs, after) != change { return fileErr(s.Abs, ErrSourceChanged) } s.Size, s.ModTime, s.Change = before.Size(), before.ModTime(), change - copy(s.SHA256[:], h.Sum(nil)) + copy(s.SHA256[:], whole.Sum(nil)) + switch { + case layoutErr != nil: + s.Parts = nil + case parts == nil: + s.Parts = [][32]byte{s.SHA256} + default: + s.Parts = parts.sums + } return nil } +// partHasher hashes what is written to it part by part, in the layout's parts, and keeps each part's +// digest. More bytes than the layout holds are a changed source. +type partHasher struct { + layout volumeformat.Layout + h hash.Hash + left int64 // bytes of the current part not yet written + sums [][32]byte +} + +func newPartHasher(l volumeformat.Layout) *partHasher { + return &partHasher{ + layout: l, + h: sha256.New(), + sums: make([][32]byte, 0, l.PartCount), + } +} + +func (ph *partHasher) Write(b []byte) (int, error) { + written := len(b) + for len(b) > 0 { + if ph.left == 0 { + next := int64(len(ph.sums)) + 1 + _, n, err := ph.layout.PlaintextRange(next) + if err != nil { + return 0, fmt.Errorf("%w: it grew while it was read", ErrSourceChanged) + } + ph.left = n + } + k := min(int64(len(b)), ph.left) + ph.h.Write(b[:k]) + ph.left -= k + b = b[k:] + if ph.left == 0 { + ph.sums = append(ph.sums, [32]byte(ph.h.Sum(nil))) + ph.h.Reset() + } + } + return written, nil +} + // hashReader reads under a context and counts the bytes for progress. type hashReader struct { ctx context.Context @@ -232,14 +338,42 @@ func (h *hashReader) Read(b []byte) (int, error) { return n, err } +// fileChangeTime is changeTime. Tests replace it to model a filesystem where a write does not move the +// change time. +var fileChangeTime = changeTime + // unchanged returns ErrSourceChanged when the file's size, modification time or change time moved since hashing. func unchanged(s *Source) error { info, err := os.Stat(s.Abs) if err != nil { return fileErr(s.Abs, fmt.Errorf("%w: %w", ErrSourceChanged, err)) } - if info.Size() != s.Size || !info.ModTime().Equal(s.ModTime) || changeTime(s.Abs, info) != s.Change { + if info.Size() != s.Size || !info.ModTime().Equal(s.ModTime) || fileChangeTime(s.Abs, info) != s.Change { return fileErr(s.Abs, ErrSourceChanged) } return nil } + +// sourceFile is a source file opened for reading. +type sourceFile interface { + io.Reader + io.ReaderAt + io.Closer + Stat() (os.FileInfo, error) +} + +// openSource opens a source file for reading, through the options' hook when one is set. +func (r *runner) openSource(path string) (sourceFile, error) { + if r.o.openSource != nil { + return r.o.openSource(path) + } + return openFile(path) +} + +func openFile(path string) (sourceFile, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + return f, nil +} diff --git a/internal/volumes/put/hashcache_test.go b/internal/volumes/put/hashcache_test.go index 671cd1de..9b67a853 100644 --- a/internal/volumes/put/hashcache_test.go +++ b/internal/volumes/put/hashcache_test.go @@ -17,30 +17,30 @@ func TestHashCacheKey(t *testing.T) { c := loadHashCache(t.TempDir()) mod := time.Date(2026, time.November, 16, 9, 0, 0, 123, time.UTC) sum := sha256.Sum256([]byte("content")) - c.store("/data/a.bin", 7, mod, 42, sum) + c.store("/data/a.bin", 7, mod, 42, sum, nil) - if got, ok := c.lookup("/data/a.bin", 7, mod, 42); !ok || got != sum { + if got, _, ok := c.lookup("/data/a.bin", 7, mod, 42); !ok || got != sum { t.Errorf("lookup of the same path, size and times = %x, %v", got, ok) } for name, miss := range map[string]func() bool{ - "another size": func() bool { _, ok := c.lookup("/data/a.bin", 8, mod, 42); return ok }, - "a later time": func() bool { _, ok := c.lookup("/data/a.bin", 7, mod.Add(time.Nanosecond), 42); return ok }, - "an earlier one": func() bool { _, ok := c.lookup("/data/a.bin", 7, mod.Add(-time.Second), 42); return ok }, - "another change time": func() bool { _, ok := c.lookup("/data/a.bin", 7, mod, 43); return ok }, - "another path": func() bool { _, ok := c.lookup("/data/b.bin", 7, mod, 42); return ok }, + "another size": func() bool { _, _, ok := c.lookup("/data/a.bin", 8, mod, 42); return ok }, + "a later time": func() bool { _, _, ok := c.lookup("/data/a.bin", 7, mod.Add(time.Nanosecond), 42); return ok }, + "an earlier one": func() bool { _, _, ok := c.lookup("/data/a.bin", 7, mod.Add(-time.Second), 42); return ok }, + "another change time": func() bool { _, _, ok := c.lookup("/data/a.bin", 7, mod, 43); return ok }, + "another path": func() bool { _, _, ok := c.lookup("/data/b.bin", 7, mod, 42); return ok }, } { if miss() { t.Errorf("the cache answered for %s", name) } } - c.store("/data/c.bin", 7, mod, 0, sum) - if _, ok := c.lookup("/data/c.bin", 7, mod, 0); ok { + c.store("/data/c.bin", 7, mod, 0, sum, nil) + if _, _, ok := c.lookup("/data/c.bin", 7, mod, 0); ok { t.Error("the cache answered for a file with no change time") } c.forget("/data/a.bin") - if _, ok := c.lookup("/data/a.bin", 7, mod, 42); ok { + if _, _, ok := c.lookup("/data/a.bin", 7, mod, 42); ok { t.Error("the cache answered for a forgotten file") } } @@ -50,16 +50,48 @@ func TestHashCacheRoundTrip(t *testing.T) { c := loadHashCache(dir) mod := time.Date(2026, time.November, 16, 9, 0, 0, 0, time.UTC) sum := sha256.Sum256([]byte("content")) - c.store("/data/a.bin", 7, mod, 42, sum) + c.store("/data/a.bin", 7, mod, 42, sum, nil) if err := c.save(); err != nil { t.Fatal(err) } - if got, ok := loadHashCache(dir).lookup("/data/a.bin", 7, mod, 42); !ok || got != sum { + if got, _, ok := loadHashCache(dir).lookup("/data/a.bin", 7, mod, 42); !ok || got != sum { t.Errorf("a saved entry reads back as %x, %v", got, ok) } } +// TestHashCacheBypassLookup: a cache that bypasses lookups answers for no file, but still records +// fresh entries and keeps the others. +func TestHashCacheBypassLookup(t *testing.T) { + dir := filepath.Join(t.TempDir(), "volumes") + c := loadHashCache(dir) + mod := time.Date(2026, time.November, 16, 9, 0, 0, 0, time.UTC) + sum := sha256.Sum256([]byte("content")) + c.store("/data/a.bin", 7, mod, 42, sum, nil) + if err := c.save(); err != nil { + t.Fatal(err) + } + + c = loadHashCache(dir) + c.bypassLookup = true + if _, _, ok := c.lookup("/data/a.bin", 7, mod, 42); ok { + t.Error("a cache that bypasses lookups answered") + } + fresh := sha256.Sum256([]byte("other content")) + c.store("/data/b.bin", 9, mod, 42, fresh, nil) + if err := c.save(); err != nil { + t.Fatal(err) + } + + reloaded := loadHashCache(dir) + if got, _, ok := reloaded.lookup("/data/a.bin", 7, mod, 42); !ok || got != sum { + t.Errorf("the earlier entry reads back as %x, %v", got, ok) + } + if got, _, ok := reloaded.lookup("/data/b.bin", 9, mod, 42); !ok || got != fresh { + t.Errorf("the fresh entry reads back as %x, %v", got, ok) + } +} + func TestHashCacheKeepsNewestEntriesWithinLimit(t *testing.T) { dir := t.TempDir() c := loadHashCache(dir) @@ -68,7 +100,7 @@ func TestHashCacheKeepsNewestEntriesWithinLimit(t *testing.T) { } mod := time.Unix(1, 0) want := sha256.Sum256([]byte("new content")) - c.store("/data/new.bin", 11, mod, 42, want) + c.store("/data/new.bin", 11, mod, 42, want, nil) if err := c.save(); err != nil { t.Fatal(err) } @@ -80,7 +112,7 @@ func TestHashCacheKeepsNewestEntriesWithinLimit(t *testing.T) { if _, ok := reloaded.entries["0"]; ok { t.Error("the oldest entry was not evicted") } - if got, ok := reloaded.lookup("/data/new.bin", 11, mod, 42); !ok || got != want { + if got, _, ok := reloaded.lookup("/data/new.bin", 11, mod, 42); !ok || got != want { t.Error("the most recently cached hash was lost") } } @@ -94,7 +126,7 @@ func TestHashCacheCorruptFileIsEmpty(t *testing.T) { if len(c.entries) != 0 { t.Fatalf("a corrupt cache holds %d entries", len(c.entries)) } - c.store("/data/a.bin", 1, time.Unix(1, 0), 1, [32]byte{1}) + c.store("/data/a.bin", 1, time.Unix(1, 0), 1, [32]byte{1}, nil) if err := c.save(); err != nil { t.Errorf("a corrupt cache could not be replaced: %v", err) } @@ -113,7 +145,7 @@ func TestPutChecksContentWhenSourceMetadataMatches(t *testing.T) { t.Skip("this filesystem does not report a change time for cache hits") } cache := loadHashCache(e.stateDir()) - cache.store(src.Abs, src.Size, src.ModTime, src.Change, sha256.Sum256([]byte("old bytes"))) + cache.store(src.Abs, src.Size, src.ModTime, src.Change, sha256.Sum256([]byte("old bytes")), nil) if err := cache.save(); err != nil { t.Fatal(err) } @@ -122,8 +154,8 @@ func TestPutChecksContentWhenSourceMetadataMatches(t *testing.T) { if !errors.Is(err, ErrSourceChanged) || !strings.Contains(err.Error(), name) { t.Fatalf("put error = %v, want ErrSourceChanged naming %s", err, name) } - if e.hashedCount() != 0 || len(e.cloud.putLog()) != 0 { - t.Error("put should use the cached hash and reject the changed content before sending the part") + if e.hashedCount() != 0 || okPuts(e, name, 1) != 0 { + t.Error("put should use the cached hash and reject the changed content before the part is acknowledged") } } @@ -133,7 +165,7 @@ func TestHashCacheFilePerms(t *testing.T) { } dir := filepath.Join(t.TempDir(), "volumes") c := loadHashCache(dir) - c.store("/data/a.bin", 1, time.Unix(1, 0), 1, [32]byte{1}) + c.store("/data/a.bin", 1, time.Unix(1, 0), 1, [32]byte{1}, nil) if err := c.save(); err != nil { t.Fatal(err) } @@ -164,7 +196,7 @@ func TestHashFileSetsDigestAndIdentity(t *testing.T) { Size: 1, } - if err := hashFile(t.Context(), &src, make([]byte, hashBufBytes), nil); err != nil { + if err := hashFile(t.Context(), &src, make([]byte, hashBufBytes), nil, openFile); err != nil { t.Fatal(err) } @@ -183,7 +215,7 @@ func TestHashFileHonorsContext(t *testing.T) { cancel() src := Source{Abs: file} - err := hashFile(ctx, &src, make([]byte, hashBufBytes), nil) + err := hashFile(ctx, &src, make([]byte, hashBufBytes), nil, openFile) if !errors.Is(err, context.Canceled) { t.Errorf("error = %v, want the cancellation", err) @@ -263,7 +295,7 @@ func TestHashFileRefusesAFileThatChangesWhileItIsRead(t *testing.T) { } src := Source{Abs: file} - err := hashFile(ctx, &src, make([]byte, hashBufBytes), nil) + err := hashFile(ctx, &src, make([]byte, hashBufBytes), nil, openFile) if !errors.Is(err, ErrSourceChanged) { t.Fatalf("error = %v, want ErrSourceChanged", err) diff --git a/internal/volumes/put/help.go b/internal/volumes/put/help.go index c0b56456..a28f7049 100644 --- a/internal/volumes/put/help.go +++ b/internal/volumes/put/help.go @@ -1,5 +1,7 @@ package put +import "github.com/runware/runware-cli/internal/config" + // Help text of volumes put: additive uploads, and no promise to delete. const ( escapingSymlinkAdvice = "remove the link or replace it with a copy of its target" @@ -8,6 +10,10 @@ const ( HelpLong = `Upload local files and directories to a Volume. +put needs your organization id. Copy it from the Runware console, then either set the +` + config.OrganizationFromEnvVar + ` environment variable or add the line "organization: " at the +top level of ~/.runware/config.yaml (config set cannot set it). + Uploads are additive. The paths you give are added to the Volume's latest files, or replace the file already at the same path; files you do not name stay as they are. A directory's files keep their paths relative to the directory, under --to when you give @@ -26,6 +32,9 @@ Content the organization already stores is never sent again, so repeating an upl that changes nothing sends no bytes. A file must not change while it uploads: if one does, put stops, names the file and publishes nothing. +put sends up to --concurrency parts at once, one connection each. Each part streams +from the file, so a part in flight holds about 1 MiB of memory. + If put is interrupted, run the same command again to continue the upload. Parts whose acknowledgements were saved are skipped. If a file changed, put aborts the saved upload. Run the command again to start a new session.` diff --git a/internal/volumes/put/part_digest_test.go b/internal/volumes/put/part_digest_test.go new file mode 100644 index 00000000..595bea1f --- /dev/null +++ b/internal/volumes/put/part_digest_test.go @@ -0,0 +1,409 @@ +package put + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sync" + "testing" + "time" + + "github.com/runware/runware-cli/pkg/volumeformat" +) + +// readCounter opens sources through countedFile and counts the bytes read from each, by base name. +// When flipAt is set, a positioned read of flipName returns the byte at that offset inverted, as a +// change after hashing that the file's size and times do not show. +type readCounter struct { + flipName string + flipAt int64 + + mu sync.Mutex + bytes map[string]int64 +} + +func newReadCounter() *readCounter { + return &readCounter{ + flipAt: -1, + bytes: map[string]int64{}, + } +} + +func (c *readCounter) open(path string) (sourceFile, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + return &countedFile{ + File: f, + counter: c, + name: filepath.Base(path), + }, nil +} + +func (c *readCounter) add(name string, n int) { + c.mu.Lock() + defer c.mu.Unlock() + c.bytes[name] += int64(n) +} + +func (c *readCounter) read(name string) int64 { + c.mu.Lock() + defer c.mu.Unlock() + return c.bytes[name] +} + +type countedFile struct { + *os.File + counter *readCounter + name string +} + +func (f *countedFile) Read(p []byte) (int, error) { + n, err := f.File.Read(p) + f.counter.add(f.name, n) + return n, err +} + +func (f *countedFile) ReadAt(p []byte, off int64) (int, error) { + n, err := f.File.ReadAt(p, off) + f.counter.add(f.name, n) + if f.name == f.counter.flipName && f.counter.flipAt >= off && f.counter.flipAt < off+int64(n) { + p[f.counter.flipAt-off] ^= 0xff + } + return n, err +} + +// smallName is the one-part file of resumeTree. +const smallName = "small.txt" + +// treeSizes is the size of each file of resumeTree. +var treeSizes = map[string]int64{ + bigName: twoPartSize, + smallName: 3000, +} + +// TestPutReadsEachFileTwice: hashing reads a file once for its digest and every part's digest, and +// the send reads each part once more; nothing else reads it. +func TestPutReadsEachFileTwice(t *testing.T) { + e := newTestEnv(t) + dir := resumeTree(t, e) + vol := e.cloud.newVolume("model-weights", "") + counter := newReadCounter() + opts := e.options(vol, dir) + opts.openSource = counter.open + + if _, err := Run(t.Context(), opts); err != nil { + t.Fatal(err) + } + + requireFiles(t, e, vol, expectedFiles(t, dir, "")) + for name, size := range treeSizes { + if got := counter.read(name); got != 2*size { + t.Errorf("%s: read %d bytes, want %d: once to hash it and once to send it", name, got, 2*size) + } + } +} + +// TestPutCacheHitReadsEachFileOnce: a cache entry with the part digests stands for the hashing read, +// so the file is read only to send it. +func TestPutCacheHitReadsEachFileOnce(t *testing.T) { + e := newTestEnv(t) + dir := resumeTree(t, e) + vol := e.cloud.newVolume("model-weights", "") + opts := e.options(vol, dir) + sources := cachedTree(t, opts) + counter := newReadCounter() + opts.openSource = counter.open + + if _, err := Run(t.Context(), opts); err != nil { + t.Fatal(err) + } + + if e.hashedCount() != 0 { + t.Errorf("%d files were hashed, want every one from the cache", e.hashedCount()) + } + requireFiles(t, e, vol, expectedFiles(t, dir, "")) + for name, size := range treeSizes { + if got := counter.read(name); got != size { + t.Errorf("%s: read %d bytes, want %d: only to send it", name, got, size) + } + } + for i := range sources { + src := &sources[i] + entry := loadHashCache(e.stateDir()).entries[src.Abs] + want := 0 // a one-part file keeps only the file's digest + if filepath.Base(src.Abs) == bigName { + want = 2 + } + if len(entry.Parts) != want { + t.Errorf("%s: the cache holds %d part digests, want %d", src.Target, len(entry.Parts), want) + } + } +} + +// TestPutOldCacheEntryIsAMiss: an entry saved before part digests were cached is a miss, so the file is +// hashed again rather than read a third time to find its part digests. +func TestPutOldCacheEntryIsAMiss(t *testing.T) { + e := newTestEnv(t) + dir := resumeTree(t, e) + vol := e.cloud.newVolume("model-weights", "") + opts := e.options(vol, dir) + sources := cachedTree(t, opts) + old := cacheFile{ + Version: 2, + Files: map[string]cacheEntry{}, + } + for i := range sources { + src := &sources[i] + old.Files[src.Abs] = cacheEntry{ + Size: src.Size, + ModTime: src.ModTime.UnixNano(), + Change: src.Change, + SHA256: hex.EncodeToString(src.SHA256[:]), + StoredAt: time.Now().UnixNano(), + } + } + data, err := json.Marshal(old) + if err != nil { + t.Fatal(err) + } + writeFile(t, filepath.Join(e.stateDir(), hashCacheFile), data) + counter := newReadCounter() + opts.openSource = counter.open + + if _, err := Run(t.Context(), opts); err != nil { + t.Fatal(err) + } + + if e.hashedCount() != len(sources) { + t.Errorf("%d files were hashed, want all %d: an old entry is a miss", e.hashedCount(), len(sources)) + } + requireFiles(t, e, vol, expectedFiles(t, dir, "")) + for name, size := range treeSizes { + if got := counter.read(name); got != 2*size { + t.Errorf("%s: read %d bytes, want %d", name, got, 2*size) + } + } +} + +// cachedTree hashes the put's sources into the hash cache, as an earlier put would, and returns them. +func cachedTree(t *testing.T, opts Options) []Source { + t.Helper() + sources, err := Walk(opts.Paths, opts.To) + if err != nil { + t.Fatal(err) + } + for i := range sources { + src := &sources[i] + if src.Change == 0 { + t.Skip("this filesystem does not report a change time for cache hits") + } + } + r, err := newRunner(opts) + if err != nil { + t.Fatal(err) + } + r.o.onHash = nil + cache := loadHashCache(r.stateDir) + if err := r.hashSources(t.Context(), sources, cache); err != nil { + t.Fatal(err) + } + if err := cache.save(); err != nil { + t.Fatal(err) + } + return sources +} + +// TestHashCacheNeedsEveryPartDigest: an entry for a file of several parts is a hit only with a digest +// for each part, and an entry for a one-part file answers the file's digest as its part's. +func TestHashCacheNeedsEveryPartDigest(t *testing.T) { + c := loadHashCache(t.TempDir()) + mod := time.Unix(1, 0) + sum := [32]byte{1} + parts := [][32]byte{{2}, {3}} + + c.store("/data/one.bin", 7, mod, 42, sum, [][32]byte{sum}) + if got, gotParts, ok := c.lookup("/data/one.bin", 7, mod, 42); !ok || got != sum || len(gotParts) != 1 || gotParts[0] != sum { + t.Errorf("a one-part entry reads back as %x, %x, %v", got, gotParts, ok) + } + c.store("/data/two.bin", twoPartSize, mod, 42, sum, parts) + if got, gotParts, ok := c.lookup("/data/two.bin", twoPartSize, mod, 42); !ok || got != sum || len(gotParts) != 2 || gotParts[0] != parts[0] || gotParts[1] != parts[1] { + t.Errorf("a two-part entry reads back as %x, %x, %v", got, gotParts, ok) + } + for name, entryParts := range map[string][]string{ + "no part digests": nil, + "too few part digests": {hex.EncodeToString(parts[0][:])}, + "a malformed digest": {hex.EncodeToString(parts[0][:]), "zz"}, + "too many part digests": {hex.EncodeToString(parts[0][:]), hex.EncodeToString(parts[1][:]), hex.EncodeToString(parts[1][:])}, + } { + e := c.entries["/data/two.bin"] + e.Parts = entryParts + c.entries["/data/three.bin"] = e + if _, _, ok := c.lookup("/data/three.bin", twoPartSize, mod, 42); ok { + t.Errorf("the cache answered for a two-part entry with %s", name) + } + } +} + +// TestHashFileDigestsEveryPart: hashing gives each part of the layout the digest of its bytes. +func TestHashFileDigestsEveryPart(t *testing.T) { + file := filepath.Join(t.TempDir(), bigName) + writeTwoPartFile(t, file) + src := Source{Abs: file} + + if err := hashFile(t.Context(), &src, make([]byte, hashBufBytes), nil, openFile); err != nil { + t.Fatal(err) + } + + content, err := os.ReadFile(file) //nolint:gosec // the test's own temporary file + if err != nil { + t.Fatal(err) + } + if len(src.Parts) != 2 || src.Parts[0] != sha256.Sum256(content[:firstPartSize]) || src.Parts[1] != sha256.Sum256(content[firstPartSize:]) { + t.Errorf("part digests = %x, want the digest of each part's bytes", src.Parts) + } + if src.SHA256 != sha256.Sum256(content) { + t.Error("the file's digest is not the digest of its bytes") + } +} + +// partChange is a byte of a part that differs when the part is sent. +type partChange struct { + name string + part int64 + at int64 // the file offset of the byte +} + +// TestChangeBetweenHashingAndSendNeverCompletesThePart: bytes that differ from those hashed when the +// part is sent, with the file's size and times unchanged, stop the part before its last segment is +// sealed: it is never acknowledged and the put aborts. +func TestChangeBetweenHashingAndSendNeverCompletesThePart(t *testing.T) { + for _, tc := range []partChange{ + { + name: "in the first part", + part: 1, + at: 10, + }, + { + name: "in the last part", + part: 2, + at: firstPartSize + 10, + }, + } { + t.Run(tc.name, func(t *testing.T) { + e := newTestEnv(t) + file := filepath.Join(e.srcDir, bigName) + writeTwoPartFile(t, file) + vol := e.cloud.newVolume("model-weights", "") + var rec sealRecorder + counter := newReadCounter() + counter.flipName, counter.flipAt = bigName, tc.at + opts := e.options(vol, file) + opts.Parallelism = 1 + opts.newSealer = rec.factory + opts.openSource = counter.open + + _, err := Run(t.Context(), opts) + + assertAborted(t, e, err, file, vol, 0) + resolved, evalErr := filepath.EvalSymlinks(file) + if evalErr != nil { + t.Fatal(evalErr) + } + want := fmt.Sprintf("%s: part %d no longer matches what was hashed, so nothing from this upload was published; run put again", resolved, tc.part) + if err.Error() != want { + t.Errorf("error = %q, want %q", err, want) + } + if okPuts(e, bigName, int(tc.part)) != 0 { + t.Errorf("part %d, which changed, was acknowledged", tc.part) + } + if e.cloud.count("complete-file") != 0 { + t.Error("the changed file was completed") + } + layout, err := volumeformat.PlanLayout(twoPartSize) + if err != nil { + t.Fatal(err) + } + segments, err := layout.SegmentsInPart(tc.part) + if err != nil { + t.Fatal(err) + } + sealed := 0 + for _, seal := range rec.all() { + if seal.part != tc.part { + continue + } + sealed++ + if int64(len(seal.segments)) == segments { + t.Errorf("the changed part %d was sealed to its last segment", tc.part) + } + } + if sealed == 0 { + t.Errorf("part %d was never sent, so the send's check was not reached", tc.part) + } + rec.requireSafe(t) + }) + } +} + +// statChange is a change to a file that moves its size or times. +type statChange struct { + name string + change func(t *testing.T, file string) +} + +// TestChangeBeforeTheLastPartStopsItBeforeItIsSent: before the last part of a file is journalled, the +// file's size and times are checked against hashing, so a file that grew, or whose modification time +// moved, after it was hashed never sends its last part, even when every part's bytes still match. +func TestChangeBeforeTheLastPartStopsItBeforeItIsSent(t *testing.T) { + for _, tc := range []statChange{ + { + name: "it grows by a byte", + change: func(t *testing.T, file string) { appendTo(t, file, []byte{0}) }, + }, + { + name: "its modification time moves", + change: func(t *testing.T, file string) { + later := time.Now().Add(5 * time.Second) + if err := os.Chtimes(file, later, later); err != nil { + t.Fatal(err) + } + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + e := newTestEnv(t) + file := filepath.Join(e.srcDir, bigName) + writeTwoPartFile(t, file) + vol := e.cloud.newVolume("model-weights", "") + var rec sealRecorder + opts := e.options(vol, file) + opts.Parallelism = 1 + opts.newSealer = rec.factory + // Declaration follows hashing and checks the file before it is sent, so the change lands + // after every check before the one for the last part. + e.cloud.onDeclare = func(FileDeclarations) { tc.change(t, file) } + + _, err := Run(t.Context(), opts) + + assertAborted(t, e, err, file, vol, 0) + for _, p := range e.cloud.putLog() { + if p.Part == 2 { + t.Errorf("the last part was sent (status %d) after the file changed", p.Status) + } + } + for _, seal := range rec.all() { + if seal.part == 2 { + t.Error("the last part was sealed after the file changed") + } + } + if e.cloud.count("complete-file") != 0 { + t.Error("the changed file was completed") + } + }) + } +} diff --git a/internal/volumes/put/part_retry_test.go b/internal/volumes/put/part_retry_test.go index 88da9c06..ce780f5a 100644 --- a/internal/volumes/put/part_retry_test.go +++ b/internal/volumes/put/part_retry_test.go @@ -2,8 +2,11 @@ package put import ( "context" + "crypto/sha256" "errors" "io" + "os" + "path/filepath" "testing" "testing/synctest" "time" @@ -11,6 +14,9 @@ import ( "github.com/runware/runware-cli/pkg/volumeformat" ) +// testAck is the acknowledgement the test transports answer a part with. +const testAck = "test-ack" + type stalledPartTransport struct { stall time.Duration starts []time.Time @@ -26,19 +32,30 @@ func (s *stalledPartTransport) PutPart(ctx context.Context, _ Target, _ io.Reade func sendTestPart(t *testing.T, tr Transport) (partResult, error) { t.Helper() - plain := []byte("test part") + r, f, digest := newTestPart(t, tr, []byte("test part")) + return r.sendPart(t.Context(), f, 1, digest) +} + +// newTestPart is a runner sending through tr and a one-part file of plain, with the part's digest. +func newTestPart(t *testing.T, tr Transport, plain []byte) (*runner, *fileState, [32]byte) { + t.Helper() + path := filepath.Join(t.TempDir(), "part.bin") + if err := os.WriteFile(path, plain, 0o600); err != nil { + t.Fatal(err) + } layout, err := volumeformat.PlanLayout(int64(len(plain))) if err != nil { t.Fatal(err) } expires := time.Now().Add(time.Hour) - r := runner{ + r := &runner{ tr: tr, now: time.Now, sleep: sleepContext, expiresAt: expires, } - f := fileState{ + f := &fileState{ + src: &Source{Abs: path}, key: &fakeFileKey{dataKey: make([]byte, 32)}, layout: layout, identity: volumeformat.FileIdentity{Size: uint64(len(plain))}, @@ -46,7 +63,7 @@ func sendTestPart(t *testing.T, tr Transport) (partResult, error) { 1: {ExpiresAt: expires}, }, } - return r.sendPart(t.Context(), &f, 1, plain) + return r, f, sha256.Sum256(plain) } func TestPartRetryTimeBudget(t *testing.T) { @@ -86,14 +103,14 @@ func (s *slowSuccessfulRetry) PutPart(ctx context.Context, _ Target, body io.Rea if _, err := io.Copy(io.Discard, body); err != nil { return "", err } - return "test-ack", nil + return testAck, nil } func TestPartRetryCanFinishAfterRetryWindow(t *testing.T) { synctest.Test(t, func(t *testing.T) { tr := &slowSuccessfulRetry{} result, err := sendTestPart(t, tr) - if err != nil || result.Ack != "test-ack" || tr.calls != 2 { + if err != nil || result.Ack != testAck || tr.calls != 2 { t.Errorf("ack = %q, error = %v, attempts = %d; want one successful slow retry", result.Ack, err, tr.calls) } }) diff --git a/internal/volumes/put/part_stream_test.go b/internal/volumes/put/part_stream_test.go new file mode 100644 index 00000000..fb3a3da4 --- /dev/null +++ b/internal/volumes/put/part_stream_test.go @@ -0,0 +1,176 @@ +package put + +import ( + "bytes" + "context" + "errors" + "io" + "path/filepath" + "runtime" + "sync" + "testing" + + "github.com/runware/runware-cli/pkg/volumeformat" +) + +// changingTransport changes the file once a part's body has yielded after bytes, reads the rest of +// the body as a transport would, and records how much of it there was. +type changingTransport struct { + after int64 + change func() + + mu sync.Mutex + calls int + read []int64 +} + +func (c *changingTransport) PutPart(_ context.Context, _ Target, body io.Reader, _ int64) (Secret, error) { + c.mu.Lock() + c.calls++ + first := c.calls == 1 + c.mu.Unlock() + n, err := io.CopyN(io.Discard, body, c.after) + if err == nil { + if first { + c.change() + } + var rest int64 + rest, err = io.Copy(io.Discard, body) + n += rest + } + c.mu.Lock() + c.read = append(c.read, n) + c.mu.Unlock() + if err != nil { + return "", err + } + return testAck, nil +} + +// TestChangeInsideAStreamingPartStopsBeforeItsLastSegment: bytes that change in a part while it +// streams fail the send before the part's last segment goes out, without a retry. +func TestChangeInsideAStreamingPartStopsBeforeItsLastSegment(t *testing.T) { + segments := int64(volumeformat.MinSegmentsPerPart) + plain := patterned(int(segments*volumeformat.SegmentPlaintextBytes), 3) + tr := &changingTransport{after: volumeformat.SaltBytes + 2*volumeformat.SegmentBytes} + r, f, digest := newTestPart(t, tr, plain) + tr.change = func() { patchFile(t, f.src.Abs, 40*volumeformat.SegmentPlaintextBytes, []byte("changed")) } + + _, err := r.sendPart(t.Context(), f, 1, digest) + + if !errors.Is(err, ErrSourceChanged) { + t.Fatalf("error = %v, want the changed source", err) + } + length, _ := f.layout.PartLength(1) + if want := length - volumeformat.SegmentBytes; tr.calls != 1 || len(tr.read) != 1 || tr.read[0] != want { + t.Errorf("%d sends read %v bytes, want one send of %d: every segment but the last", tr.calls, tr.read, want) + } +} + +// TestChangeInsideAStreamingPartAbortsThePut: a file changed while one of its parts streams is never +// acknowledged, and the put aborts and publishes nothing. +func TestChangeInsideAStreamingPartAbortsThePut(t *testing.T) { + e := newTestEnv(t) + file := filepath.Join(e.srcDir, "big.bin") + writeTwoPartFile(t, file) + vol := e.cloud.newVolume("model-weights", "") + var rec sealRecorder + var once sync.Once + opts := e.options(vol, file) + opts.Parallelism = 1 + opts.newSealer = rec.factory + opts.Transport = &partHook{ + Transport: opts.Transport, + after: volumeformat.SaltBytes + 2*volumeformat.SegmentBytes, + hook: func(part int) { + if part == 1 { + once.Do(func() { patchFile(t, file, 40*volumeformat.SegmentPlaintextBytes, []byte("changed")) }) + } + }, + } + + _, err := Run(t.Context(), opts) + + assertAborted(t, e, err, file, vol, 0) + if okPuts(e, "big.bin", 1) != 0 { + t.Error("the changed part was acknowledged") + } + for _, seal := range rec.firstParts(firstPartSize) { + if int64(len(seal.segments)) == volumeformat.MinSegmentsPerPart { + t.Error("the changed part's last segment was sealed") + } + } +} + +// partHook runs hook with the part number once the part's body has yielded after bytes. +type partHook struct { + Transport + after int64 + hook func(part int) +} + +func (h *partHook) PutPart(ctx context.Context, target Target, body io.Reader, length int64) (Secret, error) { + return h.Transport.PutPart(ctx, target, &hookedBody{ + r: body, + left: h.after, + fire: func() { h.hook(target.PartNumber) }, + fired: false, + }, length) +} + +type hookedBody struct { + r io.Reader + left int64 + fire func() + fired bool +} + +func (b *hookedBody) Read(p []byte) (int, error) { + if !b.fired && b.left <= 0 { + b.fired = true + b.fire() + } + if !b.fired { + p = p[:min(int64(len(p)), b.left)] + } + n, err := b.r.Read(p) + b.left -= int64(n) + return n, err +} + +// discardTransport reads every part body and acknowledges it. +type discardTransport struct{} + +func (discardTransport) PutPart(_ context.Context, _ Target, body io.Reader, _ int64) (Secret, error) { + if _, err := io.Copy(io.Discard, body); err != nil { + return "", err + } + return testAck, nil +} + +// TestPartInFlightHoldsAboutOneSegment: sending a part allocates about one segment of memory, the +// same for a part of one segment and for a full 64-segment part, rather than the part's plaintext. +func TestPartInFlightHoldsAboutOneSegment(t *testing.T) { + if testing.Short() { + t.Skip("sends a 64 MiB part") + } + var allocated [2]int64 + for i, segments := range []int{1, volumeformat.MinSegmentsPerPart} { + r, f, digest := newTestPart(t, discardTransport{}, bytes.Repeat([]byte{7}, segments*volumeformat.SegmentPlaintextBytes)) + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + if _, err := r.sendPart(t.Context(), f, 1, digest); err != nil { + t.Fatal(err) + } + runtime.ReadMemStats(&after) + allocated[i] = int64(after.TotalAlloc - before.TotalAlloc) + t.Logf("a part of %d segments allocated %d KiB", segments, allocated[i]>>10) + if allocated[i] > 2*volumeformat.SegmentBytes { + t.Errorf("a part of %d segments allocated %d bytes, want at most two segments", segments, allocated[i]) + } + } + if allocated[1] > allocated[0]+256<<10 { + t.Errorf("a 64-segment part allocated %d bytes, %d more than a one-segment part", allocated[1], allocated[1]-allocated[0]) + } +} diff --git a/internal/volumes/put/parts.go b/internal/volumes/put/parts.go index d0372e09..101098f6 100644 --- a/internal/volumes/put/parts.go +++ b/internal/volumes/put/parts.go @@ -1,15 +1,14 @@ package put import ( - "bytes" "context" "crypto/sha256" "encoding/hex" "errors" "fmt" + "hash" "io" "net/http" - "os" "sync" "sync/atomic" "time" @@ -83,10 +82,12 @@ func (f *fileState) acknowledgedBytes() int64 { return n } +// partJob is a part to send and the digest of its plaintext, taken when the file was hashed and +// journalled before the part goes out. type partJob struct { - file *fileState - part int - buf *partBuffer + file *fileState + part int + digest [32]byte } // failure keeps the first error of a group of goroutines and cancels the rest. @@ -102,40 +103,6 @@ func (f *failure) set(err error, cancel context.CancelFunc) { }) } -// partBuffer holds one part's plaintext from the read to the acknowledgement. -type partBuffer struct { - data []byte -} - -// bufferPool bounds the plaintext held in memory to a fixed number of part buffers. -type bufferPool struct { - free chan *partBuffer -} - -func newBufferPool(n int) *bufferPool { - p := &bufferPool{free: make(chan *partBuffer, n)} - for range n { - p.free <- &partBuffer{} - } - return p -} - -// get waits for a free buffer and sizes it to n bytes. -func (p *bufferPool) get(ctx context.Context, n int) (*partBuffer, error) { - select { - case b := <-p.free: - if cap(b.data) < n { - b.data = make([]byte, n) - } - b.data = b.data[:n] - return b, nil - case <-ctx.Done(): - return nil, context.Cause(ctx) - } -} - -func (p *bufferPool) put(b *partBuffer) { p.free <- b } - // uploadFiles sends the files' parts in parallel and completes each file after its last ack. func (r *runner) uploadFiles(ctx context.Context, todo []*fileState) error { if len(todo) == 0 { @@ -150,7 +117,7 @@ func (r *runner) uploadFiles(ctx context.Context, todo []*fileState) error { ctx, cancel := context.WithCancel(ctx) defer cancel() var fail failure - pool := newBufferPool(r.parallel + 1) + // Unbuffered, so the reader stays at most one part ahead of the senders. jobs := make(chan partJob) var wg sync.WaitGroup for range r.parallel { @@ -159,12 +126,11 @@ func (r *runner) uploadFiles(ctx context.Context, todo []*fileState) error { if err := r.transferPart(ctx, j); err != nil { fail.set(err, cancel) } - pool.put(j.buf) } }) } for _, f := range todo { - if err := r.feedFile(ctx, f, pool, jobs); err != nil { + if err := r.feedFile(ctx, f, jobs); err != nil { fail.set(err, cancel) break } @@ -180,42 +146,35 @@ func (r *runner) uploadFiles(ctx context.Context, todo []*fileState) error { return fail.err } -// feedFile reads a file part by part and checks its digest before the last part goes out. -func (r *runner) feedFile(ctx context.Context, f *fileState, pool *bufferPool, jobs chan<- partJob) error { - file, err := os.Open(f.src.Abs) - if err != nil { - return fileErr(f.src.Abs, fmt.Errorf("%w: %w", ErrSourceChanged, err)) - } - defer func() { _ = file.Close() }() - whole := sha256.New() +// feedFile journals each part's digest before the part is sent. The digests come from hashing, which +// read the file once and computed the file's digest from the same bytes, so feedFile reads nothing: +// the sender reads each part from the file and must find the bytes hashed for it, and a part whose +// bytes differ is never acknowledged. Before the last part it checks the file's size and times have +// not moved since hashing. +func (r *runner) feedFile(ctx context.Context, f *fileState, jobs chan<- partJob) error { last := int(f.layout.PartCount) + if len(f.src.Parts) != last { + return fileErr(f.src.Abs, fmt.Errorf("%d part digests for %d parts", len(f.src.Parts), last)) + } for part := 1; part <= last; part++ { - offset, n, err := f.layout.PlaintextRange(int64(part)) - if err != nil { - return fileErr(f.src.Abs, err) - } - buf, err := pool.get(ctx, int(n)) - if err != nil { + if err := context.Cause(ctx); err != nil { return err } - if err := readPart(file, offset, buf.data); err != nil { - pool.put(buf) + _, n, err := f.layout.PlaintextRange(int64(part)) + if err != nil { return fileErr(f.src.Abs, err) } - whole.Write(buf.data) if part == last { - if err := f.verifySource(whole.Sum(nil)); err != nil { - pool.put(buf) + if err := unchanged(f.src); err != nil { return err } } - digest := sha256.Sum256(buf.data) + digest := f.src.Parts[part-1] send, err := r.resumePart(f, part, digest) - if err != nil || !send { - pool.put(buf) - if err != nil { - return err - } + if err != nil { + return err + } + if !send { continue } if err := r.journal.logSync(partRecord{ @@ -225,46 +184,91 @@ func (r *runner) feedFile(ctx context.Context, f *fileState, pool *bufferPool, j SHA256: hex.EncodeToString(digest[:]), Length: n, }); err != nil { - pool.put(buf) return err } select { case jobs <- partJob{ - file: f, - part: part, - buf: buf, + file: f, + part: part, + digest: digest, }: case <-ctx.Done(): - pool.put(buf) return context.Cause(ctx) } } return r.resumeVerified(ctx, f) } -// readPart fills buf from the file at offset; a file that ends early has changed. -func readPart(file *os.File, offset int64, buf []byte) error { - _, err := io.ReadFull(io.NewSectionReader(file, offset, int64(len(buf))), buf) - if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) { - return fmt.Errorf("%w: it ended before byte %d", ErrSourceChanged, offset+int64(len(buf))) +// partSource reads a part's plaintext from the file for one send and hashes it on the way. Where the +// part ends it returns io.EOF only when the bytes match the digest journalled for the part, and +// ErrSourceChanged otherwise. The sealer seals the part's last segment only after that io.EOF, so a +// part whose bytes changed since they were journalled stops short and is never acknowledged. +type partSource struct { + r *io.SectionReader + h hash.Hash + digest [32]byte + part int + end int64 // the file offset where the part ends + left int64 // bytes of the part not yet read + err error // io.EOF once the part is read and matches, or what stopped it +} + +func newPartSource(file io.ReaderAt, part int, offset, n int64, digest [32]byte) *partSource { + return &partSource{ + r: io.NewSectionReader(file, offset, n), + h: sha256.New(), + digest: digest, + part: part, + end: offset + n, + left: n, } - return err } -// verifySource checks the digest of what was read and the file's size and time since hashing. -func (f *fileState) verifySource(sum []byte) error { - if !bytes.Equal(sum, f.src.SHA256[:]) { - return fileErr(f.src.Abs, ErrSourceChanged) +func (s *partSource) Read(p []byte) (int, error) { + if s.err != nil { + return 0, s.err + } + if s.left == 0 { + s.err = io.EOF + if [32]byte(s.h.Sum(nil)) != s.digest { + s.err = sourceChangedError{ + cause: fmt.Sprintf("part %d no longer matches what was hashed", s.part), + } + } + return 0, s.err + } + n, err := s.r.Read(p[:min(int64(len(p)), s.left)]) + s.h.Write(p[:n]) + s.left -= int64(n) + switch { + case errors.Is(err, io.EOF) && s.left > 0: + s.err = sourceChangedError{ + cause: fmt.Sprintf("the file is shorter than when it was hashed: part %d ends before byte %d", s.part, s.end), + } + case err != nil && !errors.Is(err, io.EOF): + s.err = err } - return unchanged(f.src) + return n, s.err +} + +// failure is the error that stopped the part's plaintext, or nil when none did. +func (s *partSource) failure() error { + if errors.Is(s.err, io.EOF) { + return nil + } + return s.err } // transferPart sends one part, records its ack and completes the file after its last part. func (r *runner) transferPart(ctx context.Context, j partJob) error { f := j.file - res, err := r.sendPart(ctx, f, j.part, j.buf.data) + res, err := r.sendPart(ctx, f, j.part, j.digest) if err != nil { - return fileErr(f.src.Abs, fmt.Errorf("part %d: %w", j.part, err)) + // A changed part names itself. + if _, ok := errors.AsType[sourceChangedError](err); !ok { + err = fmt.Errorf("part %d: %w", j.part, err) + } + return fileErr(f.src.Abs, err) } f.results[j.part-1] = res r.progress.addBytes(res.Len) @@ -284,8 +288,19 @@ func (r *runner) transferPart(ctx context.Context, j partJob) error { return nil } -// sendPart seals and sends one part: under a fresh salt on retry, with a renewed token when it expired. -func (r *runner) sendPart(ctx context.Context, f *fileState, part int, plain []byte) (partResult, error) { +// sendPart seals and sends one part, streaming its plaintext from the file: every attempt reads the +// part again from its offset and seals it under a fresh salt, with a renewed token when it expired. +// Bytes that differ from digest stop the attempt before the part's last segment and end the send. +func (r *runner) sendPart(ctx context.Context, f *fileState, part int, digest [32]byte) (partResult, error) { + offset, n, err := f.layout.PlaintextRange(int64(part)) + if err != nil { + return partResult{}, err + } + file, err := r.openSource(f.src.Abs) + if err != nil { + return partResult{}, fmt.Errorf("%w: %w", ErrSourceChanged, err) + } + defer func() { _ = file.Close() }() var failed Secret // The retry window limits when another attempt can start. retryCtx := ctx @@ -308,7 +323,8 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, plain []b if err != nil { return partResult{}, fmt.Errorf("seal the part: %w", err) } - body, err := sealer.Reader(plain) + src := newPartSource(file, part, offset, n, digest) + body, err := sealer.StreamReader(src) if err != nil { return partResult{}, fmt.Errorf("seal the part: %w", err) } @@ -321,6 +337,9 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, plain []b progress: r.progress, } ack, err := r.tr.PutPart(ctx, target, io.TeeReader(body, io.MultiWriter(crc, traffic)), sealer.Len()) + if srcErr := src.failure(); srcErr != nil { + return partResult{}, srcErr + } tokenExpired := errors.Is(err, ErrPartTokenExpired) switch { case err == nil: diff --git a/internal/volumes/put/put_test.go b/internal/volumes/put/put_test.go index de2c5e46..a11f90fe 100644 --- a/internal/volumes/put/put_test.go +++ b/internal/volumes/put/put_test.go @@ -12,6 +12,7 @@ import ( "slices" "strconv" "strings" + "sync" "testing" "time" @@ -19,6 +20,7 @@ import ( "github.com/runware/runware-cli/internal/config" "github.com/runware/runware-cli/internal/output" "github.com/runware/runware-cli/internal/volumes/keypair" + "github.com/runware/runware-cli/pkg/volumeformat" ) const testServerlessURL = "https://api.example.com" @@ -382,7 +384,7 @@ func TestPutRequiresOrganization(t *testing.T) { if strings.TrimSpace(org) == "" && !errors.Is(err, ErrNoOrganization) { t.Errorf("error = %v, want ErrNoOrganization", err) } - for _, want := range []string{config.OrganizationFromEnvVar, "organization", config.DefaultDashboardURL} { + for _, want := range []string{config.OrganizationFromEnvVar, `"organization: " at the top level of`, "config set cannot set it", config.DefaultDashboardURL} { if !strings.Contains(err.Error(), want) { t.Errorf("error %q does not mention %q", err, want) } @@ -727,21 +729,71 @@ func TestPutReusedFileChangedAborts(t *testing.T) { assertAborted(t, e, err, file, second, since) } -// AC 7: a file truncated during the upload is a changed file. +// truncationCase is when a file is truncated during the upload, and the cause its error gives. +type truncationCase struct { + name string + // whilePartSends truncates the file while its first part streams; otherwise it is truncated once + // the files are declared, before any part is sent. + whilePartSends bool + cause string +} + +// AC 7: a file truncated during the upload is a changed file. Truncated before its parts are sent, +// the check of its size finds it; truncated while a part streams, that part finds it short. func TestPutTruncatedDuringUploadAborts(t *testing.T) { - e := newTestEnv(t) - file := filepath.Join(e.srcDir, "big.bin") - writeTwoPartFile(t, file) - vol := e.cloud.newVolume("model-weights", "") - e.cloud.onDeclare = func(FileDeclarations) { - if err := os.Truncate(file, 1000); err != nil { - t.Error(err) - } - } + for _, tc := range []truncationCase{ + { + name: "before its parts are sent", + whilePartSends: false, + cause: "the file changed after it was hashed", + }, + { + name: "while a part is sent", + whilePartSends: true, + cause: fmt.Sprintf("the file is shorter than when it was hashed: part 1 ends before byte %d", firstPartSize), + }, + } { + t.Run(tc.name, func(t *testing.T) { + e := newTestEnv(t) + file := filepath.Join(e.srcDir, "big.bin") + writeTwoPartFile(t, file) + vol := e.cloud.newVolume("model-weights", "") + truncate := func() { + if err := os.Truncate(file, 1000); err != nil { + t.Error(err) + } + } + opts := e.options(vol, file) + // One part at a time, so the last part's size check cannot find the file first. + opts.Parallelism = 1 + if tc.whilePartSends { + var once sync.Once + opts.Transport = &partHook{ + Transport: opts.Transport, + after: volumeformat.SaltBytes + 2*volumeformat.SegmentBytes, + hook: func(part int) { + if part == 1 { + once.Do(truncate) + } + }, + } + } else { + e.cloud.onDeclare = func(FileDeclarations) { truncate() } + } - _, err := e.put(vol, file) + _, err := Run(t.Context(), opts) - assertAborted(t, e, err, file, vol, 0) + assertAborted(t, e, err, file, vol, 0) + resolved, evalErr := filepath.EvalSymlinks(file) + if evalErr != nil { + t.Fatal(evalErr) + } + want := resolved + ": " + tc.cause + ", so nothing from this upload was published; run put again" + if err.Error() != want { + t.Errorf("error = %q, want %q", err, want) + } + }) + } } func TestPutRechecksEverySourceBeforePublish(t *testing.T) { diff --git a/internal/volumes/put/resume.go b/internal/volumes/put/resume.go index 0290aa6b..b0e01662 100644 --- a/internal/volumes/put/resume.go +++ b/internal/volumes/put/resume.go @@ -18,7 +18,7 @@ import ( const unreadableStateAge = 25 * time.Hour // resumeFile is what feedFile needs to resume a file: the part digests journalled before, and whether -// the file's completion waits for feedFile's whole-file check. +// the file's completion waits for feedFile to check every part's digest against them. type resumeFile struct { digests map[int]string held bool @@ -45,8 +45,8 @@ func (p *resumePlan) clear() { // resumeCandidates releases locks on sessions that address other source paths. func (r *runner) resumeCandidates(saved []*savedSession, sources []Source) []*savedSession { targets := make(map[string]struct{}, len(sources)) - for _, src := range sources { - targets[src.Target] = struct{}{} + for i := range sources { + targets[sources[i].Target] = struct{}{} } var candidates []*savedSession for _, s := range saved { @@ -89,8 +89,11 @@ func (r *runner) resume(ctx context.Context, saved []*savedSession, sources []So if len(saved) == 0 { return false, Summary{}, nil } + // The resume trusts the digests of acknowledged parts without reading them, so every file is read + // once here: a cached digest could hide a write that moved neither the size nor the times. cache := loadHashCache(r.stateDir) - err := hashSources(ctx, sources, cache, r.progress, r.o.onHash) + cache.bypassLookup = true + err := r.hashSources(ctx, sources, cache) r.saveCache(cache) if err != nil { if file, ok := errors.AsType[*FileError](err); ok && errors.Is(err, os.ErrNotExist) { @@ -464,7 +467,7 @@ func (r *runner) continueSession(ctx context.Context, p *resumePlan, sources []S // restoreFile rebuilds an uploading file from its saved layout and acknowledgements and returns how many // parts were acknowledged. Its targets are renewed when its parts go out, and its completion waits for -// the whole-file check, since its last part may already be acknowledged. +// feedFile to check every part's digest, since its last part may already be acknowledged. func (r *runner) restoreFile(f *fileState, sf *savedFile) (int, error) { layout, err := checkLayout(f.src.Size, sf.declared.Layout) if err != nil { @@ -491,16 +494,18 @@ func (r *runner) restoreFile(f *fileState, sf *savedFile) (int, error) { return acked, nil } -// resumePart checks a part read for a resumed file against the digest journalled for it before: other -// bytes abort the session, since the file changed between a send and its retry. An acknowledged -// part with the same bytes is not sent again. +// resumePart checks a part's digest from hashing against the digest journalled for it before: another +// digest aborts the session, since the file changed between a send and its retry. An acknowledged +// part with the same digest is not sent again. func (r *runner) resumePart(f *fileState, part int, digest [32]byte) (bool, error) { rf := r.resumed[f.index] if rf == nil { return true, nil } if want, ok := rf.digests[part]; ok && want != hex.EncodeToString(digest[:]) { - return false, fileErr(f.src.Abs, fmt.Errorf("%w: part %d differs from the bytes read for it before", ErrSourceChanged, part)) + return false, fileErr(f.src.Abs, sourceChangedError{ + cause: fmt.Sprintf("part %d no longer matches what was hashed", part), + }) } if res := f.results[part-1]; res.Ack != "" { return false, nil @@ -508,8 +513,8 @@ func (r *runner) resumePart(f *fileState, part int, digest [32]byte) (bool, erro return true, nil } -// resumeVerified releases a resumed file's completion once feedFile has read all of it and its digest -// matched. +// resumeVerified releases a resumed file's completion once feedFile has checked every part's digest +// against the journal. func (r *runner) resumeVerified(ctx context.Context, f *fileState) error { rf := r.resumed[f.index] if rf == nil || !rf.held { diff --git a/internal/volumes/put/resume_test.go b/internal/volumes/put/resume_test.go index aee9cf37..d41ef7b7 100644 --- a/internal/volumes/put/resume_test.go +++ b/internal/volumes/put/resume_test.go @@ -4,9 +4,11 @@ import ( "bytes" "context" "crypto/sha256" + "encoding/hex" "encoding/json" "errors" "fmt" + "hash" "io" "io/fs" "log/slog" @@ -14,6 +16,7 @@ import ( "os" "path/filepath" "runtime" + "slices" "strings" "sync" "sync/atomic" @@ -53,6 +56,7 @@ func (s *sealRecorder) factory(dataKey []byte, id volumeformat.FileIdentity, l v rec: s, inner: inner, dataKey: bytes.Clone(dataKey), + layout: l, part: part, }, nil } @@ -61,42 +65,110 @@ type recordingSealer struct { rec *sealRecorder inner *volumeformat.PartSealer dataKey []byte + layout volumeformat.Layout part int64 } func (r *recordingSealer) Len() int64 { return r.inner.Len() } -// Reader records the sealing before any ciphertext exists, so a body that never fully goes out still counts. -func (r *recordingSealer) Reader(plaintext []byte) (io.Reader, error) { - body, err := r.inner.Reader(plaintext) +// StreamReader records the sealing when it starts, and each segment as soon as the format would seal +// it: once its plaintext is whole, and for the part's last segment once the plaintext has also ended. +// A segment the format refuses to seal, because its plaintext failed or changed, is not recorded. +func (r *recordingSealer) StreamReader(plaintext io.Reader) (io.Reader, error) { + _, n, err := r.layout.PlaintextRange(r.part) if err != nil { return nil, err } - var segments [][32]byte - for off := 0; off == 0 || off < len(plaintext); off += volumeformat.SegmentPlaintextBytes { - end := min(off+volumeformat.SegmentPlaintextBytes, len(plaintext)) - segments = append(segments, sha256.Sum256(plaintext[off:end])) - } - r.rec.add(sealRecord{ - dataKey: r.dataKey, - salt: r.inner.Salt(), - part: r.part, - size: len(plaintext), - segments: segments, + count, err := r.layout.SegmentsInPart(r.part) + if err != nil { + return nil, err + } + index := r.rec.add(sealRecord{ + dataKey: r.dataKey, + salt: r.inner.Salt(), + part: r.part, + size: int(n), + }) + return r.inner.StreamReader(&recordingPlaintext{ + r: plaintext, + rec: r.rec, + index: index, + size: n, + count: count, + h: sha256.New(), }) - return body, nil } -func (s *sealRecorder) add(rec sealRecord) { +// recordingPlaintext hashes the plaintext a sealer reads, segment by segment, into its sealing's record. +type recordingPlaintext struct { + r io.Reader + rec *sealRecorder + index int + size int64 // the part's plaintext bytes + count int64 // the part's segments + read int64 + seg int64 // the segment being read + h hash.Hash + last *[32]byte // the last segment's digest, recorded when the plaintext ends +} + +func (p *recordingPlaintext) Read(b []byte) (int, error) { + n, err := p.r.Read(b) + for chunk := b[:n]; len(chunk) > 0 && p.seg < p.count; { + end := min(p.size, (p.seg+1)*volumeformat.SegmentPlaintextBytes) + k := min(int64(len(chunk)), end-p.read) + p.h.Write(chunk[:k]) + p.read += k + chunk = chunk[k:] + if p.read == end { + p.segmentRead() + } + } + if p.size == 0 && p.seg == 0 && p.last == nil { + p.segmentRead() + } + if errors.Is(err, io.EOF) && p.last != nil { + p.rec.addSegment(p.index, *p.last) + p.last = nil + } + return n, err +} + +// segmentRead closes the segment being read: a segment before the last is sealed at once, the last +// only once the plaintext ends. +func (p *recordingPlaintext) segmentRead() { + sum := [32]byte(p.h.Sum(nil)) + p.h.Reset() + if p.seg == p.count-1 { + p.last = &sum + } else { + p.rec.addSegment(p.index, sum) + } + p.seg++ +} + +func (s *sealRecorder) add(rec sealRecord) int { s.mu.Lock() defer s.mu.Unlock() s.seals = append(s.seals, rec) + return len(s.seals) - 1 +} + +func (s *sealRecorder) addSegment(index int, digest [32]byte) { + s.mu.Lock() + defer s.mu.Unlock() + s.seals[index].segments = append(s.seals[index].segments, digest) } func (s *sealRecorder) all() []sealRecord { s.mu.Lock() defer s.mu.Unlock() - return append([]sealRecord(nil), s.seals...) + out := make([]sealRecord, len(s.seals)) + for i, rec := range s.seals { + rec.segments = slices.Clone(rec.segments) + out[i] = rec + } + return out } // violations lists every (key, nonce) pair that sealed two different plaintexts, and every part key used @@ -415,9 +487,10 @@ func TestResumeAbortsAChangedFileAndStartsOver(t *testing.T) { rec.requireSafe(t) } -// AC 2: a file changed between a failed send and its retry is not sealed again: the resumed put finds -// the part's bytes differ from the digest journalled before the send, and aborts the session. Nothing -// reaches the Volume, the state is gone, and the next put starts over. +// AC 2: a file changed between a failed send and its retry is never acknowledged: the resumed put's +// send finds the part's bytes differ from the digest journalled before the first send and stops before +// the part's last segment, or the size and time check before the last part stops it first. The session +// aborts, nothing reaches the Volume, the state is gone, and the next put starts over. func TestResumeAbortsWhenAPartChangedBeforeItsRetry(t *testing.T) { e := newTestEnv(t) dir := resumeTree(t, e) @@ -425,7 +498,9 @@ func TestResumeAbortsWhenAPartChangedBeforeItsRetry(t *testing.T) { var rec sealRecorder interruptedPut(t, e, resumeOptions(e, &rec, vol, dir), 1) big := filepath.Join(dir, bigName) - // A new file makes the resume declare, which happens after hashing and before any part is read. + interrupted := len(rec.firstParts(firstPartSize)) + accepted := okPuts(e, bigName, 1) + // A new file makes the resume declare, which happens after hashing and before any part is sent. writeFile(t, filepath.Join(dir, "new.txt"), patterned(100, 9)) e.cloud.mu.Lock() e.cloud.onDeclare = func(FileDeclarations) { patchFile(t, big, 10, []byte("changed")) } @@ -433,8 +508,12 @@ func TestResumeAbortsWhenAPartChangedBeforeItsRetry(t *testing.T) { _, err := Run(t.Context(), resumeOptions(e, &rec, vol, dir)) - if !errors.Is(err, ErrSourceChanged) || !strings.Contains(err.Error(), "part 1 differs") { - t.Fatalf("error = %v, want the changed part", err) + resolved, evalErr := filepath.EvalSymlinks(big) + if evalErr != nil { + t.Fatal(evalErr) + } + if !errors.Is(err, ErrSourceChanged) || !strings.Contains(err.Error(), resolved) { + t.Fatalf("error = %v, want the changed file", err) } if e.cloud.uploadState() != fakeAborted { t.Errorf("session state = %q, want aborted", e.cloud.uploadState()) @@ -445,8 +524,13 @@ func TestResumeAbortsWhenAPartChangedBeforeItsRetry(t *testing.T) { if dirs := e.uploadDirs(); len(dirs) != 0 { t.Errorf("resume state left after the abort: %v", dirs) } - if got := len(rec.firstParts(firstPartSize)); got != 1 { - t.Errorf("the first part was sealed %d times, want once: the changed bytes must not be sealed", got) + if okPuts(e, bigName, 1) != accepted { + t.Error("the changed first part was acknowledged") + } + for _, seal := range rec.firstParts(firstPartSize)[interrupted:] { + if int64(len(seal.segments)) == volumeformat.MinSegmentsPerPart { + t.Error("the changed first part's last segment was sealed") + } } e.cloud.mu.Lock() @@ -459,8 +543,104 @@ func TestResumeAbortsWhenAPartChangedBeforeItsRetry(t *testing.T) { rec.requireSafe(t) } -// AC 2: a retry inside one put seals the bytes it read, not the file as it is now. -func TestRetryResealsTheSameBytes(t *testing.T) { +// AC 2: a resume reads every file again rather than trusting the hash cache, so a write inside an +// acknowledged part that moves neither the size, the modification time nor the change time still aborts +// the saved session, and the stale part never reaches the Volume. +func TestResumeRehashesAFileTheCacheWouldTrust(t *testing.T) { + // A filesystem where a write does not move the change time. + defer func(saved func(string, fs.FileInfo) int64) { fileChangeTime = saved }(fileChangeTime) + fileChangeTime = func(string, fs.FileInfo) int64 { return 1 } + e := newTestEnv(t) + dir := resumeTree(t, e) + vol := e.cloud.newVolume("model-weights", "") + var rec sealRecorder + interruptedPut(t, e, resumeOptions(e, &rec, vol, dir), 2) + if okPuts(e, bigName, 1) != 1 { + t.Fatalf("before the resume: puts = %+v, want the first part acknowledged", e.cloud.putLog()) + } + big := filepath.Join(dir, bigName) + info, err := os.Stat(big) + if err != nil { + t.Fatal(err) + } + patchFile(t, big, 10, []byte("changed")) + if err := os.Chtimes(big, info.ModTime(), info.ModTime()); err != nil { + t.Fatal(err) + } + resolved, err := filepath.EvalSymlinks(big) + if err != nil { + t.Fatal(err) + } + opts := resumeOptions(e, &rec, vol, dir) + var hashed []string + opts.onHash = func(p string) { hashed = append(hashed, p) } + + _, err = Run(t.Context(), opts) + + if !errors.Is(err, ErrSourceChanged) || !strings.Contains(err.Error(), resolved) { + t.Fatalf("resume returned %v, want a source-change error naming %s", err, resolved) + } + if !slices.Contains(hashed, resolved) { + t.Errorf("hashed %v: the resume trusted the cached digest of %s", hashed, resolved) + } + if e.cloud.uploadState() != fakeAborted { + t.Errorf("session state = %q, want aborted", e.cloud.uploadState()) + } + if files, _ := e.cloud.latest(vol); len(files) != 0 { + t.Errorf("files = %v, want no publication after a source change", files) + } + if okPuts(e, bigName, 1) != 1 { + t.Errorf("puts = %+v, want the first part acknowledged once", e.cloud.putLog()) + } +} + +// AC 2: a resume compares each part's digest from hashing with the digest journalled before the part +// first went out, so a journalled digest that differs aborts the saved session before any part is sent +// again, even when the file's own digest still matches. +func TestResumeAbortsWhenAJournalledPartDigestDiffers(t *testing.T) { + e := newTestEnv(t) + dir := resumeTree(t, e) + vol := e.cloud.newVolume("model-weights", "") + var rec sealRecorder + interruptedPut(t, e, resumeOptions(e, &rec, vol, dir), 2) + other := sha256.Sum256([]byte("other bytes")) + edited := 0 + editJournal(t, e.configDir, func(r map[string]any) map[string]any { + if r["type"] == recordPart && r["part"] == float64(1) && r["length"] == float64(firstPartSize) { + r["sha256"] = hex.EncodeToString(other[:]) + edited++ + } + return r + }) + if edited != 1 { + t.Fatalf("edited %d part records, want the first part of %s", edited, bigName) + } + puts := len(e.cloud.putLog()) + resolved, err := filepath.EvalSymlinks(filepath.Join(dir, bigName)) + if err != nil { + t.Fatal(err) + } + + _, err = Run(t.Context(), resumeOptions(e, &rec, vol, dir)) + + want := resolved + ": part 1 no longer matches what was hashed, so nothing from this upload was published; run put again" + if !errors.Is(err, ErrSourceChanged) || err.Error() != want { + t.Fatalf("resume returned %q, want %q", err, want) + } + if e.cloud.uploadState() != fakeAborted { + t.Errorf("session state = %q, want aborted", e.cloud.uploadState()) + } + if files, _ := e.cloud.latest(vol); len(files) != 0 { + t.Errorf("files = %v, want no publication", files) + } + if sent := e.cloud.putLog()[puts:]; len(sent) != 0 { + t.Errorf("the resume sent %+v before it aborted", sent) + } +} + +// AC 2: a retry reads the part from the file again, and a part whose bytes changed since they were +// journalled stops before its last segment is sealed: the put fails and the changed bytes never go out. +func TestRetryOfAChangedPartFailsBeforeItCompletes(t *testing.T) { e := newTestEnv(t) content := patterned(5000, 1) file := singleFile(t, e, "weights.bin", content) @@ -479,23 +659,59 @@ func TestRetryResealsTheSameBytes(t *testing.T) { opts := e.options(vol, file) opts.newSealer = rec.factory - // The retry seals the bytes it read before; the check before publishing then sees the change. - if _, err := Run(t.Context(), opts); !errors.Is(err, ErrSourceChanged) { - t.Fatalf("error = %v, want the changed file refused before publishing", err) - } + _, err := Run(t.Context(), opts) + assertAborted(t, e, err, file, vol, 0) + if errors.Is(err, errUploadRetriesExhausted) { + t.Errorf("error = %v, want the change, not exhausted retries", err) + } seals := rec.firstParts(5000) - if len(seals) != 2 || bytes.Equal(seals[0].salt, seals[1].salt) || seals[0].segments[0] != seals[1].segments[0] { - t.Errorf("the retry must seal the same plaintext under a fresh salt") + if len(seals) != 2 || bytes.Equal(seals[0].salt, seals[1].salt) { + t.Fatalf("%d sealings, want the first send and one retry under a fresh salt", len(seals)) } - if files, _ := e.cloud.latest(vol); len(files) != 0 { - t.Errorf("published %+v, want nothing from an upload whose file changed", files) + if len(seals[0].segments) != 1 || seals[0].segments[0] != sha256.Sum256(content) || len(seals[1].segments) != 0 { + t.Errorf("sealed %d and %d segments, want the original bytes once and nothing of the changed part", len(seals[0].segments), len(seals[1].segments)) + } + if okPuts(e, "weights.bin", 1) != 0 { + t.Error("a part was acknowledged") } if naive := rec.requireSafe(t); naive != 0 { t.Errorf("%d segments sealed other plaintext under the same data key", naive) } } +// AC 2: a retry of an unchanged part reads it from the file again and seals the same plaintext, every +// segment of it, under a fresh salt. +func TestRetryResealsTheSameBytes(t *testing.T) { + e := newTestEnv(t) + size := 3*volumeformat.SegmentPlaintextBytes + 7 + file := singleFile(t, e, "weights.bin", patterned(size, 1)) + vol := e.cloud.newVolume("model-weights", "") + var rec sealRecorder + e.cloud.fault = func(rq partRequest) *fakeFault { + if rq.Attempt == 1 { + return &fakeFault{ + Status: 503, + Slug: slugPartStorageUnavailable, + } + } + return nil + } + opts := e.options(vol, file) + opts.newSealer = rec.factory + + if _, err := Run(t.Context(), opts); err != nil { + t.Fatal(err) + } + + seals := rec.firstParts(int64(size)) + if len(seals) != 2 || bytes.Equal(seals[0].salt, seals[1].salt) || len(seals[0].segments) != 4 || !slices.Equal(seals[0].segments, seals[1].segments) { + t.Fatal("the retry must seal every segment of the same plaintext under a fresh salt") + } + requireFiles(t, e, vol, expectedFiles(t, e.srcDir, "")) + rec.requireSafe(t) +} + // AC 3: resuming from a snapshot taken before a part was acknowledged seals that part again under a // fresh salt, so no key and nonce pair repeats, and the session still completes. func TestResumeFromRolledBackState(t *testing.T) { diff --git a/internal/volumes/put/run.go b/internal/volumes/put/run.go index 759bff2e..3743af94 100644 --- a/internal/volumes/put/run.go +++ b/internal/volumes/put/run.go @@ -23,9 +23,16 @@ import ( "github.com/runware/runware-cli/pkg/volumeformat" ) +// Parts in flight. Each one streams its plaintext from the file one segment at a +// time, so it holds about 1 MiB of memory however large the part is, and the +// default holds about 32 MiB of part data. The most is set by the connections +// it opens, one per part in flight, not by memory. +const ( + DefaultParallelism = 32 + MaxParallelism = 64 +) + const ( - defaultParallelism = 4 - maxParallelism = 16 maxDeclarationBatch = 100 keyPairAttempts = 5 maxUploadAttempts = 18 @@ -52,7 +59,7 @@ type Options struct { API API Keys Keys Transport Transport - Parallelism int // parts in flight; zero means four, and sixteen is the most + Parallelism int // parts in flight; zero means DefaultParallelism, and MaxParallelism is the most Progress io.Writer ProgressTTY bool // Progress is a terminal Logger *slog.Logger // debug events, such as a resumed or discarded session; nil logs nothing @@ -61,6 +68,7 @@ type Options struct { sleep func(context.Context, time.Duration) error tick <-chan time.Time onHash func(path string) + openSource func(path string) (sourceFile, error) progressEvery time.Duration newSealer sealerFactory } @@ -121,9 +129,9 @@ func newRunner(o Options) (*runner, error) { parallel: o.Parallelism, } if r.parallel <= 0 { - r.parallel = defaultParallelism + r.parallel = DefaultParallelism } - r.parallel = min(r.parallel, maxParallelism) + r.parallel = min(r.parallel, MaxParallelism) if r.now == nil { r.now = time.Now } @@ -164,7 +172,7 @@ func parseOrganization(s string) ([16]byte, error) { } func organizationHelp() string { - return fmt.Sprintf("set organization in %s or the %s environment variable, and copy the id from the Runware console (%s)", + return fmt.Sprintf("add the line \"organization: \" at the top level of %s (config set cannot set it), or set the %s environment variable; copy the id from the Runware console (%s)", config.ConfigPath(), config.OrganizationFromEnvVar, config.GetDashboardURL()) } @@ -203,7 +211,7 @@ func (r *runner) run(ctx context.Context) (Summary, error) { } defer sess.Clear() cache := loadHashCache(r.stateDir) - err = hashSources(ctx, sources, cache, r.progress, r.o.onHash) + err = r.hashSources(ctx, sources, cache) r.saveCache(cache) if err != nil { return Summary{}, err diff --git a/internal/volumes/put/sealer.go b/internal/volumes/put/sealer.go index eb35f87a..8d2d0bb8 100644 --- a/internal/volumes/put/sealer.go +++ b/internal/volumes/put/sealer.go @@ -6,9 +6,9 @@ import ( "github.com/runware/runware-cli/pkg/volumeformat" ) -// partSealer seals one plaintext of one part, as volumeformat.PartSealer does. +// partSealer seals one plaintext of one part, streamed from a reader, as volumeformat.PartSealer does. type partSealer interface { - Reader(plaintext []byte) (io.Reader, error) + StreamReader(plaintext io.Reader) (io.Reader, error) Len() int64 } diff --git a/internal/volumes/put/transport.go b/internal/volumes/put/transport.go index 63e092d1..67652531 100644 --- a/internal/volumes/put/transport.go +++ b/internal/volumes/put/transport.go @@ -70,7 +70,7 @@ func NewHTTPTransport(client *http.Client) *HTTPTransport { }).DialContext, // HTTP/2 would carry the parallel parts on one connection. ForceAttemptHTTP2: false, - MaxIdleConnsPerHost: maxParallelism, + MaxIdleConnsPerHost: MaxParallelism, TLSHandshakeTimeout: 15 * time.Second, // The endpoint answers once storage holds the part; a stalled answer is retried. ResponseHeaderTimeout: 2 * time.Minute, diff --git a/internal/volumes/put/transport_test.go b/internal/volumes/put/transport_test.go index de9758c2..360df1c0 100644 --- a/internal/volumes/put/transport_test.go +++ b/internal/volumes/put/transport_test.go @@ -233,7 +233,7 @@ type roundGate struct { // TestDefaultTransportKeepsAnHTTP1ConnectionPerPart sends the most parts the engine runs at once, twice, to a server that offers HTTP/2. func TestDefaultTransportKeepsAnHTTP1ConnectionPerPart(t *testing.T) { const rounds = 2 - parts := maxParallelism + parts := MaxParallelism seen := &connections{ protos: map[string]int{}, conns: map[string]struct{}{}, diff --git a/internal/volumes/put/walk.go b/internal/volumes/put/walk.go index 40ee81b6..52241721 100644 --- a/internal/volumes/put/walk.go +++ b/internal/volumes/put/walk.go @@ -36,13 +36,14 @@ var ( // Source is one local file to upload. type Source struct { - Abs string // the absolute path the file is read from, symlinks resolved - Target string // the file's path in the Volume - Size int64 // the size when it was hashed - ModTime time.Time // the modification time when it was hashed - Change int64 // the change time when it was hashed, in Unix nanoseconds; zero when it cannot be read - Mode uint32 // the Volume mode: the file's read and execute bits - SHA256 [32]byte // the plaintext digest, set by hashing + Abs string // the absolute path the file is read from, symlinks resolved + Target string // the file's path in the Volume + Size int64 // the size when it was hashed + ModTime time.Time // the modification time when it was hashed + Change int64 // the change time when it was hashed, in Unix nanoseconds; zero when it cannot be read + Mode uint32 // the Volume mode: the file's read and execute bits + SHA256 [32]byte // the plaintext digest, set by hashing + Parts [][32]byte // the plaintext digest of each part of the format's layout for Size, set by hashing } // Walk lists the files the paths name, sorted by Volume path, under the directory to when it is set. @@ -176,7 +177,7 @@ func newSource(abs, target string, info fs.FileInfo) (Source, error) { Target: target, Size: info.Size(), ModTime: info.ModTime(), - Change: changeTime(abs, info), + Change: fileChangeTime(abs, info), Mode: uint32(info.Mode().Perm() & modeMask), }, nil } diff --git a/pkg/volumeformat/part.go b/pkg/volumeformat/part.go index 20eff8c8..6a0840f8 100644 --- a/pkg/volumeformat/part.go +++ b/pkg/volumeformat/part.go @@ -194,7 +194,14 @@ func (s *PartSealer) start(plaintext []byte) error { func (s *PartSealer) sealSegment(dst []byte, i int64, plaintext []byte, scratch *[segmentAADBytes + 12]byte) []byte { off := i * SegmentPlaintextBytes n, _ := s.c.segmentLength(i) // cannot fail: callers pass 0 <= i < count - return s.c.aead.Seal(dst, nonce(scratch[segmentAADBytes:segmentAADBytes], i), plaintext[off:off+n], s.c.aad(scratch[:0], i)) + return s.sealOne(dst, i, plaintext[off:off+n], scratch) +} + +// sealOne appends sealed segment i, whose plaintext is segment. Every way of sealing a +// part ends here, so they all produce the same bytes. dst may be segment[:0], which +// seals in place. +func (s *PartSealer) sealOne(dst []byte, i int64, segment []byte, scratch *[segmentAADBytes + 12]byte) []byte { + return s.c.aead.Seal(dst, nonce(scratch[segmentAADBytes:segmentAADBytes], i), segment, s.c.aad(scratch[:0], i)) } // Seal returns the whole sealed part: the salt, then the part's sealed segments. The @@ -251,6 +258,90 @@ func (r *sealedPartReader) Read(p []byte) (int, error) { return n, nil } +// StreamReader returns the sealed part as a stream of exactly Len bytes, as Reader +// does, but reads the plaintext from plaintext as it goes, one segment at a time, so a +// part costs one segment of memory however large it is. The output is byte for byte +// what Seal and Reader return for the same plaintext and salt. +// +// plaintext must yield the part's range of the file (Layout.PlaintextRange) and then +// io.EOF. A segment is sealed only once its whole plaintext has been read, and the +// part's last segment only once plaintext has also returned io.EOF right after the +// part's last byte. A source that ends early stops the stream with +// io.ErrUnexpectedEOF, one that continues past the part with ErrLayout, one that keeps +// returning nothing with io.ErrNoProgress, and any other error from plaintext, even one +// returned with the part's last bytes, is returned as is; in every case the failing segment and those +// after it are never sealed, and every later Read returns the same error. A caller +// that checks the plaintext as it streams, such as its digest, can return its verdict +// in place of the final io.EOF, so a part whose plaintext changed is never complete. +// +// The sealer is spent when StreamReader returns, whatever plaintext then yields. +func (s *PartSealer) StreamReader(plaintext io.Reader) (io.Reader, error) { + if !s.used.CompareAndSwap(false, true) { + return nil, ErrSealerUsed + } + buf := make([]byte, 0, SegmentBytes) + return &streamedPartReader{ + s: s, + src: plaintext, + pending: append(buf, s.salt[:]...), + buf: buf, + }, nil +} + +type streamedPartReader struct { + s *PartSealer + src io.Reader + pending []byte // sealed bytes not yet read + buf []byte // backing array reused for every segment, sealed in place + next int64 // next segment to seal + err error // the error that stopped the stream, returned by every later Read + scratch [segmentAADBytes + 12]byte +} + +func (r *streamedPartReader) Read(p []byte) (int, error) { + if len(r.pending) == 0 { + if r.err != nil { + return 0, r.err + } + if r.next == r.s.c.count { + return 0, io.EOF + } + if err := r.seal(); err != nil { + r.err = err + return 0, err + } + } + n := copy(p, r.pending) + r.pending = r.pending[n:] + return n, nil +} + +// seal reads the next segment's plaintext, and seals it in place once it is whole +// (and, for the part's last segment, once the source has ended). +func (r *streamedPartReader) seal() error { + i := r.next + n, _ := r.s.c.segmentLength(i) // cannot fail: i < count + segment := r.buf[:n] + if err := readSegment(r.src, segment); err != nil { + if errors.Is(err, io.ErrUnexpectedEOF) { + return fmt.Errorf("volume format: part %d plaintext ends inside segment %d: %w", r.s.c.part, i, io.ErrUnexpectedEOF) + } + return err + } + if i == r.s.c.count-1 { + more, err := atEOF(r.src) + if err != nil { + return err + } + if more { + return fmt.Errorf("%w: part %d plaintext continues past the part", ErrLayout, r.s.c.part) + } + } + r.pending = r.s.sealOne(segment[:0], i, segment, &r.scratch) + r.next++ + return nil +} + // SealPart seals one 1-based part under a fresh random salt: NewPartSealer, then Seal. func SealPart(dataKey []byte, id FileIdentity, l Layout, part int64, plaintext []byte) ([]byte, error) { s, err := NewPartSealer(dataKey, id, l, part) @@ -394,20 +485,59 @@ func readExact(r io.Reader, b []byte, part, segment int64) error { // expectEOF refuses bytes after a part's last segment. func expectEOF(r io.Reader, part int64) error { + more, err := atEOF(r) + if more { + return fmt.Errorf("%w: part %d continues after its last segment", ErrAuthentication, part) + } + return err +} + +// readSegment fills segment from r as io.ReadFull does, with one difference: an error +// other than io.EOF that arrives in the same Read as the bytes completing segment is +// returned, where io.ReadFull drops it, so a verdict returned with the part's last +// bytes still stops the stream. A source that ends before segment is full returns +// io.ErrUnexpectedEOF. +func readSegment(r io.Reader, segment []byte) error { + got, empty := 0, 0 + for got < len(segment) { + n, err := r.Read(segment[got:]) + got += n + switch { + case errors.Is(err, io.EOF): + if got < len(segment) { + return io.ErrUnexpectedEOF + } + return nil + case err != nil: + return err + case n > 0: + empty = 0 + default: + if empty++; empty == maxEmptyReads { + return io.ErrNoProgress + } + } + } + return nil +} + +// atEOF reads one byte more from r: more is true when r has one, and err is nil when r +// reports io.EOF instead. Any other error is returned as is. +func atEOF(r io.Reader) (more bool, err error) { var one [1]byte for range maxEmptyReads { n, err := r.Read(one[:]) if n > 0 { - return fmt.Errorf("%w: part %d continues after its last segment", ErrAuthentication, part) + return true, nil } switch { case errors.Is(err, io.EOF): - return nil + return false, nil case err != nil: - return err + return false, err } } - return io.ErrNoProgress + return false, io.ErrNoProgress } // maxEmptyReads bounds how often a reader may return nothing and no error, as diff --git a/pkg/volumeformat/stream_test.go b/pkg/volumeformat/stream_test.go new file mode 100644 index 00000000..991db428 --- /dev/null +++ b/pkg/volumeformat/stream_test.go @@ -0,0 +1,391 @@ +package volumeformat + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "runtime" + "testing" + "testing/iotest" +) + +// TestStreamReaderMatchesSeal: the same part sealed under the same salt by Seal, by +// Reader and by StreamReader gives the same bytes, however the plaintext source and the +// consumer split their reads. +func TestStreamReaderMatchesSeal(t *testing.T) { + sizes := []int64{ + 0, + 1, + SegmentPlaintextBytes - 1, + SegmentPlaintextBytes, + SegmentPlaintextBytes + 1, + 3*SegmentPlaintextBytes + 7, + MinSegmentsPerPart * SegmentPlaintextBytes, + MinSegmentsPerPart*SegmentPlaintextBytes + 1, + } + for _, size := range sizes { + f := newFixture(t, size) + for part := int64(1); part <= f.layout.PartCount; part++ { + off, n, err := f.layout.PlaintextRange(part) + if err != nil { + t.Fatal(err) + } + plain := f.plain[off : off+n] + salt := [SaltBytes]byte{byte(size), byte(part), 7} + whole := sealWith(t, f, part, salt, func(s *PartSealer) (io.Reader, error) { + b, err := s.Seal(plain) + return bytes.NewReader(b), err + }) + fromSlice := sealWith(t, f, part, salt, func(s *PartSealer) (io.Reader, error) { return s.Reader(plain) }) + streamed := sealWith(t, f, part, salt, func(s *PartSealer) (io.Reader, error) { + return s.StreamReader(iotest.HalfReader(bytes.NewReader(plain))) + }) + if !bytes.Equal(whole, fromSlice) || !bytes.Equal(whole, streamed) { + t.Fatalf("size %d part %d: Seal, Reader and StreamReader differ", size, part) + } + if n <= 3*SegmentPlaintextBytes+7 { + oneByte := sealWith(t, f, part, salt, func(s *PartSealer) (io.Reader, error) { + r, err := s.StreamReader(iotest.OneByteReader(bytes.NewReader(plain))) + return iotest.OneByteReader(r), err + }) + if !bytes.Equal(whole, oneByte) { + t.Fatalf("size %d part %d: one-byte reads differ", size, part) + } + } + got, err := OpenPart(f.key, f.id, f.layout, part, streamed) + if err != nil || !bytes.Equal(got, plain) { + t.Fatalf("size %d part %d: the streamed part does not open: %v", size, part, err) + } + } + } +} + +// sealWith seals a part under a fixed salt through seal and returns every byte it yields. +func sealWith(t *testing.T, f fixture, part int64, salt [SaltBytes]byte, seal func(*PartSealer) (io.Reader, error)) []byte { + t.Helper() + s, err := newPartSealerWithSalt(f.key, f.id, f.layout, part, salt) + if err != nil { + t.Fatal(err) + } + r, err := seal(s) + if err != nil { + t.Fatal(err) + } + out, err := io.ReadAll(r) + if err != nil { + t.Fatal(err) + } + if int64(len(out)) != s.Len() { + t.Fatalf("part %d: %d bytes, Len %d", part, len(out), s.Len()) + } + return out +} + +// TestVectorStreamedParts: StreamReader reproduces every part of the golden vectors. +func TestVectorStreamedParts(t *testing.T) { + lv := loadVectors(t) + for _, f := range lv.file.Files { + c := lv.cases[f.Name] + for i, p := range f.Parts { + var salt [SaltBytes]byte + copy(salt[:], unhex(t, p.Salt)) + s, err := newPartSealerWithSalt(c.dataKey, c.identity, c.layout, p.PartNumber, salt) + if err != nil { + t.Fatal(err) + } + off, n, err := c.layout.PlaintextRange(p.PartNumber) + if err != nil { + t.Fatal(err) + } + r, err := s.StreamReader(bytes.NewReader(c.plain[off : off+n])) + if err != nil { + t.Fatal(err) + } + part, err := io.ReadAll(r) + if err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(part) + if int64(len(part)) != p.Length || hex.EncodeToString(sum[:]) != p.SHA256 || !bytes.Equal(part, c.parts[i]) { + t.Fatalf("%s part %d: streamed %d bytes, sha256 %x; want %d, %s", f.Name, p.PartNumber, len(part), sum, p.Length, p.SHA256) + } + if p.Ciphertext != "" && hex.EncodeToString(part) != p.Ciphertext { + t.Fatalf("%s part %d: streamed ciphertext differs from the vector", f.Name, p.PartNumber) + } + } + } +} + +var errVerdict = errors.New("the plaintext changed") + +// verdictWithLastBytes returns errVerdict in the same Read as the last bytes of plain, +// then io.EOF on every later Read: a source whose verdict is not sticky. +type verdictWithLastBytes struct { + plain []byte + done bool +} + +func (v *verdictWithLastBytes) Read(p []byte) (int, error) { + if v.done { + return 0, io.EOF + } + n := copy(p, v.plain) + v.plain = v.plain[n:] + if len(v.plain) > 0 { + return n, nil + } + v.done = true + return n, errVerdict +} + +// noProgress returns no bytes and no error on every Read. +type noProgress struct{} + +func (noProgress) Read([]byte) (int, error) { return 0, nil } + +type streamFailure struct { + name string + size int64 + source func(plain []byte) io.Reader + want error + sealed int64 // segments the stream yields before it stops +} + +// TestStreamReaderStopsBeforeTheFailingSegment: a source that ends early, runs past the +// part, fails, stalls, or returns a verdict in place of its final io.EOF or with its last +// bytes stops the stream before the failing segment is sealed, and the stream keeps +// returning that error. +func TestStreamReaderStopsBeforeTheFailingSegment(t *testing.T) { + const size = 3*SegmentPlaintextBytes + 7 + cases := []streamFailure{ + { + name: "ends early", + size: size, + source: func(plain []byte) io.Reader { return bytes.NewReader(plain[:len(plain)-1]) }, + want: io.ErrUnexpectedEOF, + sealed: 3, + }, + { + name: "ends at a segment boundary", + size: size, + source: func(plain []byte) io.Reader { return bytes.NewReader(plain[:2*SegmentPlaintextBytes]) }, + want: io.ErrUnexpectedEOF, + sealed: 2, + }, + { + name: "runs past the part", + size: size, + source: func(plain []byte) io.Reader { + return io.MultiReader(bytes.NewReader(plain), bytes.NewReader([]byte{0})) + }, + want: ErrLayout, + sealed: 3, + }, + { + name: "fails inside a segment", + size: size, + source: func(plain []byte) io.Reader { + return io.MultiReader(bytes.NewReader(plain[:SegmentPlaintextBytes+5]), errReader{errVerdict}) + }, + want: errVerdict, + sealed: 1, + }, + { + name: "returns a verdict in place of io.EOF", + size: size, + source: func(plain []byte) io.Reader { return io.MultiReader(bytes.NewReader(plain), errReader{errVerdict}) }, + want: errVerdict, + sealed: 3, + }, + { + name: "returns a verdict with its last bytes", + size: size, + source: func(plain []byte) io.Reader { return &verdictWithLastBytes{plain: plain} }, + want: errVerdict, + sealed: 3, + }, + { + name: "one segment with a verdict with its last bytes", + size: SegmentPlaintextBytes, + source: func(plain []byte) io.Reader { return &verdictWithLastBytes{plain: plain} }, + want: errVerdict, + sealed: 0, + }, + { + name: "returns nothing forever", + size: size, + source: func([]byte) io.Reader { return noProgress{} }, + want: io.ErrNoProgress, + sealed: 0, + }, + { + name: "empty part with a verdict", + size: 0, + source: func([]byte) io.Reader { return errReader{errVerdict} }, + want: errVerdict, + sealed: 0, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := newFixture(t, tc.size) + s, err := NewPartSealer(f.key, f.id, f.layout, 1) + if err != nil { + t.Fatal(err) + } + r, err := s.StreamReader(tc.source(f.plain)) + if err != nil { + t.Fatal(err) + } + out, err := io.ReadAll(r) + if !errors.Is(err, tc.want) { + t.Fatalf("error = %v, want %v", err, tc.want) + } + if want := SaltBytes + tc.sealed*SegmentBytes; int64(len(out)) != want { + t.Fatalf("yielded %d bytes, want %d: the salt and %d segments", len(out), want, tc.sealed) + } + if n, again := r.Read(make([]byte, 1)); n != 0 || !errors.Is(again, tc.want) { + t.Fatalf("a later read = %d, %v; want the same error", n, again) + } + o, err := NewPartOpener(f.key, f.id, f.layout, 1, out[:SaltBytes]) + if err != nil { + t.Fatal(err) + } + for i := range tc.sealed { + seg := out[SaltBytes+i*SegmentBytes : SaltBytes+(i+1)*SegmentBytes] + if _, err := o.OpenSegment(nil, i, seg); err != nil { + t.Fatalf("segment %d does not open: %v", i, err) + } + } + }) + } +} + +// TestStreamReaderSpendsTheSealer: StreamReader shares the sealer's single use with Seal +// and Reader, whatever the source then yields. +func TestStreamReaderSpendsTheSealer(t *testing.T) { + f := newFixture(t, 10) + s, err := NewPartSealer(f.key, f.id, f.layout, 1) + if err != nil { + t.Fatal(err) + } + if _, err := s.StreamReader(errReader{errVerdict}); err != nil { + t.Fatal(err) + } + if _, err := s.Seal(f.plain); !errors.Is(err, ErrSealerUsed) { + t.Fatalf("Seal after StreamReader: %v", err) + } + if _, err := s.StreamReader(bytes.NewReader(f.plain)); !errors.Is(err, ErrSealerUsed) { + t.Fatalf("second StreamReader: %v", err) + } + s, err = NewPartSealer(f.key, f.id, f.layout, 1) + if err != nil { + t.Fatal(err) + } + if _, err := s.Seal(f.plain); err != nil { + t.Fatal(err) + } + if _, err := s.StreamReader(bytes.NewReader(f.plain)); !errors.Is(err, ErrSealerUsed) { + t.Fatalf("StreamReader after Seal: %v", err) + } +} + +// zeros yields n zero bytes, then io.EOF, without allocating. +type zeros struct{ n int64 } + +func (z *zeros) Read(p []byte) (int, error) { + if z.n == 0 { + return 0, io.EOF + } + p = p[:min(int64(len(p)), z.n)] + clear(p) + z.n -= int64(len(p)) + return len(p), nil +} + +// writerOnly hides io.Discard's ReadFrom, so io.CopyBuffer reads through the given +// buffer instead of a pooled one of its own. +type writerOnly struct{ io.Writer } + +// streamAllocation streams part 1 of a file of size bytes and returns the bytes the +// sealing allocated on the heap. +func streamAllocation(t *testing.T, size int64) (allocated, plaintext int64) { + t.Helper() + l, err := PlanLayout(size) + if err != nil { + t.Fatal(err) + } + _, n, err := l.PlaintextRange(1) + if err != nil { + t.Fatal(err) + } + id := FileIdentity{Size: uint64(size)} + key := make([]byte, dataKeyBytes) + out := make([]byte, 32<<10) + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + s, err := NewPartSealer(key, id, l, 1) + if err != nil { + t.Fatal(err) + } + r, err := s.StreamReader(&zeros{n: n}) + if err != nil { + t.Fatal(err) + } + if _, err := io.CopyBuffer(writerOnly{io.Discard}, r, out); err != nil { + t.Fatal(err) + } + runtime.ReadMemStats(&after) + return int64(after.TotalAlloc - before.TotalAlloc), n +} + +// TestStreamReaderMemoryIsOneSegment: streaming a part allocates about one segment, +// whether the part holds one segment, the usual 64, or the 256 of a file of about +// 2.4 TiB. +func TestStreamReaderMemoryIsOneSegment(t *testing.T) { + if testing.Short() { + t.Skip("streams 256 MiB") + } + sizes := []int64{ + SegmentPlaintextBytes, + MinSegmentsPerPart * SegmentPlaintextBytes, + 256 * MaxParts * SegmentPlaintextBytes, + } + var smallest int64 + for i, size := range sizes { + allocated, plaintext := streamAllocation(t, size) + t.Logf("a part of %d KiB allocated %d KiB", plaintext>>10, allocated>>10) + if allocated > 2*SegmentBytes { + t.Errorf("a part of %d bytes allocated %d bytes, want at most two segments", plaintext, allocated) + } + if i == 0 { + smallest = allocated + } else if allocated > smallest+64<<10 { + t.Errorf("a part of %d bytes allocated %d bytes, %d more than a one-segment part", plaintext, allocated, allocated-smallest) + } + } +} + +// BenchmarkStreamPart streams one full 64-segment part from a reader; compare its +// allocations with BenchmarkSealPart, which needs the part's whole plaintext. +func BenchmarkStreamPart(b *testing.B) { + f := newFixture(b, MinSegmentsPerPart*SegmentPlaintextBytes) + b.SetBytes(f.layout.Size) + b.ReportAllocs() + for b.Loop() { + s, err := NewPartSealer(f.key, f.id, f.layout, 1) + if err != nil { + b.Fatal(err) + } + r, err := s.StreamReader(bytes.NewReader(f.plain)) + if err != nil { + b.Fatal(err) + } + if _, err := io.Copy(io.Discard, r); err != nil { + b.Fatal(err) + } + } +} From 30822f1abd8719478f066079fdbd33d3eb516b04 Mon Sep 17 00:00:00 2001 From: Emilio Del Tessandoro Date: Thu, 26 Nov 2026 17:19:53 +0100 Subject: [PATCH 2/7] fix(volumes): restart the part retry window after an attempt sends data A part's retry window ran from its first failed attempt. With many parts sharing a slow link, one attempt can take longer than the window, so two connection drops on one part suspended the upload. The window now starts again after every failed attempt that sent part of its body, so a part keeps retrying while its attempts move data. Attempts that send nothing still stop when the window passes, and attempts that fail at once still stop at the attempt limit. Add a test that a read error while a part streams stops put at once rather than being retried as a network failure, and hold the first part in the truncation test until the size check fails, so the test does not depend on which goroutine finds the short file first. --- internal/volumes/put/part_retry_test.go | 55 +++++++++++++++++ internal/volumes/put/part_stream_test.go | 75 ++++++++++++++++++++++++ internal/volumes/put/parts.go | 45 +++++++++----- internal/volumes/put/put_test.go | 21 +++++++ 4 files changed, 181 insertions(+), 15 deletions(-) diff --git a/internal/volumes/put/part_retry_test.go b/internal/volumes/put/part_retry_test.go index ce780f5a..1a931310 100644 --- a/internal/volumes/put/part_retry_test.go +++ b/internal/volumes/put/part_retry_test.go @@ -115,3 +115,58 @@ func TestPartRetryCanFinishAfterRetryWindow(t *testing.T) { } }) } + +// droppingTransport reads each part body in full, waits attemptTime and then fails the first drops +// attempts, as a connection that drops at the end of a slow send would. +type droppingTransport struct { + attemptTime time.Duration + drops int + calls int +} + +var errConnectionDropped = errors.New("the connection was reset") + +func (d *droppingTransport) PutPart(ctx context.Context, _ Target, body io.Reader, _ int64) (Secret, error) { + d.calls++ + if _, err := io.Copy(io.Discard, body); err != nil { + return "", err + } + if err := sleepContext(ctx, d.attemptTime); err != nil { + return "", err + } + if d.calls <= d.drops { + return "", errConnectionDropped + } + return testAck, nil +} + +// TestPartRetryWindowRestartsAfterSlowAttempts: attempts that each send for longer than the retry +// window, as one part does among many on a slow link, keep getting retries. +func TestPartRetryWindowRestartsAfterSlowAttempts(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + tr := &droppingTransport{ + attemptTime: 14 * time.Minute, + drops: 3, + calls: 0, + } + result, err := sendTestPart(t, tr) + if err != nil || result.Ack != testAck || tr.calls != 4 { + t.Errorf("ack = %q, error = %v, attempts = %d; want three retries, the last acknowledged", result.Ack, err, tr.calls) + } + }) +} + +// TestPartFastFailuresStopAtTheAttemptLimit: attempts that send the body and fail at once restart +// the retry window every time, and still stop at the attempt limit. +func TestPartFastFailuresStopAtTheAttemptLimit(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + tr := &droppingTransport{ + attemptTime: 0, + drops: 2 * maxUploadAttempts, + calls: 0, + } + if _, err := sendTestPart(t, tr); !errors.Is(err, errUploadRetriesExhausted) || tr.calls != maxUploadAttempts { + t.Errorf("error = %v after %d attempts, want retry exhaustion after %d", err, tr.calls, maxUploadAttempts) + } + }) +} diff --git a/internal/volumes/put/part_stream_test.go b/internal/volumes/put/part_stream_test.go index fb3a3da4..819c1bb7 100644 --- a/internal/volumes/put/part_stream_test.go +++ b/internal/volumes/put/part_stream_test.go @@ -5,9 +5,11 @@ import ( "context" "errors" "io" + "os" "path/filepath" "runtime" "sync" + "sync/atomic" "testing" "github.com/runware/runware-cli/pkg/volumeformat" @@ -174,3 +176,76 @@ func TestPartInFlightHoldsAboutOneSegment(t *testing.T) { t.Errorf("a 64-segment part allocated %d bytes, %d more than a one-segment part", allocated[1], allocated[1]-allocated[0]) } } + +var errDiskRead = errors.New("input/output error") + +// failingReadAt opens files whose ReadAt fails with errDiskRead past byte limit. Hashing reads with +// Read and is unaffected; the send reads each part with ReadAt. +type failingReadAt struct { + limit int64 +} + +func (o failingReadAt) open(path string) (sourceFile, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + return &failingFile{ + File: f, + limit: o.limit, + }, nil +} + +type failingFile struct { + *os.File + limit int64 +} + +func (f *failingFile) ReadAt(p []byte, off int64) (int, error) { + if off+int64(len(p)) <= f.limit { + return f.File.ReadAt(p, off) + } + n, err := f.File.ReadAt(p[:max(f.limit-off, 0)], off) + if err != nil { + return n, err + } + return n, errDiskRead +} + +// countingTransport counts the part sends. +type countingTransport struct { + Transport + calls atomic.Int64 +} + +func (c *countingTransport) PutPart(ctx context.Context, target Target, body io.Reader, length int64) (Secret, error) { + c.calls.Add(1) + return c.Transport.PutPart(ctx, target, body, length) +} + +// TestPutStopsAtAReadErrorOfAStreamingPart: an I/O error reading a part while it streams stops the +// put at once with that error, rather than being retried as a failure of the network. +func TestPutStopsAtAReadErrorOfAStreamingPart(t *testing.T) { + e := newTestEnv(t) + file := filepath.Join(e.srcDir, "data.bin") + writeFile(t, file, patterned(3*volumeformat.SegmentPlaintextBytes, 5)) + vol := e.cloud.newVolume("model-weights", "") + opts := e.options(vol, file) + failing := failingReadAt{ + limit: volumeformat.SegmentPlaintextBytes + 100, + } + opts.openSource = failing.open + tr := &countingTransport{ + Transport: opts.Transport, + } + opts.Transport = tr + + _, err := Run(t.Context(), opts) + + if !errors.Is(err, errDiskRead) || errors.Is(err, errUploadRetriesExhausted) { + t.Errorf("error = %v, want the read error", err) + } + if n := tr.calls.Load(); n != 1 { + t.Errorf("the part was sent %d times, want once", n) + } +} diff --git a/internal/volumes/put/parts.go b/internal/volumes/put/parts.go index 101098f6..b8224136 100644 --- a/internal/volumes/put/parts.go +++ b/internal/volumes/put/parts.go @@ -18,8 +18,14 @@ import ( ) const ( - maxRenewals = 3 - maxRenewParts = 128 + maxRenewals = 3 + maxRenewParts = 128 + // maxPartRetryTime bounds how long a part may keep failing without sending anything: no attempt + // starts once it has passed since the end of the part's last failed attempt that sent part of + // its body, or since its first failure when none did. One attempt on a slow link can take longer + // than the window, so a window that ran from the first failure would stop a part after one or + // two connection drops. Attempts that send a little and fail at once still stop at + // maxUploadAttempts. maxPartRetryTime = 5 * time.Minute ) @@ -302,7 +308,8 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, digest [3 } defer func() { _ = file.Close() }() var failed Secret - // The retry window limits when another attempt can start. + // The retry window limits when another attempt can start. It starts at the first failure and + // again after every failed attempt that sent part of its body. retryCtx := ctx var stopRetryTimer context.CancelFunc defer func() { @@ -332,7 +339,7 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, digest [3 if cause := context.Cause(retryCtx); cause != nil { return partResult{}, cause } - traffic := partTraffic{ + traffic := &partTraffic{ file: f, progress: r.progress, } @@ -340,16 +347,26 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, digest [3 if srcErr := src.failure(); srcErr != nil { return partResult{}, srcErr } - tokenExpired := errors.Is(err, ErrPartTokenExpired) - switch { - case err == nil: + if err == nil { return partResult{ Ack: ack, CRC: crc.Sum64(), Len: sealer.Len(), }, nil - case ctx.Err() != nil: + } + if ctx.Err() != nil { return partResult{}, context.Cause(ctx) + } + if stopRetryTimer == nil || traffic.sent.Load() > 0 { + if stopRetryTimer != nil { + stopRetryTimer() + } + retryWindow, cancel := context.WithTimeoutCause(ctx, maxPartRetryTime, errUploadRetriesExhausted) + stopRetryTimer = cancel + retryCtx = retryWindow + } + tokenExpired := errors.Is(err, ErrPartTokenExpired) + switch { case retryCtx.Err() != nil: return partResult{}, errors.Join(context.Cause(retryCtx), err) case tokenExpired: @@ -364,11 +381,6 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, digest [3 return partResult{}, fmt.Errorf("%w: %w", errUploadRetriesExhausted, err) } } - if stopRetryTimer == nil { - retryWindow, cancel := context.WithTimeoutCause(ctx, maxPartRetryTime, errUploadRetriesExhausted) - stopRetryTimer = cancel - retryCtx = retryWindow - } if !tokenExpired { if err := r.sleep(retryCtx, uploadBackoff(attempts)); err != nil { return partResult{}, err @@ -377,13 +389,16 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, digest [3 } } -// partTraffic counts ciphertext consumed by the transport on every attempt. +// partTraffic counts ciphertext consumed by the transport on one attempt, and adds it to the file's +// and the upload's totals. type partTraffic struct { file *fileState progress *progress + sent atomic.Int64 } -func (p partTraffic) Write(b []byte) (int, error) { +func (p *partTraffic) Write(b []byte) (int, error) { + p.sent.Add(int64(len(b))) p.file.sent.Add(int64(len(b))) p.progress.addSent(int64(len(b))) return len(b), nil diff --git a/internal/volumes/put/put_test.go b/internal/volumes/put/put_test.go index a11f90fe..4430e9a0 100644 --- a/internal/volumes/put/put_test.go +++ b/internal/volumes/put/put_test.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "maps" "os" "path/filepath" @@ -779,6 +780,12 @@ func TestPutTruncatedDuringUploadAborts(t *testing.T) { } } else { e.cloud.onDeclare = func(FileDeclarations) { truncate() } + // The part 1 worker could find the short file before the feeder checks the size for + // part 2, so part 1 waits until that check has failed and cancelled the put. + opts.Transport = &heldPart{ + Transport: opts.Transport, + part: 1, + } } _, err := Run(t.Context(), opts) @@ -796,6 +803,20 @@ func TestPutTruncatedDuringUploadAborts(t *testing.T) { } } +// heldPart holds the send of part until the put is cancelled, without reading its body. +type heldPart struct { + Transport + part int +} + +func (h *heldPart) PutPart(ctx context.Context, target Target, body io.Reader, length int64) (Secret, error) { + if target.PartNumber != h.part { + return h.Transport.PutPart(ctx, target, body, length) + } + <-ctx.Done() + return "", context.Cause(ctx) +} + func TestPutRechecksEverySourceBeforePublish(t *testing.T) { for _, firstReused := range []bool{false, true} { name := "uploaded" From aa07e59aae72ca38d03393e45ddd1a6b079e7b06 Mon Sep 17 00:00:00 2001 From: Emilio Del Tessandoro Date: Thu, 26 Nov 2026 21:23:39 +0100 Subject: [PATCH 3/7] fix(volumes): restart the part retry window only after real progress The transport counts the part bytes the HTTP client reads, and on a stalled link the client still fills its write buffer and the kernel's send buffer before it blocks. Each stalled attempt then looked like progress and restarted the retry window, so only the attempt limit stopped the part, after about 40 minutes. The window now starts again only after a failed attempt that sent more than 16 MiB, four times the default send buffer ceiling on Linux and macOS. Slow attempts that move a part's data keep their retries. Add a test where the first attempt sends the part and later attempts stall after sending nothing or a buffer's worth, and size the existing window tests' part above the new threshold. --- internal/volumes/put/part_retry_test.go | 70 ++++++++++++++++++++++++- internal/volumes/put/parts.go | 24 ++++++--- 2 files changed, 85 insertions(+), 9 deletions(-) diff --git a/internal/volumes/put/part_retry_test.go b/internal/volumes/put/part_retry_test.go index 1a931310..7c103fb2 100644 --- a/internal/volumes/put/part_retry_test.go +++ b/internal/volumes/put/part_retry_test.go @@ -4,6 +4,7 @@ import ( "context" "crypto/sha256" "errors" + "fmt" "io" "os" "path/filepath" @@ -36,6 +37,14 @@ func sendTestPart(t *testing.T, tr Transport) (partResult, error) { return r.sendPart(t.Context(), f, 1, digest) } +// sendLargeTestPart sends a part larger than maxBufferedPartBytes, so an attempt that sends all of +// it proves progress. +func sendLargeTestPart(t *testing.T, tr Transport) (partResult, error) { + t.Helper() + r, f, digest := newTestPart(t, tr, make([]byte, maxBufferedPartBytes+1<<20)) + return r.sendPart(t.Context(), f, 1, digest) +} + // newTestPart is a runner sending through tr and a one-part file of plain, with the part's digest. func newTestPart(t *testing.T, tr Transport, plain []byte) (*runner, *fileState, [32]byte) { t.Helper() @@ -149,7 +158,7 @@ func TestPartRetryWindowRestartsAfterSlowAttempts(t *testing.T) { drops: 3, calls: 0, } - result, err := sendTestPart(t, tr) + result, err := sendLargeTestPart(t, tr) if err != nil || result.Ack != testAck || tr.calls != 4 { t.Errorf("ack = %q, error = %v, attempts = %d; want three retries, the last acknowledged", result.Ack, err, tr.calls) } @@ -165,8 +174,65 @@ func TestPartFastFailuresStopAtTheAttemptLimit(t *testing.T) { drops: 2 * maxUploadAttempts, calls: 0, } - if _, err := sendTestPart(t, tr); !errors.Is(err, errUploadRetriesExhausted) || tr.calls != maxUploadAttempts { + if _, err := sendLargeTestPart(t, tr); !errors.Is(err, errUploadRetriesExhausted) || tr.calls != maxUploadAttempts { t.Errorf("error = %v after %d attempts, want retry exhaustion after %d", err, tr.calls, maxUploadAttempts) } }) } + +// bufferedStallTransport fails the first attempt after reading its body in full, then reads buffered +// bytes of each later body and stalls, as a link that stops moving data does while the client's +// buffers still take the start of every attempt. +type bufferedStallTransport struct { + buffered int64 + stall time.Duration + starts []time.Time + ends []time.Time +} + +func (b *bufferedStallTransport) PutPart(ctx context.Context, _ Target, body io.Reader, _ int64) (Secret, error) { + b.starts = append(b.starts, time.Now()) + defer func() { b.ends = append(b.ends, time.Now()) }() + if len(b.starts) == 1 { + if _, err := io.Copy(io.Discard, body); err != nil { + return "", err + } + return "", errConnectionDropped + } + if _, err := io.CopyN(io.Discard, body, b.buffered); err != nil { + return "", err + } + if err := sleepContext(ctx, b.stall); err != nil { + return "", err + } + return "", errPartStalled +} + +// TestPartStalledRetriesStopAtTheRetryWindow: after an attempt that sends the part and fails, attempts +// that stall having sent no more than the buffers hold do not restart the retry window, so the part +// stops within it rather than at the attempt limit. +func TestPartStalledRetriesStopAtTheRetryWindow(t *testing.T) { + for _, buffered := range []int64{0, maxBufferedPartBytes} { + t.Run(fmt.Sprintf("%d bytes buffered", buffered), func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + tr := &bufferedStallTransport{ + buffered: buffered, + stall: 2 * time.Minute, + starts: nil, + ends: nil, + } + if _, err := sendLargeTestPart(t, tr); !errors.Is(err, errUploadRetriesExhausted) { + t.Fatalf("error = %v, want retry exhaustion", err) + } + if len(tr.starts) < 3 { + t.Errorf("%d attempts, want the sent one and at least two stalled ones", len(tr.starts)) + } + for _, start := range tr.starts[1:] { + if late := start.Sub(tr.ends[0]); late > 5*time.Minute { + t.Errorf("started an attempt %v after the first one ended, want at most 5 minutes", late) + } + } + }) + }) + } +} diff --git a/internal/volumes/put/parts.go b/internal/volumes/put/parts.go index b8224136..70aaa3ac 100644 --- a/internal/volumes/put/parts.go +++ b/internal/volumes/put/parts.go @@ -20,13 +20,23 @@ import ( const ( maxRenewals = 3 maxRenewParts = 128 - // maxPartRetryTime bounds how long a part may keep failing without sending anything: no attempt - // starts once it has passed since the end of the part's last failed attempt that sent part of - // its body, or since its first failure when none did. One attempt on a slow link can take longer - // than the window, so a window that ran from the first failure would stop a part after one or - // two connection drops. Attempts that send a little and fail at once still stop at + // maxPartRetryTime bounds how long a part may keep failing without moving data: no attempt + // starts once it has passed since the end of the part's last failed attempt that sent more than + // maxBufferedPartBytes, or since its first failure when none did. One attempt on a slow link can + // take longer than the window, so a window that ran from the first failure would stop a part + // after one or two connection drops. Attempts that send a lot and fail at once still stop at // maxUploadAttempts. maxPartRetryTime = 5 * time.Minute + // maxBufferedPartBytes is how much of a part's body an attempt may hand to the connection without + // proving that any of it left the machine. The transport counts the bytes the HTTP client reads, + // and on a stalled link the client still fills its write buffer, the TLS record and the kernel's + // send buffer before it blocks, so a stalled attempt reads up to their sum. Send buffer + // autotuning stops at 4 MiB by default on Linux and macOS, and macOS caps any socket buffer at + // 8 MiB; the client's own buffers add tens of KiB. 16 MiB leaves room for a host tuned above + // those defaults. Restarting the window on any byte sent would let a stalled link retry until + // maxUploadAttempts, about 40 minutes. A part no larger than this, the last part of a file, + // never proves progress and keeps the window from its first failure. + maxBufferedPartBytes = 16 << 20 ) // partResult is an acknowledged part: its ack, ciphertext CRC and length. @@ -309,7 +319,7 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, digest [3 defer func() { _ = file.Close() }() var failed Secret // The retry window limits when another attempt can start. It starts at the first failure and - // again after every failed attempt that sent part of its body. + // again after every failed attempt that sent more than maxBufferedPartBytes. retryCtx := ctx var stopRetryTimer context.CancelFunc defer func() { @@ -357,7 +367,7 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, digest [3 if ctx.Err() != nil { return partResult{}, context.Cause(ctx) } - if stopRetryTimer == nil || traffic.sent.Load() > 0 { + if stopRetryTimer == nil || traffic.sent.Load() > maxBufferedPartBytes { if stopRetryTimer != nil { stopRetryTimer() } From e92bd481e05de7ea6477f86d3baa9004ed8da68e Mon Sep 17 00:00:00 2001 From: Emilio Del Tessandoro Date: Thu, 26 Nov 2026 21:45:01 +0100 Subject: [PATCH 4/7] test(volumes): keep the part retry window tests small The window tests sent parts above the 16 MiB progress threshold, up to 18 attempts of 17 MiB each under the race detector, which pushed the package past the CI test timeout. The threshold is now a variable the tests lower to 4 KiB, so their parts are 8 KiB; the production value stays 16 MiB. --- internal/volumes/put/part_retry_test.go | 13 +++++++++---- internal/volumes/put/parts.go | 5 ++++- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/internal/volumes/put/part_retry_test.go b/internal/volumes/put/part_retry_test.go index 7c103fb2..47171a54 100644 --- a/internal/volumes/put/part_retry_test.go +++ b/internal/volumes/put/part_retry_test.go @@ -37,11 +37,16 @@ func sendTestPart(t *testing.T, tr Transport) (partResult, error) { return r.sendPart(t.Context(), f, 1, digest) } -// sendLargeTestPart sends a part larger than maxBufferedPartBytes, so an attempt that sends all of -// it proves progress. +// testBufferedPartBytes stands in for maxBufferedPartBytes, so a part that proves progress is small. +const testBufferedPartBytes = 4 << 10 + +// sendLargeTestPart lowers bufferedPartBytes to testBufferedPartBytes for the test and sends a part +// larger than that, so an attempt that sends all of it proves progress. func sendLargeTestPart(t *testing.T, tr Transport) (partResult, error) { t.Helper() - r, f, digest := newTestPart(t, tr, make([]byte, maxBufferedPartBytes+1<<20)) + bufferedPartBytes = testBufferedPartBytes + t.Cleanup(func() { bufferedPartBytes = maxBufferedPartBytes }) + r, f, digest := newTestPart(t, tr, make([]byte, 2*testBufferedPartBytes)) return r.sendPart(t.Context(), f, 1, digest) } @@ -212,7 +217,7 @@ func (b *bufferedStallTransport) PutPart(ctx context.Context, _ Target, body io. // that stall having sent no more than the buffers hold do not restart the retry window, so the part // stops within it rather than at the attempt limit. func TestPartStalledRetriesStopAtTheRetryWindow(t *testing.T) { - for _, buffered := range []int64{0, maxBufferedPartBytes} { + for _, buffered := range []int64{0, testBufferedPartBytes} { t.Run(fmt.Sprintf("%d bytes buffered", buffered), func(t *testing.T) { synctest.Test(t, func(t *testing.T) { tr := &bufferedStallTransport{ diff --git a/internal/volumes/put/parts.go b/internal/volumes/put/parts.go index 70aaa3ac..df9a7294 100644 --- a/internal/volumes/put/parts.go +++ b/internal/volumes/put/parts.go @@ -39,6 +39,9 @@ const ( maxBufferedPartBytes = 16 << 20 ) +// bufferedPartBytes is maxBufferedPartBytes; tests lower it so their parts stay small. +var bufferedPartBytes = int64(maxBufferedPartBytes) + // partResult is an acknowledged part: its ack, ciphertext CRC and length. type partResult struct { Ack Secret @@ -367,7 +370,7 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, digest [3 if ctx.Err() != nil { return partResult{}, context.Cause(ctx) } - if stopRetryTimer == nil || traffic.sent.Load() > maxBufferedPartBytes { + if stopRetryTimer == nil || traffic.sent.Load() > bufferedPartBytes { if stopRetryTimer != nil { stopRetryTimer() } From 4476b03dd9482b0c421181e81b01a2a76c51555c Mon Sep 17 00:00:00 2001 From: Emilio Del Tessandoro Date: Fri, 27 Nov 2026 10:13:35 +0100 Subject: [PATCH 5/7] test(volumes): check the part progress threshold at its production value Every retry window test lowered the 16 MiB progress threshold to 4 KiB, so the package passed with the threshold at zero, which lets a stalled link retry a part until the attempt limit. The stall test now also runs at the production threshold with an attempt that stalls after 16 MiB, and a new test drops attempts after 17 MiB of an 18 MiB part, which must restart the window because the part's data moved. The threshold is a runner field, zero meaning the production value, instead of a package variable the tests write, so a parallel test cannot race on it. --- internal/volumes/put/part_retry_test.go | 61 +++++++++++++++++++++---- internal/volumes/put/parts.go | 6 +-- internal/volumes/put/run.go | 1 + 3 files changed, 54 insertions(+), 14 deletions(-) diff --git a/internal/volumes/put/part_retry_test.go b/internal/volumes/put/part_retry_test.go index 47171a54..caabb331 100644 --- a/internal/volumes/put/part_retry_test.go +++ b/internal/volumes/put/part_retry_test.go @@ -40,13 +40,19 @@ func sendTestPart(t *testing.T, tr Transport) (partResult, error) { // testBufferedPartBytes stands in for maxBufferedPartBytes, so a part that proves progress is small. const testBufferedPartBytes = 4 << 10 -// sendLargeTestPart lowers bufferedPartBytes to testBufferedPartBytes for the test and sends a part -// larger than that, so an attempt that sends all of it proves progress. +// sendLargeTestPart sends a part of twice testBufferedPartBytes with the runner's threshold lowered +// to testBufferedPartBytes, so an attempt that sends all of it proves progress. func sendLargeTestPart(t *testing.T, tr Transport) (partResult, error) { t.Helper() - bufferedPartBytes = testBufferedPartBytes - t.Cleanup(func() { bufferedPartBytes = maxBufferedPartBytes }) - r, f, digest := newTestPart(t, tr, make([]byte, 2*testBufferedPartBytes)) + return sendSizedTestPart(t, tr, 2*testBufferedPartBytes, testBufferedPartBytes) +} + +// sendSizedTestPart sends a part of size bytes with the runner threshold at buffered, or at +// maxBufferedPartBytes when buffered is zero. +func sendSizedTestPart(t *testing.T, tr Transport, size int, buffered int64) (partResult, error) { + t.Helper() + r, f, digest := newTestPart(t, tr, make([]byte, size)) + r.bufferedPartBytes = buffered return r.sendPart(t.Context(), f, 1, digest) } @@ -131,10 +137,12 @@ func TestPartRetryCanFinishAfterRetryWindow(t *testing.T) { } // droppingTransport reads each part body in full, waits attemptTime and then fails the first drops -// attempts, as a connection that drops at the end of a slow send would. +// attempts, as a connection that drops at the end of a slow send would. With partial set, a failing +// attempt reads only that many bytes of the body first. type droppingTransport struct { attemptTime time.Duration drops int + partial int64 calls int } @@ -142,6 +150,9 @@ var errConnectionDropped = errors.New("the connection was reset") func (d *droppingTransport) PutPart(ctx context.Context, _ Target, body io.Reader, _ int64) (Secret, error) { d.calls++ + if d.calls <= d.drops && d.partial > 0 { + body = io.LimitReader(body, d.partial) + } if _, err := io.Copy(io.Discard, body); err != nil { return "", err } @@ -170,6 +181,24 @@ func TestPartRetryWindowRestartsAfterSlowAttempts(t *testing.T) { }) } +// TestPartRetryWindowRestartsAfterAPartialSend: a connection that drops partway through a large +// part, after sending 17 MiB of 18, more than the production threshold but less than the part, +// restarts the retry window, so slow attempts that each drop before the end keep getting retries. +func TestPartRetryWindowRestartsAfterAPartialSend(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + tr := &droppingTransport{ + attemptTime: 6 * time.Minute, + drops: 2, + partial: 17 << 20, + calls: 0, + } + result, err := sendSizedTestPart(t, tr, 18<<20, 0) + if err != nil || result.Ack != testAck || tr.calls != 3 { + t.Errorf("ack = %q, error = %v, attempts = %d; want two retries, the last acknowledged", result.Ack, err, tr.calls) + } + }) +} + // TestPartFastFailuresStopAtTheAttemptLimit: attempts that send the body and fail at once restart // the retry window every time, and still stop at the attempt limit. func TestPartFastFailuresStopAtTheAttemptLimit(t *testing.T) { @@ -216,17 +245,29 @@ func (b *bufferedStallTransport) PutPart(ctx context.Context, _ Target, body io. // TestPartStalledRetriesStopAtTheRetryWindow: after an attempt that sends the part and fails, attempts // that stall having sent no more than the buffers hold do not restart the retry window, so the part // stops within it rather than at the attempt limit. +// +// The last case keeps the production threshold and stalls after 16 MiB, written as a literal so +// that lowering maxBufferedPartBytes below the send buffers it is sized for fails the test. func TestPartStalledRetriesStopAtTheRetryWindow(t *testing.T) { - for _, buffered := range []int64{0, testBufferedPartBytes} { - t.Run(fmt.Sprintf("%d bytes buffered", buffered), func(t *testing.T) { + cases := []struct { + threshold int64 // the runner's threshold; zero is maxBufferedPartBytes + buffered int64 // bytes each stalled attempt sends + size int + }{ + {threshold: testBufferedPartBytes, buffered: 0, size: 2 * testBufferedPartBytes}, + {threshold: testBufferedPartBytes, buffered: testBufferedPartBytes, size: 2 * testBufferedPartBytes}, + {threshold: 0, buffered: 16 << 20, size: 17 << 20}, + } + for _, c := range cases { + t.Run(fmt.Sprintf("%d of %d bytes buffered", c.buffered, c.size), func(t *testing.T) { synctest.Test(t, func(t *testing.T) { tr := &bufferedStallTransport{ - buffered: buffered, + buffered: c.buffered, stall: 2 * time.Minute, starts: nil, ends: nil, } - if _, err := sendLargeTestPart(t, tr); !errors.Is(err, errUploadRetriesExhausted) { + if _, err := sendSizedTestPart(t, tr, c.size, c.threshold); !errors.Is(err, errUploadRetriesExhausted) { t.Fatalf("error = %v, want retry exhaustion", err) } if len(tr.starts) < 3 { diff --git a/internal/volumes/put/parts.go b/internal/volumes/put/parts.go index df9a7294..6461a9df 100644 --- a/internal/volumes/put/parts.go +++ b/internal/volumes/put/parts.go @@ -1,6 +1,7 @@ package put import ( + "cmp" "context" "crypto/sha256" "encoding/hex" @@ -39,9 +40,6 @@ const ( maxBufferedPartBytes = 16 << 20 ) -// bufferedPartBytes is maxBufferedPartBytes; tests lower it so their parts stay small. -var bufferedPartBytes = int64(maxBufferedPartBytes) - // partResult is an acknowledged part: its ack, ciphertext CRC and length. type partResult struct { Ack Secret @@ -370,7 +368,7 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, digest [3 if ctx.Err() != nil { return partResult{}, context.Cause(ctx) } - if stopRetryTimer == nil || traffic.sent.Load() > bufferedPartBytes { + if stopRetryTimer == nil || traffic.sent.Load() > cmp.Or(r.bufferedPartBytes, maxBufferedPartBytes) { if stopRetryTimer != nil { stopRetryTimer() } diff --git a/internal/volumes/put/run.go b/internal/volumes/put/run.go index 3743af94..09e64a97 100644 --- a/internal/volumes/put/run.go +++ b/internal/volumes/put/run.go @@ -101,6 +101,7 @@ type runner struct { completionAttempted bool publishActions map[int]string resumed map[int]*resumeFile // resumed files by journal index; nil unless a saved session is resumed + bufferedPartBytes int64 // stands in for maxBufferedPartBytes when set, so tests can send small parts } func newRunner(o Options) (*runner, error) { From 25cb328d946a9881fd5cbd5712262fd888e75c03 Mon Sep 17 00:00:00 2001 From: Emilio Del Tessandoro Date: Fri, 27 Nov 2026 10:19:02 +0100 Subject: [PATCH 6/7] fix(volumes): count a part attempt that kept reading as progress A failed attempt restarted the part's retry window only after it sent more than 16 MiB. With 32 parts sharing a 10 Mbit/s uplink, one part needs about 7 minutes to send that much, so two drops 6 minutes apart stopped the part while its data moved, and a part of 16 MiB or less never restarted the window. An attempt now also counts as progress when it kept reading the part's body for a minute or more, from its first read to its last. A stalled link fills the send buffers in one short burst and then stops reading, so it still stops at the window. Every retryable failure still counts towards the attempt limit, which stops an endpoint that reads the body and then fails. --- internal/volumes/put/part_retry_test.go | 68 +++++++++++++++++++++++++ internal/volumes/put/parts.go | 48 +++++++++++++---- 2 files changed, 106 insertions(+), 10 deletions(-) diff --git a/internal/volumes/put/part_retry_test.go b/internal/volumes/put/part_retry_test.go index caabb331..b20d9528 100644 --- a/internal/volumes/put/part_retry_test.go +++ b/internal/volumes/put/part_retry_test.go @@ -282,3 +282,71 @@ func TestPartStalledRetriesStopAtTheRetryWindow(t *testing.T) { }) } } + +// tricklingTransport reads each failing attempt's body a KiB at a time, waiting every between +// reads, then waits tail and drops the connection; after drops attempts it reads the body in full +// and acknowledges it. It is one part among many on a slow uplink. +type tricklingTransport struct { + every time.Duration + tail time.Duration + drops int + calls int +} + +func (d *tricklingTransport) PutPart(ctx context.Context, _ Target, body io.Reader, _ int64) (Secret, error) { + d.calls++ + if d.calls > d.drops { + if _, err := io.Copy(io.Discard, body); err != nil { + return "", err + } + return testAck, nil + } + for { + n, err := io.CopyN(io.Discard, body, 1<<10) + if err != nil && !errors.Is(err, io.EOF) { + return "", err + } + if n < 1<<10 { + break + } + if err := sleepContext(ctx, d.every); err != nil { + return "", err + } + } + if err := sleepContext(ctx, d.tail); err != nil { + return "", err + } + return "", errConnectionDropped +} + +// TestPartRetryWindowRestartsAfterSlowReads: a part far below the byte threshold, read slowly for +// about 6 minutes per attempt before the connection drops, restarts the retry window on each drop +// and gets through. Attempts whose reads span under a minute and then wait as long prove nothing, +// and the part stops at the window. +func TestPartRetryWindowRestartsAfterSlowReads(t *testing.T) { + cases := []struct { + name string + every, tail time.Duration + wantErr error + }{ + {name: "reads for minutes", every: 40 * time.Second, tail: 0, wantErr: nil}, + {name: "reads for seconds", every: 3 * time.Second, tail: 6 * time.Minute, wantErr: errUploadRetriesExhausted}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + tr := &tricklingTransport{every: c.every, tail: c.tail, drops: 3, calls: 0} + result, err := sendSizedTestPart(t, tr, 8<<10, 0) + if c.wantErr != nil { + if !errors.Is(err, c.wantErr) || tr.calls != 2 { + t.Errorf("error = %v after %d attempts, want %v after 2", err, tr.calls, c.wantErr) + } + return + } + if err != nil || result.Ack != testAck || tr.calls != 4 { + t.Errorf("ack = %q, error = %v, attempts = %d; want three retries, the last acknowledged", result.Ack, err, tr.calls) + } + }) + }) + } +} diff --git a/internal/volumes/put/parts.go b/internal/volumes/put/parts.go index 6461a9df..7897bfd9 100644 --- a/internal/volumes/put/parts.go +++ b/internal/volumes/put/parts.go @@ -22,11 +22,13 @@ const ( maxRenewals = 3 maxRenewParts = 128 // maxPartRetryTime bounds how long a part may keep failing without moving data: no attempt - // starts once it has passed since the end of the part's last failed attempt that sent more than - // maxBufferedPartBytes, or since its first failure when none did. One attempt on a slow link can - // take longer than the window, so a window that ran from the first failure would stop a part - // after one or two connection drops. Attempts that send a lot and fail at once still stop at - // maxUploadAttempts. + // starts once it has passed since the end of the part's last failed attempt that made progress, + // or since its first failure when none did. A failed attempt made progress when it sent more than + // maxBufferedPartBytes of the part's body, or kept reading the body for minProgressReadTime from + // its first read to its last. One attempt on a slow link can take longer than the window, so a + // window that ran from the first failure would stop a part after one or two connection drops. + // Every retryable failure counts towards maxUploadAttempts, which stops a part whose attempts + // move data and then fail, such as an endpoint that reads the body and answers an error. maxPartRetryTime = 5 * time.Minute // maxBufferedPartBytes is how much of a part's body an attempt may hand to the connection without // proving that any of it left the machine. The transport counts the bytes the HTTP client reads, @@ -35,9 +37,15 @@ const ( // autotuning stops at 4 MiB by default on Linux and macOS, and macOS caps any socket buffer at // 8 MiB; the client's own buffers add tens of KiB. 16 MiB leaves room for a host tuned above // those defaults. Restarting the window on any byte sent would let a stalled link retry until - // maxUploadAttempts, about 40 minutes. A part no larger than this, the last part of a file, - // never proves progress and keeps the window from its first failure. + // maxUploadAttempts, about 40 minutes. An attempt that sends less, as every attempt of a part no + // larger than this does, proves progress by its reading time instead. maxBufferedPartBytes = 16 << 20 + // minProgressReadTime is how long an attempt must keep reading a part's body, from its first + // read to its last, to prove progress whatever it sent. A stalled link fills the buffers in one + // burst, a fraction of a second from a local disk, and then the client stops reading; a part + // sharing a slow uplink keeps reading for minutes, about 7 to send 16 MiB at 10 Mbit/s with 32 + // parts in flight. + minProgressReadTime = time.Minute ) // partResult is an acknowledged part: its ack, ciphertext CRC and length. @@ -320,7 +328,7 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, digest [3 defer func() { _ = file.Close() }() var failed Secret // The retry window limits when another attempt can start. It starts at the first failure and - // again after every failed attempt that sent more than maxBufferedPartBytes. + // again after every failed attempt that made progress, as maxPartRetryTime defines it. retryCtx := ctx var stopRetryTimer context.CancelFunc defer func() { @@ -353,6 +361,7 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, digest [3 traffic := &partTraffic{ file: f, progress: r.progress, + now: r.now, } ack, err := r.tr.PutPart(ctx, target, io.TeeReader(body, io.MultiWriter(crc, traffic)), sealer.Len()) if srcErr := src.failure(); srcErr != nil { @@ -368,7 +377,7 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, digest [3 if ctx.Err() != nil { return partResult{}, context.Cause(ctx) } - if stopRetryTimer == nil || traffic.sent.Load() > cmp.Or(r.bufferedPartBytes, maxBufferedPartBytes) { + if stopRetryTimer == nil || traffic.madeProgress(cmp.Or(r.bufferedPartBytes, maxBufferedPartBytes)) { if stopRetryTimer != nil { stopRetryTimer() } @@ -401,20 +410,39 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, digest [3 } // partTraffic counts ciphertext consumed by the transport on one attempt, and adds it to the file's -// and the upload's totals. +// and the upload's totals. It also records when the attempt first and last read the body. type partTraffic struct { file *fileState progress *progress + now func() time.Time sent atomic.Int64 + + mu sync.Mutex + first, last time.Time } func (p *partTraffic) Write(b []byte) (int, error) { + at := p.now() + p.mu.Lock() + if p.first.IsZero() { + p.first = at + } + p.last = at + p.mu.Unlock() p.sent.Add(int64(len(b))) p.file.sent.Add(int64(len(b))) p.progress.addSent(int64(len(b))) return len(b), nil } +// madeProgress reports whether the attempt sent more than buffered bytes of the body or kept +// reading it for minProgressReadTime. +func (p *partTraffic) madeProgress(buffered int64) bool { + p.mu.Lock() + defer p.mu.Unlock() + return p.sent.Load() > buffered || (!p.first.IsZero() && p.last.Sub(p.first) >= minProgressReadTime) +} + // retryable reports whether the request can benefit from a retry. func retryable(err error) bool { if errors.Is(err, ErrPartTokenInvalid) || errors.Is(err, ErrPartLengthMismatch) || errors.Is(err, ErrProtocol) { From d354f09ddcd283ef100451c6fc5270130918f826 Mon Sep 17 00:00:00 2001 From: Emilio Del Tessandoro Date: Fri, 27 Nov 2026 11:16:09 +0100 Subject: [PATCH 7/7] fix(volumes): count only steady reads as a part's reading time An attempt proved progress when its first and last reads of the part's body were a minute or more apart. One burst into the send buffers and one late read, as a retransmit on a lossy link can cause, passed that test, so a stalled part restarted its retry window on every attempt and stopped only at the attempt limit, after about an hour. Reading time is now the sum of the gaps between consecutive reads, counting only gaps of at most 10 seconds. A link that moves data reads the body every second or so and still adds up a minute; a burst followed by silence adds up almost nothing, whatever comes after it. The slow-read tests now pin the one-minute boundary, the longest counted gap, the burst-silence-late-read attempt, and the attempt limit for attempts that each prove progress by their reading time. --- internal/volumes/put/part_retry_test.go | 73 ++++++++++++++++--------- internal/volumes/put/parts.go | 36 +++++++----- 2 files changed, 68 insertions(+), 41 deletions(-) diff --git a/internal/volumes/put/part_retry_test.go b/internal/volumes/put/part_retry_test.go index b20d9528..c2c1da2a 100644 --- a/internal/volumes/put/part_retry_test.go +++ b/internal/volumes/put/part_retry_test.go @@ -283,17 +283,17 @@ func TestPartStalledRetriesStopAtTheRetryWindow(t *testing.T) { } } -// tricklingTransport reads each failing attempt's body a KiB at a time, waiting every between -// reads, then waits tail and drops the connection; after drops attempts it reads the body in full -// and acknowledges it. It is one part among many on a slow uplink. -type tricklingTransport struct { - every time.Duration +// pacedTransport fails its first drops attempts: each reads a KiB of the body, then waits each of +// gaps in turn and reads another KiB after it, then waits tail and drops the connection. Later +// attempts read the body in full and acknowledge it. It is one part among many on a slow uplink. +type pacedTransport struct { + gaps []time.Duration tail time.Duration drops int calls int } -func (d *tricklingTransport) PutPart(ctx context.Context, _ Target, body io.Reader, _ int64) (Secret, error) { +func (d *pacedTransport) PutPart(ctx context.Context, _ Target, body io.Reader, _ int64) (Secret, error) { d.calls++ if d.calls > d.drops { if _, err := io.Copy(io.Discard, body); err != nil { @@ -301,15 +301,14 @@ func (d *tricklingTransport) PutPart(ctx context.Context, _ Target, body io.Read } return testAck, nil } - for { - n, err := io.CopyN(io.Discard, body, 1<<10) - if err != nil && !errors.Is(err, io.EOF) { - return "", err + for i := 0; ; i++ { + if _, err := io.CopyN(io.Discard, body, 1<<10); err != nil { + return "", fmt.Errorf("the test part is too short for its reads: %w", err) } - if n < 1<<10 { + if i == len(d.gaps) { break } - if err := sleepContext(ctx, d.every); err != nil { + if err := sleepContext(ctx, d.gaps[i]); err != nil { return "", err } } @@ -319,32 +318,52 @@ func (d *tricklingTransport) PutPart(ctx context.Context, _ Target, body io.Read return "", errConnectionDropped } -// TestPartRetryWindowRestartsAfterSlowReads: a part far below the byte threshold, read slowly for -// about 6 minutes per attempt before the connection drops, restarts the retry window on each drop -// and gets through. Attempts whose reads span under a minute and then wait as long prove nothing, -// and the part stops at the window. +// steadyGaps is n gaps of every between reads. +func steadyGaps(n int, every time.Duration) []time.Duration { + gaps := make([]time.Duration, n) + for i := range gaps { + gaps[i] = every + } + return gaps +} + +// TestPartRetryWindowRestartsAfterSlowReads: a part far below the byte threshold restarts the retry +// window on each drop when its attempts kept reading the body steadily for minProgressReadTime, +// counting only gaps of at most maxReadGap between reads. Each failing attempt lasts longer than +// the window, so an attempt that proves nothing stops the part after two attempts, and one that +// proves progress lets it retry until it gets through or reaches the attempt limit. func TestPartRetryWindowRestartsAfterSlowReads(t *testing.T) { + const tick = time.Nanosecond cases := []struct { - name string - every, tail time.Duration - wantErr error + name string + gaps []time.Duration + tail time.Duration + drops int + wantErr error + wantCalls int }{ - {name: "reads for minutes", every: 40 * time.Second, tail: 0, wantErr: nil}, - {name: "reads for seconds", every: 3 * time.Second, tail: 6 * time.Minute, wantErr: errUploadRetriesExhausted}, + {name: "steady reads for minutes", gaps: steadyGaps(360, time.Second), drops: 3, wantCalls: 4}, + {name: "reads for seconds", gaps: steadyGaps(8, 3*time.Second), tail: 6 * time.Minute, drops: 3, wantErr: errUploadRetriesExhausted, wantCalls: 2}, + {name: "reads for exactly the minimum", gaps: steadyGaps(60, time.Second), tail: 5 * time.Minute, drops: 3, wantCalls: 4}, + {name: "reads for a tick under the minimum", gaps: append(steadyGaps(59, time.Second), time.Second-tick), tail: 5 * time.Minute, drops: 3, wantErr: errUploadRetriesExhausted, wantCalls: 2}, + {name: "gaps of the longest counted length", gaps: steadyGaps(6, maxReadGap), tail: 5 * time.Minute, drops: 3, wantCalls: 4}, + {name: "gaps a tick over the longest counted length", gaps: steadyGaps(7, maxReadGap+tick), tail: 5 * time.Minute, drops: 3, wantErr: errUploadRetriesExhausted, wantCalls: 2}, + {name: "burst, silence and a late read", gaps: []time.Duration{90 * time.Second}, tail: 4 * time.Minute, drops: 3, wantErr: errUploadRetriesExhausted, wantCalls: 2}, + {name: "more slow drops than the attempt limit", gaps: steadyGaps(90, time.Second), drops: maxUploadAttempts + 2, wantErr: errUploadRetriesExhausted, wantCalls: maxUploadAttempts}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { synctest.Test(t, func(t *testing.T) { - tr := &tricklingTransport{every: c.every, tail: c.tail, drops: 3, calls: 0} - result, err := sendSizedTestPart(t, tr, 8<<10, 0) + tr := &pacedTransport{gaps: c.gaps, tail: c.tail, drops: c.drops, calls: 0} + result, err := sendSizedTestPart(t, tr, (len(c.gaps)+2)<<10, 0) if c.wantErr != nil { - if !errors.Is(err, c.wantErr) || tr.calls != 2 { - t.Errorf("error = %v after %d attempts, want %v after 2", err, tr.calls, c.wantErr) + if !errors.Is(err, c.wantErr) || tr.calls != c.wantCalls { + t.Errorf("error = %v after %d attempts, want %v after %d", err, tr.calls, c.wantErr, c.wantCalls) } return } - if err != nil || result.Ack != testAck || tr.calls != 4 { - t.Errorf("ack = %q, error = %v, attempts = %d; want three retries, the last acknowledged", result.Ack, err, tr.calls) + if err != nil || result.Ack != testAck || tr.calls != c.wantCalls { + t.Errorf("ack = %q, error = %v, attempts = %d; want %d attempts, the last acknowledged", result.Ack, err, tr.calls, c.wantCalls) } }) }) diff --git a/internal/volumes/put/parts.go b/internal/volumes/put/parts.go index 7897bfd9..6cd9cecc 100644 --- a/internal/volumes/put/parts.go +++ b/internal/volumes/put/parts.go @@ -24,8 +24,8 @@ const ( // maxPartRetryTime bounds how long a part may keep failing without moving data: no attempt // starts once it has passed since the end of the part's last failed attempt that made progress, // or since its first failure when none did. A failed attempt made progress when it sent more than - // maxBufferedPartBytes of the part's body, or kept reading the body for minProgressReadTime from - // its first read to its last. One attempt on a slow link can take longer than the window, so a + // maxBufferedPartBytes of the part's body, or kept reading the body steadily for + // minProgressReadTime. One attempt on a slow link can take longer than the window, so a // window that ran from the first failure would stop a part after one or two connection drops. // Every retryable failure counts towards maxUploadAttempts, which stops a part whose attempts // move data and then fail, such as an endpoint that reads the body and answers an error. @@ -40,12 +40,19 @@ const ( // maxUploadAttempts, about 40 minutes. An attempt that sends less, as every attempt of a part no // larger than this does, proves progress by its reading time instead. maxBufferedPartBytes = 16 << 20 - // minProgressReadTime is how long an attempt must keep reading a part's body, from its first - // read to its last, to prove progress whatever it sent. A stalled link fills the buffers in one - // burst, a fraction of a second from a local disk, and then the client stops reading; a part - // sharing a slow uplink keeps reading for minutes, about 7 to send 16 MiB at 10 Mbit/s with 32 - // parts in flight. + // minProgressReadTime is how long an attempt must keep reading a part's body to prove progress + // whatever it sent. Reading time is the sum of the gaps between consecutive reads of the body, + // counting only gaps of at most maxReadGap. A stalled link fills the buffers in one burst, a + // fraction of a second from a local disk, and then the client stops reading, so its attempts + // add up almost nothing, even when a lone read arrives long after the burst. A part sharing a + // slow uplink keeps reading for minutes, about 7 to send 16 MiB at 10 Mbit/s with 32 parts in + // flight. minProgressReadTime = time.Minute + // maxReadGap is the longest gap between two reads of a part's body that still counts as + // reading. The client reads the body only as the connection takes it, in chunks of up to tens + // of KiB, so a link that moves data reads every second or so; a read every 10 seconds is a few + // KB/s per part, about 1 Mbit/s shared by 32 parts. + maxReadGap = 10 * time.Second ) // partResult is an acknowledged part: its ack, ciphertext CRC and length. @@ -410,22 +417,23 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, digest [3 } // partTraffic counts ciphertext consumed by the transport on one attempt, and adds it to the file's -// and the upload's totals. It also records when the attempt first and last read the body. +// and the upload's totals. It also adds up how long the attempt kept reading the body. type partTraffic struct { file *fileState progress *progress now func() time.Time sent atomic.Int64 - mu sync.Mutex - first, last time.Time + mu sync.Mutex + last time.Time // the latest read of the body + reading time.Duration // the gaps between reads of at most maxReadGap, summed } func (p *partTraffic) Write(b []byte) (int, error) { at := p.now() p.mu.Lock() - if p.first.IsZero() { - p.first = at + if gap := at.Sub(p.last); !p.last.IsZero() && gap <= maxReadGap { + p.reading += gap } p.last = at p.mu.Unlock() @@ -436,11 +444,11 @@ func (p *partTraffic) Write(b []byte) (int, error) { } // madeProgress reports whether the attempt sent more than buffered bytes of the body or kept -// reading it for minProgressReadTime. +// reading it for minProgressReadTime, as minProgressReadTime defines it. func (p *partTraffic) madeProgress(buffered int64) bool { p.mu.Lock() defer p.mu.Unlock() - return p.sent.Load() > buffered || (!p.first.IsZero() && p.last.Sub(p.first) >= minProgressReadTime) + return p.sent.Load() > buffered || p.reading >= minProgressReadTime } // retryable reports whether the request can benefit from a retry.