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..c2c1da2a 100644 --- a/internal/volumes/put/part_retry_test.go +++ b/internal/volumes/put/part_retry_test.go @@ -2,8 +2,12 @@ package put import ( "context" + "crypto/sha256" "errors" + "fmt" "io" + "os" + "path/filepath" "testing" "testing/synctest" "time" @@ -11,6 +15,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 +33,49 @@ 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) +} + +// testBufferedPartBytes stands in for maxBufferedPartBytes, so a part that proves progress is small. +const testBufferedPartBytes = 4 << 10 + +// 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() + 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) +} + +// 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 +83,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,15 +123,249 @@ 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) } }) } + +// 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. 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 +} + +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 + } + 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 := 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) + } + }) +} + +// 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) { + synctest.Test(t, func(t *testing.T) { + tr := &droppingTransport{ + attemptTime: 0, + drops: 2 * maxUploadAttempts, + calls: 0, + } + 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. +// +// 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) { + 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: c.buffered, + stall: 2 * time.Minute, + starts: nil, + ends: nil, + } + 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 { + 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) + } + } + }) + }) + } +} + +// 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 *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 { + return "", err + } + return testAck, nil + } + 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 i == len(d.gaps) { + break + } + if err := sleepContext(ctx, d.gaps[i]); err != nil { + return "", err + } + } + if err := sleepContext(ctx, d.tail); err != nil { + return "", err + } + return "", errConnectionDropped +} + +// 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 + gaps []time.Duration + tail time.Duration + drops int + wantErr error + wantCalls int + }{ + {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 := &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 != 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 != 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/part_stream_test.go b/internal/volumes/put/part_stream_test.go new file mode 100644 index 00000000..819c1bb7 --- /dev/null +++ b/internal/volumes/put/part_stream_test.go @@ -0,0 +1,251 @@ +package put + +import ( + "bytes" + "context" + "errors" + "io" + "os" + "path/filepath" + "runtime" + "sync" + "sync/atomic" + "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]) + } +} + +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 d0372e09..6cd9cecc 100644 --- a/internal/volumes/put/parts.go +++ b/internal/volumes/put/parts.go @@ -1,15 +1,15 @@ package put import ( - "bytes" + "cmp" "context" "crypto/sha256" "encoding/hex" "errors" "fmt" + "hash" "io" "net/http" - "os" "sync" "sync/atomic" "time" @@ -19,9 +19,40 @@ import ( ) const ( - maxRenewals = 3 - maxRenewParts = 128 + 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 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 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. 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. 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 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. @@ -83,10 +114,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 +135,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 +149,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 +158,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 +178,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 +216,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, + } +} + +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 err + return n, s.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) +// 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 unchanged(f.src) + 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,10 +320,22 @@ 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. + // The retry window limits when another attempt can start. It starts at the first failure and + // again after every failed attempt that made progress, as maxPartRetryTime defines it. retryCtx := ctx var stopRetryTimer context.CancelFunc defer func() { @@ -308,7 +356,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) } @@ -316,21 +365,35 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, plain []b if cause := context.Cause(retryCtx); cause != nil { return partResult{}, cause } - traffic := partTraffic{ + 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()) - tokenExpired := errors.Is(err, ErrPartTokenExpired) - switch { - case err == nil: + if srcErr := src.failure(); srcErr != nil { + return partResult{}, srcErr + } + 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.madeProgress(cmp.Or(r.bufferedPartBytes, maxBufferedPartBytes)) { + 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: @@ -345,11 +408,6 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, plain []b 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 @@ -358,18 +416,41 @@ func (r *runner) sendPart(ctx context.Context, f *fileState, part int, plain []b } } -// 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. 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 + 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) { +func (p *partTraffic) Write(b []byte) (int, error) { + at := p.now() + p.mu.Lock() + if gap := at.Sub(p.last); !p.last.IsZero() && gap <= maxReadGap { + p.reading += gap + } + 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, as minProgressReadTime defines it. +func (p *partTraffic) madeProgress(buffered int64) bool { + p.mu.Lock() + defer p.mu.Unlock() + return p.sent.Load() > buffered || p.reading >= 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) { diff --git a/internal/volumes/put/put_test.go b/internal/volumes/put/put_test.go index de2c5e46..4430e9a0 100644 --- a/internal/volumes/put/put_test.go +++ b/internal/volumes/put/put_test.go @@ -6,12 +6,14 @@ import ( "encoding/json" "errors" "fmt" + "io" "maps" "os" "path/filepath" "slices" "strconv" "strings" + "sync" "testing" "time" @@ -19,6 +21,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 +385,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 +730,91 @@ 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() } + // 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) + + 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) + } + }) } +} - _, err := e.put(vol, file) +// heldPart holds the send of part until the put is cancelled, without reading its body. +type heldPart struct { + Transport + part int +} - assertAborted(t, e, err, file, vol, 0) +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) { 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..09e64a97 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 } @@ -93,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) { @@ -121,9 +130,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 +173,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 +212,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) + } + } +}