diff --git a/seaweed-block/core/storage/chunk_cut_timeout_progress_test.go b/seaweed-block/core/storage/chunk_cut_timeout_progress_test.go new file mode 100644 index 0000000000..f57f0313ef --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_timeout_progress_test.go @@ -0,0 +1,261 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "fmt" + "path/filepath" + "sync" + "testing" + "time" +) + +// oneTiBChunks is the chunk count of a 1 TiB volume with 4 MiB chunks. +const oneTiBChunks = 262144 + +// expiringRemote counts every PUT. Once a given number of PUTs completed it +// ends the attempt: with expire set it cancels the attempt's context; in any +// case every later PUT waits for the attempt's context to end (its deadline +// or that cancel) and returns its error, as an upload cut off by the +// operation's time limit. +type expiringRemote struct { + *fakeChunkRemote + mu sync.Mutex + gated bool + expire context.CancelFunc // nil: wait for the context's own deadline + after int + completed int + attempts int + dups int + done map[string]bool +} + +func (r *expiringRemote) Put(ctx context.Context, key string, b []byte) error { + r.mu.Lock() + r.attempts++ + if r.done[key] { + r.dups++ + } + cutOff := r.gated && r.completed >= r.after + if cutOff && r.expire != nil { + r.expire() + } + r.mu.Unlock() + if cutOff { + <-ctx.Done() + return ctx.Err() + } + if err := ctx.Err(); err != nil { + return err + } + if err := r.fakeChunkRemote.Put(ctx, key, b); err != nil { + return err + } + r.mu.Lock() + r.done[key] = true + r.completed++ + r.mu.Unlock() + return nil +} + +func (r *expiringRemote) reset() { + r.mu.Lock() + defer r.mu.Unlock() + r.gated, r.expire, r.attempts, r.completed, r.dups = false, nil, 0, 0, 0 +} + +func (r *expiringRemote) counts() (attempts, completed, dups int) { + r.mu.Lock() + defer r.mu.Unlock() + return r.attempts, r.completed, r.dups +} + +func (r *expiringRemote) completedKeys() map[string]bool { + r.mu.Lock() + defer r.mu.Unlock() + out := make(map[string]bool, len(r.done)) + for k := range r.done { + out[k] = true + } + return out +} + +// timeoutVolumeBlock is chunk c's content: nonzero, so no chunk is elided. +func timeoutVolumeBlock(c uint32) []byte { return makeBlock(ctBlockSize, byte(c%251+1)) } + +// checkPublishedVolume reports how h differs from the volume every chunk of +// which was written once with timeoutVolumeBlock up to LSN frontier: every +// index named, each named object stored with that chunk's bytes, the +// frontier, and every key in kept named by h. +func checkPublishedVolume(f *fakeChunkRemote, h chunkHead, frontier uint64, kept map[string]bool) error { + if h.RemoteLSN != frontier { + return fmt.Errorf("HEAD frontier %d, want %d", h.RemoteLSN, frontier) + } + if len(h.Chunks) != oneTiBChunks { + return fmt.Errorf("HEAD names %d chunks, want %d", len(h.Chunks), oneTiBChunks) + } + named := make(map[string]bool, len(h.Chunks)) + f.mu.Lock() + defer f.mu.Unlock() + for c := uint32(0); c < oneTiBChunks; c++ { + ref, ok := h.Chunks[uint64(c)] + if !ok { + return fmt.Errorf("HEAD does not name chunk %d", c) + } + b, ok := f.objs[ref.Key] + if !ok { + return fmt.Errorf("HEAD names chunk %d key %q that is not stored", c, ref.Key) + } + if !bytes.Equal(b, timeoutVolumeBlock(c)) { + return fmt.Errorf("chunk %d (key %q) does not hold its written bytes", c, ref.Key) + } + named[ref.Key] = true + } + for k := range kept { + if !named[k] { + return fmt.Errorf("a chunk uploaded by the attempt that ran out of time (key %q) is not named by HEAD", k) + } + } + return nil +} + +// A cut of a 1 TiB volume (262,144 changed chunks) whose attempt runs out +// of time part way through its uploads leaves the chunks it uploaded: the +// next attempt uploads only the rest, sends no completed chunk again, and +// publishes the whole volume, the first attempt's uploads included. The +// time limit around the operation is judged by progress: work that grows +// with the volume may take more than one attempt, and no attempt redoes what +// an earlier one finished. +// +// The attempt is ended both by its context's deadline passing and by a +// cancel; the upload and capture path treats the two alike. What the first +// attempt keeps is kept in this process's memory: a restart between the +// attempts is another case, not shown here (the cut then uploads again what +// it cannot prove was uploaded, which costs time and nothing else, since +// names are by content). +func TestACutAttemptThatRunsOutOfTimeLeavesUploadsTheNextAttemptKeeps(t *testing.T) { + if testing.Short() { + t.Skip("writes 262,144 chunks") + } + for _, end := range []string{"deadline", "cancel"} { + t.Run(end, func(t *testing.T) { cutAttemptRunsOutOfTime(t, end) }) + } +} + +func cutAttemptRunsOutOfTime(t *testing.T, end string) { + path := filepath.Join(t.TempDir(), "vol.bin") + s, err := CreateWALStoreWithOptions(path, oneTiBChunks, ctBlockSize, WALStoreOptions{ChunkBlocks: 1}) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { closeBounded(t, s) }) + f := newFakeChunkRemote() + r := &expiringRemote{fakeChunkRemote: f, done: map[string]bool{}} + cfg := ctConfig(1) + cfg.ChunkBlocks = 1 + cfg.FreshFromHead = true + l := mustAttach(t, s, r, cfg).(*chunkLayerImpl) + if _, err := l.Cut(ctTimeout(t)); err != nil { // the zero baseline + t.Fatal(err) + } + setup := time.Now() + var frontier uint64 + for c := uint32(0); c < oneTiBChunks; c++ { + if frontier, err = s.Write(c, timeoutVolumeBlock(c)); err != nil { + t.Fatal(err) + } + if c%8192 == 8191 { + mustSyncFlush(t, s) + } + } + mustSyncFlush(t, s) + t.Logf("wrote %d chunks in %v", oneTiBChunks, time.Since(setup).Round(time.Millisecond)) + base := f.stats().head.Gen + + // The first attempt: after a part of the uploads every further upload + // waits until the attempt's context ends. Its deadline is short and + // real; the cancel case ends it at once. Either way the attempt must + // return within a generous bound, or the test fails here. + const cutOffAfter = oneTiBChunks / 8 + var ctx context.Context + var cancel context.CancelFunc + want := context.Canceled + if end == "deadline" { + ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second) + want = context.DeadlineExceeded + } else { + ctx, cancel = context.WithCancel(context.Background()) + } + defer cancel() + r.mu.Lock() + r.gated, r.after = true, cutOffAfter + if end == "cancel" { + r.expire = cancel + } + r.mu.Unlock() + start := time.Now() + errc := make(chan error, 1) + go func() { + _, err := l.Cut(ctx) + errc <- err + }() + select { + case err := <-errc: + if !errors.Is(err, want) { + t.Fatalf("the attempt that ran out of time: %v; want %v", err, want) + } + case <-time.After(3 * time.Minute): + cancel() + select { + case <-errc: + case <-time.After(30 * time.Second): + } + t.Fatal("the attempt did not return within 3 minutes of its start") + } + if f.stats().head.Gen != base { + t.Fatal("the attempt that ran out of time moved HEAD") + } + _, kept, _ := r.counts() + keptKeys := r.completedKeys() + t.Logf("first attempt (%s): %d chunks uploaded before its time ran out (%v)", end, kept, time.Since(start).Round(time.Millisecond)) + if kept == 0 || kept >= oneTiBChunks { + t.Fatalf("setup: %d uploads completed before the time ran out, want some but not all", kept) + } + + r.reset() + start = time.Now() + res, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatalf("the next attempt: %v", err) + } + attempts, completed, dups := r.counts() + t.Logf("next attempt: %d uploads (%d sent again) in %v", completed, dups, time.Since(start).Round(time.Millisecond)) + if res.Head.Gen != base+1 { + t.Fatalf("the next attempt published generation %d, want %d", res.Head.Gen, base+1) + } + if dups != 0 { // a resend under the same key; a resend under a new key is caught by the count below + t.Fatalf("the next attempt sent %d chunks the attempt that ran out of time had uploaded", dups) + } + if want := oneTiBChunks - kept; completed != want || attempts != want { + t.Fatalf("the next attempt uploaded %d chunks (%d attempts); want only the %d not yet uploaded", completed, attempts, want) + } + head := f.stats().head + if err := checkPublishedVolume(f, head, frontier, keptKeys); err != nil { + t.Fatalf("published HEAD: %v", err) + } + // Control: the check refuses a HEAD that drops one chunk the first + // attempt uploaded, so it measures the kept uploads reaching HEAD. + dropped := copyChunkHead(head) + for idx, ref := range dropped.Chunks { + if keptKeys[ref.Key] { + delete(dropped.Chunks, idx) + break + } + } + if err := checkPublishedVolume(f, dropped, frontier, keptKeys); err == nil { + t.Fatal("control: the check passed a HEAD without one of the first attempt's uploads") + } + assertNoSessionOpen(t, f) +}