lease: witness waits for applied late writes; take request budget
Astra Task 4 R1, two test P2s. The witness's held requests now count down only after the S3 fake has answered them; each answer's status is recorded and must be 2xx before objects are compared or the restore runs. The fixture proxy's hook returns a completion callback the proxy runs after the inner handler. The fixture records every request raw (method, COPY for a copy, key, query, status), GETs included. TestTakeRequestBudget asserts a take's exact requests: one head.json GET, every ListObjectVersions page of G (page size 2, at least two pages), one CopyObject per planned file and one head.json PUT at the switch; zero requests for a repeated Switch; no head GET when TakeOptions carries the head (HeadRead). The first wake's Switch is checked against raw requests, not deduplicated keys.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+227
−21
internal/lease/gentake_test.go+200 −13internal/lease/stale_holder_witness_test.go+27 −8
CI failed — run details
Intent
diff --git a/internal/lease/gentake_test.go b/internal/lease/gentake_test.go| index cc5f36b71..01bbcb57a 100644 |
| --- a/internal/lease/gentake_test.go |
| +++ b/internal/lease/gentake_test.go |
| @@ -36,8 +36,17 @@ var ( |
| // included), a DELETE, or one object of a POST ?delete. |
| type sentReq struct{ phase, method, key string } |
| +// rawReq is one request the proxy served, of any method: the method |
| +// (COPY for a PUT with x-amz-copy-source), key, raw query and status. |
| +type rawReq struct { |
| + phase, method, key, query string |
| + status int |
| +} |
| + |
| // genFixture is a versioned bucket behind a recording proxy. hook, when |
| -// set, sees every request before the server does and may hold it. |
| +// set, sees every request before the server does and may hold it; the |
| +// func it returns, if any, runs once the server has answered, with the |
| +// answer's status. |
| type genFixture struct { |
| m *leasetest.VersionedBucket |
| bucket, loc, region string |
| @@ -46,14 +55,20 @@ type genFixture struct { |
| mu sync.Mutex |
| sent []sentReq |
| + raw []rawReq |
| phase string |
| - hook func(r *http.Request, keys []string) |
| + hook func(r *http.Request, keys []string) (done func(status int)) |
| } |
| -func newGenFixture(t *testing.T) *genFixture { |
| +// newGenFixture builds the fixture; each configure runs on the bucket |
| +// before the server starts. |
| +func newGenFixture(t *testing.T, configure ...func(*leasetest.VersionedBucket)) *genFixture { |
| t.Helper() |
| fx := &genFixture{m: leasetest.NewVersionedBucket(), bucket: "data", loc: "instances/w.example.com", region: "test-region"} |
| fx.m.AddBucket(fx.bucket) |
| + for _, c := range configure { |
| + c(fx.m) |
| + } |
| inner, _ := leasetest.NewS3Server(fx.m) |
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| key, _ := url.PathUnescape(strings.TrimPrefix(r.URL.EscapedPath(), "/"+fx.bucket+"/")) |
| @@ -106,17 +121,72 @@ func (fx *genFixture) record(r *http.Request, keys []string) { |
| } |
| } |
| +// statusWriter remembers the status a handler answered with. |
| +type statusWriter struct { |
| + http.ResponseWriter |
| + status int |
| +} |
| + |
| +func (s *statusWriter) WriteHeader(code int) { |
| + if s.status == 0 { |
| + s.status = code |
| + } |
| + s.ResponseWriter.WriteHeader(code) |
| +} |
| + |
| +func (s *statusWriter) Write(b []byte) (int, error) { |
| + if s.status == 0 { |
| + s.status = http.StatusOK |
| + } |
| + return s.ResponseWriter.Write(b) |
| +} |
| + |
| func (fx *genFixture) serve(w http.ResponseWriter, r *http.Request, inner http.Handler, keys []string) { |
| fx.mu.Lock() |
| - hook := fx.hook |
| + hook, phase := fx.hook, fx.phase |
| fx.mu.Unlock() |
| + var done func(int) |
| if hook != nil { |
| - hook(r, keys) |
| + done = hook(r, keys) |
| + } |
| + sw := &statusWriter{ResponseWriter: w} |
| + inner.ServeHTTP(sw, r) |
| + if sw.status == 0 { |
| + sw.status = http.StatusOK |
| + } |
| + method := r.Method |
| + if method == http.MethodPut && r.Header.Get("x-amz-copy-source") != "" { |
| + method = "COPY" |
| + } |
| + key, _ := url.PathUnescape(strings.TrimPrefix(r.URL.EscapedPath(), "/"+fx.bucket)) |
| + fx.mu.Lock() |
| + fx.raw = append(fx.raw, rawReq{phase: phase, method: method, key: strings.TrimPrefix(key, "/"), query: r.URL.RawQuery, status: sw.status}) |
| + fx.mu.Unlock() |
| + if done != nil { |
| + done(sw.status) |
| } |
| - inner.ServeHTTP(w, r) |
| } |
| -func (fx *genFixture) setHook(h func(r *http.Request, keys []string)) { |
| +// requests is every request served in phase, in the order answered, as |
| +// "METHOD key?query" (the query only when there is one). |
| +func (fx *genFixture) requests(phase string) []string { |
| + fx.mu.Lock() |
| + defer fx.mu.Unlock() |
| + var out []string |
| + for _, r := range fx.raw { |
| + if r.phase != phase { |
| + continue |
| + } |
| + s := r.method + " " + r.key |
| + if r.query != "" { |
| + s += "?" + r.query |
| + } |
| + out = append(out, s) |
| + } |
| + return out |
| +} |
| + |
| +func (fx *genFixture) setHook(h func(r *http.Request, keys []string) (done func(status int))) { |
| fx.mu.Lock() |
| fx.hook = h |
| fx.mu.Unlock() |
| @@ -218,6 +288,13 @@ func (fx *genFixture) current(t *testing.T, prefix string) []string { |
| // rows replicated into it, released clean (a successor takes at once). It |
| // returns the generation and the clean marker's TXID. |
| func (fx *genFixture) seed(t *testing.T, ttl time.Duration, rows int) (string, uint64) { |
| + t.Helper() |
| + return fx.seedSyncs(t, ttl, rows, 0) |
| +} |
| + |
| +// seedSyncs is seed with syncs more rows written after replication |
| +// starts, each synced on its own: one more L0 file (one more version) each. |
| +func (fx *genFixture) seedSyncs(t *testing.T, ttl time.Duration, rows, syncs int) (string, uint64) { |
| t.Helper() |
| h := fx.acquire(t, ttl) |
| tk, err := h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{First: true, Self: selfA, Lifetime: "L1"}) |
| @@ -236,6 +313,12 @@ func (fx *genFixture) seed(t *testing.T, ttl time.Duration, rows int) (string, u |
| if err != nil { |
| t.Fatal(err) |
| } |
| + for i := range syncs { |
| + witnessExec(t, path, fmt.Sprintf(`INSERT INTO t (body) VALUES ('sync-%d')`, i)) |
| + if err := r.SyncAndWait(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| txid, err := r.Finish(ctx) |
| if err != nil { |
| t.Fatal(err) |
| @@ -284,13 +367,14 @@ func TestFirstWakeCreatesEmptyGeneration(t *testing.T) { |
| head.CreatedBy.LockGeneration != h.LockGeneration() || head.CreatedBy.Box != "a" || head.CreatedBy.IID != "i-a" || head.CreatedBy.Lifetime != "L1" || head.CreatedBy.At.IsZero() { |
| t.Fatalf("head %+v (found %v)", head, found) |
| } |
| - before := len(fx.keys("", false)) |
| + fx.setPhase("switch") |
| if err := tk.Switch(ctx); err != nil { |
| t.Fatalf("switch of a first wake: %v", err) |
| } |
| - if n := len(fx.keys("", false)); n != before { |
| - t.Fatalf("the first wake's switch wrote again: %v", fx.keys("", false)[before:]) |
| + if r := fx.requests("switch"); len(r) != 0 { |
| + t.Fatalf("the first wake's switch made requests: %v", r) |
| } |
| + fx.setPhase("") |
| path := filepath.Join(t.TempDir(), "w.example.com.db") |
| if ok, err := lease.RestoreTake(ctx, path, tk); err != nil || ok { |
| t.Fatalf("restore of an empty generation: %v %v, want nothing restored", ok, err) |
| @@ -369,21 +453,22 @@ func TestEmptyGenerationNextTakeStartsAfresh(t *testing.T) { |
| func heldSwitch(fx *genFixture) (arrived <-chan struct{}, release func()) { |
| in, out := make(chan struct{}), make(chan struct{}) |
| var once sync.Once |
| - fx.setHook(func(r *http.Request, keys []string) { |
| + fx.setHook(func(r *http.Request, keys []string) func(int) { |
| if r.Method != http.MethodPut || len(keys) != 1 || !strings.HasSuffix(keys[0], "/head.json") { |
| - return |
| + return nil |
| } |
| fx.mu.Lock() |
| phase := fx.phase |
| fx.mu.Unlock() |
| if phase != "a" { |
| - return |
| + return nil |
| } |
| held := false |
| once.Do(func() { held = true; close(in) }) |
| if held { |
| <-out |
| } |
| + return nil |
| }) |
| return in, sync.OnceFunc(func() { close(out) }) |
| } |
| @@ -779,3 +864,105 @@ func TestTakeOverAnEmptyRootStartsFresh(t *testing.T) { |
| t.Fatalf("head %+v: want an empty %s after the root", head, tk.Generation) |
| } |
| } |
| + |
| +// The take's request budget (common rules): one GET of head.json, the |
| +// ListObjectVersions pages of G, one CopyObject per planned file and one |
| +// PUT of head.json; nothing else. A repeated Switch makes no request, and |
| +// a take given the head it already read (HeadRead) reads none. |
| +func TestTakeRequestBudget(t *testing.T) { |
| + const pageSize = 2 |
| + haBox(t) |
| + fx := newGenFixture(t, func(m *leasetest.VersionedBucket) { m.PageSize = pageSize }) |
| + seedGen, txid := fx.seedSyncs(t, time.Hour, 10, 4) |
| + headKey := fx.loc + "/head.json" |
| + headGet, headPut := "GET "+headKey+"?x-id=GetObject", "PUT "+headKey+"?x-id=PutObject" |
| + |
| + // budget checks one take's requests: the head GET when wantHeadGet, |
| + // then every listing page of from, then one COPY per object the copy |
| + // left under to, and nothing else. |
| + budget := func(t *testing.T, phase, from, to string, wantHeadGet bool) { |
| + t.Helper() |
| + reqs := fx.requests(phase) |
| + var gets, lists, copies, other []string |
| + for _, r := range reqs { |
| + switch { |
| + case r == headGet: |
| + gets = append(gets, r) |
| + case strings.HasPrefix(r, "GET ?") && strings.Contains(r, "versions"): |
| + lists = append(lists, r) |
| + case strings.HasPrefix(r, "COPY "+replicagen.Prefix(fx.loc, to)): |
| + copies = append(copies, r) |
| + default: |
| + other = append(other, r) |
| + } |
| + } |
| + if want := map[bool]int{true: 1, false: 0}[wantHeadGet]; len(gets) != want { |
| + t.Errorf("%d head.json GETs, want %d: %v", len(gets), want, reqs) |
| + } |
| + if wantHeadGet && (len(reqs) == 0 || reqs[0] != headGet) { |
| + t.Errorf("the take did not start with the head read: %v", reqs) |
| + } |
| + versions, err := fx.m.ListVersions(ctx, fx.bucket, replicagen.Prefix(fx.loc, from)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if want := (len(versions) + pageSize - 1) / pageSize; len(lists) != want || want < 2 { |
| + t.Errorf("%d listing pages over %d versions, want %d (and at least 2): %v", len(lists), len(versions), want, lists) |
| + } |
| + planned := fx.current(t, replicagen.Prefix(fx.loc, to)) |
| + if len(copies) != len(planned) || len(planned) == 0 { |
| + t.Errorf("%d copies for %d planned files: %v", len(copies), len(planned), copies) |
| + } |
| + if len(other) != 0 { |
| + t.Errorf("requests outside the budget: %v", other) |
| + } |
| + } |
| + switchBudget := func(t *testing.T, tk *lease.Take, phase string) { |
| + t.Helper() |
| + fx.setPhase(phase) |
| + if err := tk.Switch(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r := fx.requests(phase); !slices.Equal(r, []string{headPut}) { |
| + t.Errorf("switch requests %v, want one head.json PUT", r) |
| + } |
| + fx.setPhase(phase + "-again") |
| + if err := tk.Switch(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r := fx.requests(phase + "-again"); len(r) != 0 { |
| + t.Errorf("a repeated switch made requests: %v", r) |
| + } |
| + } |
| + |
| + h := fx.acquire(t, time.Hour) |
| + fx.setPhase("take") |
| + tk, err := h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{CleanTXID: txid, Self: selfA, Lifetime: "L2"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + budget(t, "take", seedGen, tk.Generation, true) |
| + switchBudget(t, tk, "switch") |
| + fx.setPhase("") |
| + if err := h.Release(ctx); err != nil { // never replicated: settled |
| + t.Fatal(err) |
| + } |
| + |
| + // A take given the head its caller read: no head GET, and its switch |
| + // is conditional on that read's ETag. |
| + head, etag, found := fx.head(t) |
| + h2 := fx.acquire(t, time.Hour) |
| + fx.setPhase("take2") |
| + tk2, err := h2.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfA, Lifetime: "L3", HeadRead: true, Head: head, HeadETag: etag, HeadFound: found}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if tk2.Predecessor != tk.Generation { |
| + t.Fatalf("the second take copied from %s, want %s", tk2.Predecessor, tk.Generation) |
| + } |
| + budget(t, "take2", tk.Generation, tk2.Generation, false) |
| + switchBudget(t, tk2, "switch2") |
| + if got, _, _ := fx.head(t); got.Generation != tk2.Generation { |
| + t.Fatalf("head names %s, want %s", got.Generation, tk2.Generation) |
| + } |
| +} |
diff --git a/internal/lease/stale_holder_witness_test.go b/internal/lease/stale_holder_witness_test.go| index 1949f5caf..2670f57d4 100644 |
| --- a/internal/lease/stale_holder_witness_test.go |
| +++ b/internal/lease/stale_holder_witness_test.go |
| @@ -46,23 +46,31 @@ func TestWitnessLateWriteFromAnEarlierHolderKeepsTheSuccessorsHistory(t *testing |
| // The partition: while it is on, every replica write that reaches the |
| // server (lock.json aside, so A's release goes through) is read in |
| // full, as S3 would have received it, and held unapplied until heal. |
| + // applied counts a held request down only once the server has |
| + // answered it, with the status it answered. |
| var ( |
| partitioned atomic.Bool |
| healed = make(chan struct{}) |
| - held sync.WaitGroup |
| + applied sync.WaitGroup |
| mu sync.Mutex |
| heldKeys []string |
| + heldStatus []int |
| ) |
| - fx.setHook(func(r *http.Request, keys []string) { |
| - if !partitioned.Load() || r.Method == http.MethodGet || isControlKey(keys) { |
| - return |
| + fx.setHook(func(r *http.Request, keys []string) func(int) { |
| + if !partitioned.Load() || r.Method == http.MethodGet || r.Method == http.MethodHead || isControlKey(keys) { |
| + return nil |
| } |
| - held.Add(1) |
| - defer held.Done() |
| + applied.Add(1) |
| mu.Lock() |
| heldKeys = append(heldKeys, keys...) |
| mu.Unlock() |
| <-healed |
| + return func(status int) { |
| + mu.Lock() |
| + heldStatus = append(heldStatus, status) |
| + mu.Unlock() |
| + applied.Done() |
| + } |
| }) |
| heal := sync.OnceFunc(func() { close(healed) }) |
| t.Cleanup(heal) |
| @@ -169,8 +177,19 @@ func TestWitnessLateWriteFromAnEarlierHolderKeepsTheSuccessorsHistory(t *testing |
| // The partition heals: the server applies what A sent. |
| heal() |
| - held.Wait() |
| - t.Logf("A's held writes, applied after B's history: %v", aHeldKeys) |
| + applied.Wait() |
| + mu.Lock() |
| + statuses := append([]int(nil), heldStatus...) |
| + mu.Unlock() |
| + if len(statuses) == 0 { |
| + t.Fatal("fixture: no held request of A's was applied") |
| + } |
| + for i, st := range statuses { |
| + if st < 200 || st > 299 { |
| + t.Fatalf("fixture: held request %d of A's answered %d, want 2xx (the late write must land)", i, st) |
| + } |
| + } |
| + t.Logf("A's held writes, applied after B's history (statuses %v): %v", statuses, aHeldKeys) |
| // The invariant at the object level, whatever a restore happens to |
| // read: no object of B's history is replaced by A's late writes. |