carlos / platform Public

lease tests: wait on signals and moved clocks, not sleeps

The code-health ratchet failed at 11 time.Sleep sites in this branch's
internal/lease tests. Each now waits on what it needs:
- lateWrites closes a channel when the first write is held (the
  takeover witness and the MinIO take);
- the first-renewal test hears each landed PUT from its lock store;
- the eight-copy limit runs in a synctest bubble, so synctest.Wait shows
  a ninth copy would have started;
- renewals: the take-bound test hears lock.json PUTs through the
  fixture hook; waitRenewal waits until the holder's SafeUntil moves on,
  so a release that follows never races the renewal's answer;
- expiries and marker openings move the box's clock (SetBoxNowForTest)
  and, for the point, the store's Date, instead of waiting them out.

The four waits for litestream's Open compaction pass, which it retries on
a fixed one-second timer and signals no end of, share one helper,
awaitOpenPasses: its sleep is raised in .amadan/code-health.tsv.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 5459280aeb16af23f80f899d688ed114c66c9da7 parent fac3955
9 files changed, +170 −69
  • .amadan/code-health.tsv +1 −0
  • internal/lease/generations_lock_test.go +26 −8
  • internal/lease/genpoint_test.go +6 −3
  • internal/lease/genstart_test.go +32 −28
  • internal/lease/gentake_minio_test.go +1 −5
  • internal/lease/gentake_test.go +43 −6
  • internal/lease/gentakeover_test.go +27 −10
  • internal/lease/renew_attempt_test.go +28 −3
  • internal/lease/stale_holder_witness_test.go +6 −6
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv
index 29788ab43..540b9ea41 100644
--- a/.amadan/code-health.tsv
+++ b/.amadan/code-health.tsv
@@ -1242,6 +1242,7 @@ sleep internal/lease_test TestUnsettledMarkerKeepsALateWriteOutOfTheSuccessorsHi
sleep internal/lease_test TestWriteFenceFiresAfterAnEarlierLoss time.Sleep 1
sleep internal/lease_test TestWriteFenceReleaseKeepsItsDeadlineBehindAHungUpload time.Sleep 2
sleep internal/lease_test TestWriteFenceTripsWithFailingUploads time.Sleep 1
+sleep internal/lease_test awaitOpenPasses time.Sleep 1 # raised: replaces 4 generations-test sleeps; litestream retries its Open compaction pass on a fixed 1 s timer and signals neither pass
sleep internal/lease_test delayPutAck time.Sleep 1
sleep internal/mailer TestMailerConcurrencyLimit time.Sleep 1
sleep internal/mailer TestMailerPerSenderInFlight time.Sleep 2
diff --git a/internal/lease/generations_lock_test.go b/internal/lease/generations_lock_test.go
index bae283685..f47cc9029 100644
--- a/internal/lease/generations_lock_test.go
+++ b/internal/lease/generations_lock_test.go
@@ -71,15 +71,33 @@ func requireGenMarker(t *testing.T, fx *leasetest.LockFixture, prefix string, ge
return *v.Lock.Release
}
-// waitRenewal waits until the stored lock body is no longer before.
-func waitRenewal(t *testing.T, fx *leasetest.LockFixture, prefix string, before []byte) {
+// waitRenewal waits until h has renewed its lock. SafeUntil moves on only
+// once a renewal's answer has reached h, with the lock's new ETag, so a
+// release after this is made over the renewed lock and never races the
+// renewal's answer. The renewal comes on h's own ticker; this looks every
+// 5ms.
+func waitRenewal(t *testing.T, h *lease.Held) {
t.Helper()
- deadline := time.Now().Add(5 * time.Second)
- for bytes.Equal(fx.LockBody(prefix), before) {
- if time.Now().After(deadline) {
+ from, err := h.SafeUntil()
+ if err != nil {
+ t.Fatal(err)
+ }
+ tick := time.NewTicker(5 * time.Millisecond)
+ defer tick.Stop()
+ timeout := time.After(5 * time.Second)
+ for {
+ until, err := h.SafeUntil()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if until.After(from) {
+ return
+ }
+ select {
+ case <-tick.C:
+ case <-timeout:
t.Fatal("no renewal")
}
- time.Sleep(20 * time.Millisecond)
}
}
@@ -97,7 +115,7 @@ func TestRenewKeepsCarlosGeneration(t *testing.T) {
if taken.Lock.GenName != want {
t.Fatalf("take wrote %+v", taken.Lock)
}
- waitRenewal(t, fx, "instances/h", fx.LockBody("instances/h"))
+ waitRenewal(t, h)
renewed := lockView(t, fx, "instances/h")
if renewed.Lock.GenName != want || renewed.Lock.Owner != taken.Lock.Owner || renewed.Lock.Generation != 1 || !renewed.Lock.ExpiresAt.After(taken.Lock.ExpiresAt) {
t.Fatalf("renewal wrote %+v over %+v", renewed.Lock, taken.Lock)
@@ -122,7 +140,7 @@ func TestGenerationsOffWritesTodaysLock(t *testing.T) {
}
}
today("take")
- waitRenewal(t, fx, "instances/h", fx.LockBody("instances/h"))
+ waitRenewal(t, h)
today("renewal")
if err := h.Release(ctx); err != nil {
t.Fatal(err)
diff --git a/internal/lease/genpoint_test.go b/internal/lease/genpoint_test.go
index 742e89eff..31503d96a 100644
--- a/internal/lease/genpoint_test.go
+++ b/internal/lease/genpoint_test.go
@@ -14,6 +14,7 @@ import (
"github.com/carlosframework/platform/internal/hafresh"
"github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/lease/leasetest"
"github.com/carlosframework/platform/internal/replicagen"
)
@@ -322,7 +323,8 @@ func TestPointSetsAnExactBound(t *testing.T) {
// take, over it, starts from the pointed generation.
func TestPointFencesADelayedSwitch(t *testing.T) {
haBox(t)
- fx := newGenFixture(t)
+ clock := boxClockAhead(t) // the box's clock, and the store's (its Date header)
+ fx := newGenFixture(t, func(b *leasetest.VersionedBucket) { b.Date = clock.now })
g1, t1 := fx.seed(t, time.Minute, 3)
const ttl = time.Second
h := fx.acquire(t, ttl)
@@ -341,8 +343,9 @@ func TestPointFencesADelayedSwitch(t *testing.T) {
if held.Lock.Release != nil || held.Lock.GenName == "" {
t.Fatalf("fixture: %+v, want a held generations lock", held.Lock)
}
- // The store's clock (whole seconds) past the expiry and its margin.
- time.Sleep(time.Until(held.Lock.ExpiresAt.Add(lease.RenewMargin + 1500*time.Millisecond)))
+ // The store's clock (whole seconds) past the expiry and its margin,
+ // and the box's with it.
+ clock.set(time.Until(held.Lock.ExpiresAt.Add(lease.RenewMargin + 1500*time.Millisecond)))
fx.setPhase("point")
res, err := fx.point(t, g1, t1, true)
diff --git a/internal/lease/genstart_test.go b/internal/lease/genstart_test.go
index c3fab4421..9ed47b6d9 100644
--- a/internal/lease/genstart_test.go
+++ b/internal/lease/genstart_test.go
@@ -11,7 +11,7 @@ import (
"strings"
"sync"
"testing"
- "time"
+ "testing/synctest"
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/superfly/ltx"
@@ -486,35 +486,39 @@ func manyFiles(t *testing.T, m *leasetest.VersionedBucket, n int) lease.StartPla
return p
}
+// In a synctest bubble: once eight copies wait at the gate, synctest.Wait
+// returns only when every goroutine is blocked, so a ninth copy, if one
+// could start, has started by then.
func TestCopyStartRunsAtMostEightCopies(t *testing.T) {
- m := newGenBucket()
- p := manyFiles(t, m, 20)
- cs := newCounting(m)
- full := make(chan struct{})
- gate := make(chan struct{})
- var once sync.Once
- cs.onCopy = func(ctx context.Context, key string, inFlight int) error {
- if inFlight >= 8 {
- once.Do(func() { close(full) })
+ synctest.Test(t, func(t *testing.T) {
+ m := newGenBucket()
+ p := manyFiles(t, m, 20)
+ cs := newCounting(m)
+ full := make(chan struct{})
+ gate := make(chan struct{})
+ var once sync.Once
+ cs.onCopy = func(ctx context.Context, key string, inFlight int) error {
+ if inFlight >= 8 {
+ once.Do(func() { close(full) })
+ }
+ <-gate
+ return nil
}
- <-gate
- return nil
- }
- done := make(chan error, 1)
- go func() { done <- lease.CopyStart(context.Background(), cs, gsBucket, gsLoc, p, gsTo) }()
- select {
- case <-full:
- case <-time.After(5 * time.Second):
- t.Fatal("eight copies never ran at once")
- }
- time.Sleep(50 * time.Millisecond) // room for a ninth to start, if one could
- close(gate)
- if err := <-done; err != nil {
- t.Fatal(err)
- }
- if _, copies, _ := cs.snapshot(); copies != 20 || cs.maxInFlight != 8 {
- t.Fatalf("%d copies, at most %d at once; want 20, 8", copies, cs.maxInFlight)
- }
+ done := make(chan error, 1)
+ go func() { done <- lease.CopyStart(context.Background(), cs, gsBucket, gsLoc, p, gsTo) }()
+ <-full
+ synctest.Wait()
+ if _, copies, _ := cs.snapshot(); copies != 8 {
+ t.Errorf("%d copies started with eight waiting, want 8", copies)
+ }
+ close(gate)
+ if err := <-done; err != nil {
+ t.Fatal(err)
+ }
+ if _, copies, _ := cs.snapshot(); copies != 20 || cs.maxInFlight != 8 {
+ t.Fatalf("%d copies, at most %d at once; want 20, 8", copies, cs.maxInFlight)
+ }
+ })
}
func TestCopyStartReturnsTheFirstErrorAndCancelsTheRest(t *testing.T) {
diff --git a/internal/lease/gentake_minio_test.go b/internal/lease/gentake_minio_test.go
index 3f78e765b..ad8be332d 100644
--- a/internal/lease/gentake_minio_test.go
+++ b/internal/lease/gentake_minio_test.go
@@ -258,11 +258,7 @@ func (m minioGen) take(t *testing.T) {
witnessExec(t, aPath, `INSERT INTO t (body) VALUES ('a-only')`)
synced := make(chan error, 1)
go func() { synced <- a.SyncAndWait(ctx) }()
- for deadline := time.Now().Add(10 * time.Second); len(lw.heldKeys()) == 0; time.Sleep(20 * time.Millisecond) {
- if time.Now().After(deadline) {
- t.Fatal("fixture: no write of A's reached the proxy")
- }
- }
+ lw.awaitHeld(t, "fixture: no write of A's reached the proxy")
boxB()
fx.setPhase("b")
diff --git a/internal/lease/gentake_test.go b/internal/lease/gentake_test.go
index 52144f081..4ed765ed6 100644
--- a/internal/lease/gentake_test.go
+++ b/internal/lease/gentake_test.go
@@ -13,6 +13,7 @@ import (
"slices"
"strings"
"sync"
+ "sync/atomic"
"testing"
"time"
@@ -700,7 +701,7 @@ func TestGenerationWriterRunsRetention(t *testing.T) {
if err := h.Err(); !errors.Is(err, lease.ErrSpent) {
t.Fatalf("fixture: the Held after Replicate: %v, want spent", err)
}
- time.Sleep(1500 * time.Millisecond) // the Open passes
+ awaitOpenPasses()
for i := range 3 {
witnessExec(t, path, fmt.Sprintf(`INSERT INTO t (body) VALUES ('w-%d')`, i))
if err := r.SyncAndWait(ctx); err != nil {
@@ -772,7 +773,7 @@ func TestGenerationWriterRefusesOnceTheLeaseIsLost(t *testing.T) {
if err := r.SyncAndWait(ctx); err != nil {
t.Fatal(err)
}
- time.Sleep(1500 * time.Millisecond) // the Open passes
+ awaitOpenPasses()
lost := errors.New("renewal: AccessDenied")
lease.LoseLeaseForTest(r, lost)
fx.setPhase("lost")
@@ -968,6 +969,23 @@ func TestTakeRequestBudget(t *testing.T) {
}
// lockView is the stored lock, decoded.
+// clockAhead is a clock running ahead of time.Now by what set last gave
+// it: a test moves past an expiry or a marker's opening instead of
+// waiting for it.
+type clockAhead struct{ by atomic.Int64 }
+
+func (c *clockAhead) now() time.Time { return time.Now().Add(time.Duration(c.by.Load())) }
+func (c *clockAhead) set(d time.Duration) { c.by.Store(int64(d)) }
+
+// boxClockAhead makes the box's clock (boxNow: the acquire table's now
+// and a release marker's At) a clockAhead, for t.
+func boxClockAhead(t *testing.T) *clockAhead {
+ t.Helper()
+ c := &clockAhead{}
+ t.Cleanup(lease.SetBoxNowForTest(c.now))
+ return c
+}
+
func (fx *genFixture) lockView(t *testing.T) hafresh.View {
t.Helper()
body, ok := fx.m.Current(fx.bucket, fx.loc+"/lock.json")
@@ -1072,15 +1090,33 @@ func TestHeldLockCarriesTheTakeBound(t *testing.T) {
const ttl = 1500 * time.Millisecond // renewals every 500ms
renewed := func(t *testing.T, fx *genFixture, after hafresh.View) hafresh.View {
t.Helper()
- for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) {
+ wrote := make(chan struct{}, 1)
+ fx.setHook(func(r *http.Request, keys []string) func(int) {
+ if r.Method != http.MethodPut || !slices.Contains(keys, fx.loc+"/lock.json") {
+ return nil
+ }
+ return func(int) {
+ select {
+ case wrote <- struct{}{}:
+ default:
+ }
+ }
+ })
+ defer fx.setHook(nil)
+ timeout := time.After(5 * time.Second)
+ for {
if v := fx.lockView(t); v.Lock.ExpiresAt.After(after.Lock.ExpiresAt) {
return v
}
+ select {
+ case <-wrote:
+ case <-timeout:
+ t.Fatal("no renewal within 5s")
+ }
}
- t.Fatal("no renewal within 5s")
- return hafresh.View{}
}
t.Run("crash-before-switch", func(t *testing.T) {
+ box := boxClockAhead(t)
fx := newGenFixture(t)
_, txid := fx.seed(t, time.Minute, 3)
v := fx.lockView(t)
@@ -1105,7 +1141,8 @@ func TestHeldLockCarriesTheTakeBound(t *testing.T) {
}
// The box dies before its take: no switch, no release.
lease.AbandonHeldForTest(h)
- time.Sleep(time.Until(fx.lockView(t).Lock.ExpiresAt) + 50*time.Millisecond)
+ // The box's clock moves past the dead holder's expiry.
+ box.set(time.Until(fx.lockView(t).Lock.ExpiresAt) + 50*time.Millisecond)
}
// The next take, over the expired held lock (same box, emptiness
// proof), passes no bound: the lease reads it from the held lock.
diff --git a/internal/lease/gentakeover_test.go b/internal/lease/gentakeover_test.go
index 75a706fae..d003e8c1d 100644
--- a/internal/lease/gentakeover_test.go
+++ b/internal/lease/gentakeover_test.go
@@ -36,6 +36,8 @@ type lateWrites struct {
prefix atomic.Pointer[string]
healed chan struct{}
heal func()
+ held chan struct{} // closed when the first write is held
+ holdOnce sync.Once
applied sync.WaitGroup
mu sync.Mutex
keys []string
@@ -43,7 +45,7 @@ type lateWrites struct {
}
func newLateWrites(t *testing.T, fx *genFixture) *lateWrites {
- lw := &lateWrites{healed: make(chan struct{})}
+ lw := &lateWrites{healed: make(chan struct{}), held: make(chan struct{})}
lw.heal = sync.OnceFunc(func() { close(lw.healed) })
t.Cleanup(lw.heal)
fx.setHook(func(r *http.Request, keys []string) func(int) {
@@ -54,6 +56,7 @@ func newLateWrites(t *testing.T, fx *genFixture) *lateWrites {
lw.mu.Lock()
lw.keys = append(lw.keys, keys...)
lw.mu.Unlock()
+ lw.holdOnce.Do(func() { close(lw.held) })
<-lw.healed
return func(status int) {
lw.mu.Lock()
@@ -76,6 +79,16 @@ func (lw *lateWrites) under(keys []string) bool {
return p != nil && slices.ContainsFunc(keys, func(k string) bool { return strings.HasPrefix(k, *p) })
}
+// awaitHeld waits until a write has reached the server and is held.
+func (lw *lateWrites) awaitHeld(t *testing.T, what string) {
+ t.Helper()
+ select {
+ case <-lw.held:
+ case <-time.After(10 * time.Second):
+ t.Fatal(what)
+ }
+}
+
func (lw *lateWrites) heldKeys() []string {
lw.mu.Lock()
defer lw.mu.Unlock()
@@ -194,6 +207,15 @@ func requireHeldNothingWritten(t *testing.T, fx *genFixture, lw *lateWrites, ttl
}
}
+// awaitOpenPasses lets the compaction and snapshot pass a replicating
+// store starts at Open finish. Litestream runs it at Open and, while the
+// database is not ready (its page size is unknown until the first sync),
+// again a second later on its own fixed timer. The store signals neither
+// pass, and what a pass writes depends on the files the generation
+// already holds, so there is nothing to wait on but that timer: this is
+// the generations tests' one sleep (raised in .amadan/code-health.tsv).
+func awaitOpenPasses() { time.Sleep(1500 * time.Millisecond) }
+
// successorOverLateWrite is the successor's part of both witnesses. B
// (holding bHeld, taken while A's write is still held at the proxy)
// starts its generation, restores from it, switches head.json, replicates
@@ -234,10 +256,9 @@ func successorOverLateWrite(t *testing.T, fx *genFixture, lw *lateWrites, bHeld
if err := b.SyncAndWait(ctx); err != nil {
t.Fatal(err)
}
- // B's store runs one compaction and snapshot pass at Open (retried a
- // second later while the database is not ready). Let it finish before
- // B's row, so the row lives only in B's L0 until the compaction below.
- time.Sleep(1500 * time.Millisecond)
+ // Let B's store's Open pass finish before B's row, so the row lives
+ // only in B's L0 until the compaction below.
+ awaitOpenPasses()
witnessExec(t, bPath, `INSERT INTO t (body) VALUES ('b-only')`)
if err := b.SyncAndWait(ctx); err != nil {
t.Fatal(err)
@@ -358,11 +379,7 @@ func TestTerminatedHolderTakenOnProofAlone(t *testing.T) {
witnessExec(t, aPath, `INSERT INTO t (body) VALUES ('a-only')`)
synced := make(chan error, 1)
go func() { synced <- a.SyncAndWait(ctx) }()
- for deadline := time.Now().Add(10 * time.Second); len(lw.heldKeys()) == 0; time.Sleep(20 * time.Millisecond) {
- if time.Now().After(deadline) {
- t.Fatal("fixture: no write of A's reached the server")
- }
- }
+ lw.awaitHeld(t, "fixture: no write of A's reached the server")
v := fx.lockView(t)
if v.Lock.Release != nil || v.Lock.GenName != aGen || !v.Lock.ExpiresAt.After(time.Now().Add(ttl/2)) {
t.Fatalf("A's lock %+v: want held, unexpired, generation %s", v.Lock, aGen)
diff --git a/internal/lease/renew_attempt_test.go b/internal/lease/renew_attempt_test.go
index 6b97dc708..0eff3f786 100644
--- a/internal/lease/renew_attempt_test.go
+++ b/internal/lease/renew_attempt_test.go
@@ -277,8 +277,9 @@ func TestRenewAttemptUsesEarlierSafeUntil(t *testing.T) {
func TestRenewerFirstRenewalCarriesTheBound(t *testing.T) {
const ttl = 300 * time.Millisecond // a renewal every 100ms
backend := &lockStore{}
+ client := landedPuts{backend, make(chan struct{}, 1)}
leaser := lss3.NewLeaser()
- leaser.SetClient(backend)
+ leaser.SetClient(client)
leaser.TTL = ttl
lock, err := leaser.AcquireLease(context.Background())
if err != nil {
@@ -289,7 +290,8 @@ func TestRenewerFirstRenewalCarriesTheBound(t *testing.T) {
backend.mu.Unlock()
var first []byte
renewerStarted = func(*renewer) {
- for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(time.Millisecond) {
+ timeout := time.After(5 * time.Second)
+ for {
backend.mu.Lock()
if backend.puts > acquired {
first = append([]byte(nil), backend.body...)
@@ -297,10 +299,15 @@ func TestRenewerFirstRenewalCarriesTheBound(t *testing.T) {
return
}
backend.mu.Unlock()
+ select {
+ case <-client.landed:
+ case <-timeout:
+ return
+ }
}
}
t.Cleanup(func() { renewerStarted = nil })
- rn := startRenewerGen(backend, leaser, lock, "g-00000000000000000002", 77, time.Now(), marginForTTL(ttl))
+ rn := startRenewerGen(client, leaser, lock, "g-00000000000000000002", 77, time.Now(), marginForTTL(ttl))
renewerStarted = nil
t.Cleanup(func() {
if err := leaser.ReleaseLease(context.Background(), rn.stop()); err != nil {
@@ -314,3 +321,21 @@ func TestRenewerFirstRenewalCarriesTheBound(t *testing.T) {
t.Fatalf("the first renewal wrote %s, want carlos_generation and carlos_min_txid 77", first)
}
}
+
+// landedPuts is a lockStore that says on landed (without blocking) each
+// time a PUT has been applied.
+type landedPuts struct {
+ *lockStore
+ landed chan struct{}
+}
+
+func (s landedPuts) PutObject(ctx context.Context, p *s3.PutObjectInput, opts ...func(*s3.Options)) (*s3.PutObjectOutput, error) {
+ out, err := s.lockStore.PutObject(ctx, p, opts...)
+ if err == nil {
+ select {
+ case s.landed <- struct{}{}:
+ default:
+ }
+ }
+ return out, err
+}
diff --git a/internal/lease/stale_holder_witness_test.go b/internal/lease/stale_holder_witness_test.go
index 2670f57d4..fd0ddf55c 100644
--- a/internal/lease/stale_holder_witness_test.go
+++ b/internal/lease/stale_holder_witness_test.go
@@ -40,6 +40,7 @@ import (
func TestWitnessLateWriteFromAnEarlierHolderKeepsTheSuccessorsHistory(t *testing.T) {
const ttl = 3 * time.Second
haBox(t)
+ box := boxClockAhead(t)
fx := newGenFixture(t)
bucket, prefix, region := fx.bucket, fx.loc, fx.region
@@ -124,7 +125,7 @@ func TestWitnessLateWriteFromAnEarlierHolderKeepsTheSuccessorsHistory(t *testing
if err != nil || v.Lock.Release == nil {
t.Fatalf("A's marker: %+v %v", v.Lock.Release, err)
}
- time.Sleep(time.Until(v.Lock.Release.At.Add(ttl)) + 200*time.Millisecond)
+ box.set(time.Until(v.Lock.Release.At.Add(ttl)) + 200*time.Millisecond) // the box's clock, past the opening
boxB()
fx.setPhase("b")
bPath := filepath.Join(t.TempDir(), "w.example.com.db")
@@ -149,11 +150,10 @@ func TestWitnessLateWriteFromAnEarlierHolderKeepsTheSuccessorsHistory(t *testing
if err := b.SyncAndWait(ctx); err != nil {
t.Fatal(err)
}
- // B's store runs one compaction and snapshot pass at Open (retried a
- // second later while the database is not ready). Let it finish before
- // B's row, so the row lives only in B's L0, as a successor's first
- // writes do until its next compaction.
- time.Sleep(1500 * time.Millisecond)
+ // Let B's store's Open pass (awaitOpenPasses) finish before B's row,
+ // so the row lives only in B's L0, as a successor's first writes do
+ // until its next compaction.
+ awaitOpenPasses()
witnessExec(t, bPath, `INSERT INTO t (body) VALUES ('b-only')`)
if err := b.SyncAndWait(ctx); err != nil {
t.Fatal(err)