Merge pull request #253 from seaweedfs/test/227-part2

test: #227 part 2: handshakes and progress conditions instead of wall-clock bounds
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-19 19:56:26 -08:00
commit 139ff04d1d
7 files changed
+145 -81

No files matched your search

@@ -37,7 +37,9 @@ func (v *arrivingAssignment) Projection() frontend.Projection {
}
func TestRestoreWaitsForFirstAssignment(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
// No wall-clock bound (#227): every wait below is a progress condition; a
// hang is reported by the go test timeout.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})}
p := chunkProviderForAssignment(t, v)
@@ -49,34 +51,21 @@ func TestRestoreWaitsForFirstAssignment(t *testing.T) {
defer finishRecovery()
done := make(chan error, 1)
go func() { _, err := p.RecoverVolume(recoverCtx, "v1"); done <- err }()
select {
case <-v.seen:
case <-ctx.Done():
t.Fatal("recovery never inspected assignment")
}
select {
case err := <-done:
if err != nil {
t.Fatalf("first assignment did not converge: %v", err)
}
case <-ctx.Done():
t.Fatal("local recovery must settle before assignment can be applied")
<-v.seen // recovery inspected the assignment
if err := <-done; err != nil { // local recovery settles before assignment can be applied
t.Fatalf("first assignment did not converge: %v", err)
}
if statuses := p.DurableStatuses(); len(statuses) != 1 || statuses[0].Operational {
t.Fatalf("unassigned backend became operational: %+v", statuses)
}
finishRecovery() // deferred attachment outlives a completed recovery caller
close(v.assigned)
for {
for { // progress: the deferred attachment becomes operational
statuses := p.DurableStatuses()
if len(statuses) == 1 && statuses[0].Operational {
break
}
select {
case <-ctx.Done():
t.Fatalf("assignment never became operational: %+v", statuses)
case <-time.After(time.Millisecond):
}
time.Sleep(time.Millisecond)
}
if _, err := p.CaptureVolume(ctx, "v1"); err != nil {
t.Fatal(err)
@@ -121,19 +110,10 @@ func TestRestoreDeferredAssignmentWaitEndsOnDeadlineAndClose(t *testing.T) {
defer cancel()
done := make(chan error, 1)
go func() { _, err := p.RecoverVolume(ctx, "v1"); done <- err }()
select {
case <-v.seen:
case <-time.After(2 * time.Second):
t.Fatal("no assignment inspection")
}
<-v.seen // progress, no timer (#227): recovery inspected the assignment
// Local recovery must return first, so the host can apply assignment.
select {
case err := <-done:
if err != nil {
t.Fatal(err)
}
case <-time.After(2 * time.Second):
t.Fatal("local recovery blocked on assignment")
if err := <-done; err != nil {
t.Fatal(err)
}
cancel() // recovery caller no longer owns the deferred worker
if mode == "close" {
@@ -144,18 +124,15 @@ func TestRestoreDeferredAssignmentWaitEndsOnDeadlineAndClose(t *testing.T) {
if mode == "close" {
return
}
deadline := time.NewTimer(2 * time.Second)
defer deadline.Stop()
for {
for { // progress: the 40 ms assignment limit fails the wait closed
status := p.DurableStatuses()
if len(status) == 1 && !status[0].Operational && strings.Contains(status[0].Evidence, "deadline exceeded") {
break
}
select {
case <-deadline.C:
t.Fatalf("assignment wait did not fail closed: %+v", status)
case <-time.After(time.Millisecond):
if len(status) == 1 && status[0].Operational {
t.Fatalf("became operational without an assignment: %+v", status)
}
time.Sleep(time.Millisecond)
}
})
}
@@ -96,14 +96,10 @@ func TestWALStoreChunk_ExplicitCutRestartsTheTimer(t *testing.T) {
if h := headGen(t, remote); h.Gen != 1 {
t.Fatalf("automatic cut %s after the explicit one (HEAD gen %d): the timer did not restart", time.Since(explicit), h.Gen)
}
deadline := explicit.Add(interval + 5*time.Second)
for {
if h := headGen(t, remote); h.Gen >= 2 {
return
}
if time.Now().After(deadline) {
t.Fatal("no automatic cut one interval after the explicit cut")
}
// Progress, no timer (#227): the automatic cut follows; a loaded host only
// delays it (the early-cut check above is the timing assertion, and it
// skips when the host cannot separate the two deadlines).
for headGen(t, remote).Gen < 2 {
time.Sleep(50 * time.Millisecond)
}
}
@@ -77,6 +77,7 @@ type runtimeLeaseServer struct {
mu sync.Mutex
ttl time.Duration
disabled, blocked, revoking bool
blockedCalls int // renewals that arrived while blocked
acks int
ackGen uint64
first chan struct{}
@@ -93,6 +94,9 @@ func (s *runtimeLeaseServer) RenewWorkspaceLease(ctx context.Context, id *contro
return nil, status.Error(codes.FailedPrecondition, "workspace RPC disabled")
}
if blocked {
s.mu.Lock()
s.blockedCalls++
s.mu.Unlock()
<-ctx.Done()
return nil, ctx.Err()
}
@@ -164,7 +168,10 @@ func TestWorkspaceHostLeaseExpiryAndRevokeCloseRealProvider(t *testing.T) {
for _, kind := range []string{"expiry-stalled-renewal", "detach-then-revoke", "cancel"} {
t.Run(kind, func(t *testing.T) {
var stopped atomic.Bool
wire := &runtimeLeaseServer{ttl: 300 * time.Millisecond, stopped: &stopped}
// A 3 s lease while the volume is set up (#227: a 300 ms lease could
// expire under load before the detach/cut steps ran); the expiry case
// switches to 300 ms below.
wire := &runtimeLeaseServer{ttl: 3 * time.Second, stopped: &stopped}
h := workspaceRuntimeHost(t, runtimeWire(t, wire), true)
p, remote := runtimeStore(t, h)
ctx, cancel := context.WithCancel(context.Background())
@@ -213,9 +220,39 @@ func TestWorkspaceHostLeaseExpiryAndRevokeCloseRealProvider(t *testing.T) {
wire.mu.Unlock()
}
if kind == "expiry-stalled-renewal" {
// Shorten the lease and wait (progress) until the client guard
// installed a 300 ms horizon; then stall renewals and wait until a
// renewal arrived blocked: the client holds a short lease that is
// not renewed.
guard := h.view.workspaceGuard.Load()
if guard == nil {
t.Fatal("no workspace lease guard")
}
guard.mu.Lock()
lastUntil := guard.until // the current 3 s horizon
guard.mu.Unlock()
wire.mu.Lock()
wire.ttl = 300 * time.Millisecond
wire.mu.Unlock()
// Witness on the client: the host's guard installed a 300 ms
// horizon (a newly installed deadline less than 1 s ahead; the 3 s
// grants install about 3 s ahead).
runtimeAwait(t, "the guard installed a 300 ms grant", func() bool {
guard.mu.Lock()
until, fenced := guard.until, guard.fenced
guard.mu.Unlock()
installed := !fenced && !until.Equal(lastUntil) && until.Sub(time.Now()) < time.Second
lastUntil = until
return installed
})
wire.mu.Lock()
wire.blocked = true
wire.mu.Unlock()
runtimeAwait(t, "a renewal stalled after a 300 ms grant", func() bool {
wire.mu.Lock()
defer wire.mu.Unlock()
return wire.blockedCalls > 0
})
}
if kind == "cancel" {
cancel()
@@ -52,7 +52,7 @@ func TestChunkLayerV3_BASEBeginDrainsWholeCut(t *testing.T) {
}
entered, release := holdPuts(t, f)
cutDone := startCapture(t, l)
waitKey(t, entered, "held cut upload after barrier")
<-entered // progress, no timer (#227): the cut's upload is held after its barrier
attempted := make(chan struct{})
l.testBaseTransitionBeforeLock = func() { close(attempted) }
type result struct {
@@ -70,26 +70,17 @@ func TestChunkLayerV3_BASEBeginDrainsWholeCut(t *testing.T) {
}
})
go func() { defer close(joined); h, e := s.BeginBaseInstall(7, idA); finished <- result{h, e} }()
select {
case <-attempted:
case <-time.After(ctLocalBound):
t.Fatal("BASE did not reach outer drain")
}
<-attempted // BASE reached the outer drain
select {
case r := <-finished:
t.Fatalf("BASE begin completed before the captured upload/CAS drained: %v", r.err)
case <-time.After(200 * time.Millisecond):
}
release()
if e := waitErr(t, cutDone, "old cut settlement"); e != nil {
if e := <-cutDone; e != nil { // the old cut settles once released
t.Fatal(e)
}
var r result
select {
case r = <-finished:
case <-time.After(ctLocalBound):
t.Fatal("BASE begin failed to resume after cut settled")
}
r := <-finished // BASE begin resumes after the cut settled
if r.err != nil {
t.Fatal(r.err)
}
@@ -357,6 +357,15 @@ func TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap(t *tes
if err != nil {
t.Fatal(err)
}
// The simulated crash below cannot leave the automatic flusher using the
// descriptor (its reopen raced that close: "volume locked", #227); this
// test drives the flush by hand. Stop it before writes, as walstore_test.
s.DisableAutoFlushForRecoveryTest()
select {
case <-s.flusher.doneCh:
default:
t.Fatal("automatic flusher still running")
}
writeSynced(t, s, 1, 3)
before := s.v3.pub.current()
if err := s.flusher.flushOnceInternal(false); err != nil {
@@ -54,32 +54,27 @@ func g1Lineage(sess, epoch uint64) RecoveryLineage {
}
// g1Ship sends one ship on a fresh connection and reports whether it was
// applied (bytes visible within d) or refused (connection closed).
// applied or refused (g2Refused's probe handshake: an accepted ship is applied
// before the probe is answered), and checks the effect agrees.
func g1Ship(t *testing.T, ln *ReplicaListener, store storage.LogicalStorage, l RecoveryLineage, lsn uint64, fill byte) bool {
t.Helper()
want := bytes.Repeat([]byte{fill}, 4096)
if g2Refused(t, ln.Addr(), MsgShipEntry, EncodeShipEntry(ShipEntry{Lineage: l, LBA: 0, LSN: lsn, Data: want})) {
if bytes.Equal(g1Block(t, store), want) {
t.Fatalf("epoch-%d ship refused yet its bytes were applied", l.Epoch)
}
return false
refused := g2Refused(t, ln.Addr(), MsgShipEntry, EncodeShipEntry(ShipEntry{Lineage: l, LBA: 0, LSN: lsn, Data: want}))
applied := bytes.Equal(g1Block(t, store), want)
if refused && applied {
t.Fatalf("epoch-%d ship refused yet its bytes were applied", l.Epoch)
}
deadline := time.Now().Add(2 * time.Second)
for !bytes.Equal(g1Block(t, store), want) {
if time.Now().After(deadline) {
t.Fatalf("epoch-%d ship neither refused nor applied", l.Epoch)
}
time.Sleep(5 * time.Millisecond)
if !refused && !applied {
t.Fatalf("epoch-%d ship accepted but its bytes are not visible after the probe answer", l.Epoch)
}
return true
return !refused
}
// g1Barrier sends a barrier and reports whether it was ACKed (a barrier
// response echoing the lineage) or refused (connection closed, no ACK).
func g1Barrier(t *testing.T, ln *ReplicaListener, l RecoveryLineage) bool {
t.Helper()
conn := g2Dial(t, ln.Addr())
_ = conn.SetDeadline(time.Now().Add(2 * time.Second))
conn := g2Dial(t, ln.Addr()) // no deadline: the listener answers or closes
if err := WriteMsg(conn, MsgBarrierReq, EncodeLineage(l)); err != nil {
t.Fatal(err)
}
@@ -331,6 +326,49 @@ func TestG1_PersistFailureRefusesTheRaisingMutation(t *testing.T) {
}
}
// A refusal that is slow (a loaded machine; here a persist failure delayed
// past the old 500 ms read window) is still classified as a refusal: the
// probe handshake waits for the listener's answer or close, not a timer.
func TestG1_SlowPersistFailureIsStillARefusal(t *testing.T) {
store := storage.NewBlockStore(16, 4096)
floor := g1Fresh(t)
ln := g1Listener(t, store, floor)
if err := ln.AdmitAsReplica(1); err != nil {
t.Fatal(err)
}
ops := osFloorOps
ops.rename = func(string, string) error {
time.Sleep(700 * time.Millisecond) // injected slowness, not a bound
return errors.New("injected slow rename failure")
}
floorFS = ops
t.Cleanup(func() { floorFS = osFloorOps })
if g1Ship(t, ln, store, g1Lineage(1, 2), 1, 's') {
t.Fatal("a slow refused ship was classified as applied")
}
}
// The probe handshake classifies by effect: an accepted ship's bytes are
// visible after the probe answer, a refused ship's never are, including a
// refused ship below an accepted higher epoch (the probe stays admissible).
func TestG1_ProbeHandshakeClassifiesByEffect(t *testing.T) {
store := storage.NewBlockStore(16, 4096)
floor := g1Fresh(t)
ln := g1Listener(t, store, floor)
if err := ln.AdmitAsReplica(3); err != nil {
t.Fatal(err)
}
if !g1Ship(t, ln, store, g1Lineage(1, 3), 1, 'a') {
t.Fatal("an epoch-3 ship at the admitted epoch was classified refused")
}
if g1Ship(t, ln, store, g1Lineage(2, 2), 2, 'b') {
t.Fatal("an epoch-2 ship below the admitted epoch was classified accepted")
}
if !bytes.Equal(g1Block(t, store), bytes.Repeat([]byte{'a'}, 4096)) {
t.Fatal("the refused ship changed the block")
}
}
// The role calls persist before they return; a persist failure is returned
// and nothing changes (an unassigned listener stays unassigned).
func TestG1_RoleCallsPersistBeforeReturning(t *testing.T) {
@@ -1,9 +1,7 @@
package transport
import (
"errors"
"net"
"os"
"testing"
"time"
@@ -24,17 +22,35 @@ func g2Dial(t *testing.T, addr string) net.Conn {
return conn
}
// g2ProbeLineage is always admissible for a probe: probes are refused only
// below the active (epoch, endpointVersion), and no test reaches this epoch.
// Probes never change listener state.
var g2ProbeLineage = RecoveryLineage{SessionID: 1, Epoch: 1 << 62, EndpointVersion: 1, TargetLSN: 1}
// g2Refused sends one mutating frame and reports whether the listener closed
// the connection (refusal) rather than leaving it open (accepted).
// the connection (refusal) rather than accepting it. Handshake, no timer: an
// always-admissible probe follows on the same connection; the listener
// handles frames in order, so it either closes the connection (refused) or
// answers the probe after the frame's effect (accepted). A write or read error
// on the probe counts as refused: the listener is the only side that closes
// this connection, and it closes it only on a refusal.
func g2Refused(t *testing.T, addr string, msgType byte, payload []byte) bool {
t.Helper()
conn := g2Dial(t, addr)
if err := WriteMsg(conn, msgType, payload); err != nil {
t.Fatal(err)
}
_ = conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
_, err := conn.Read(make([]byte, 1))
return err != nil && !errors.Is(err, os.ErrDeadlineExceeded)
if err := WriteMsg(conn, MsgProbeReq, EncodeProbeReq(ProbeRequest{Lineage: g2ProbeLineage})); err != nil {
return true // the listener already closed the connection
}
replyType, _, err := ReadMsg(conn)
if err != nil {
return true
}
if replyType != MsgProbeResp {
t.Fatalf("frame 0x%02x followed by a probe answered 0x%02x", msgType, replyType)
}
return false
}
func g2ShipPayload(l RecoveryLineage, lsn uint64) []byte {