carlos / platform Public

activator: fenced waking entries answer 503; deterministic F1 test

Fix round 1 for G6 Task 3 (Astra review).

P1: a request for a waking entry the write fence has marked gets
ErrHALeaseUnavailable at once (haLeaseRefusalLocked). Nothing is
latched or begun there, so the failed wake's cleanup stays the one stop
owner. A wake the fence cancelled sets e.err to ErrHALeaseUnavailable,
so callers already waiting get the lost lease's 503, not the
cancellation's empty answer.

P2: the F1 test runs the wake synchronously with no later request and
asserts the entry is already stopping on StopLeaseLost. An unfenced
control goes awake.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e9f5bb19cdb967c557351ecc97ccc70a17eae069 parent 73d8fc3
3 files changed, +204 −48
  • internal/activator/activator.go +6 −0
  • internal/activator/haleaseloss.go +6 −0
  • internal/activator/writefence_test.go +192 −48

CI failed — run details

Intent

Human

<task-notification> <task-id>baa12eqeg</task-id> <tool-use-id>toolu_019nD8VhC7oBvF8oosP5AKBh</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/1be65f1d-61c8-4308-afb1-2c756edd9c6e/tasks/baa12eqeg.output</output-file> <status>completed</status> <summary>Background command "Wait for fence Task 3 review" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 23.2 g CO₂e (2,900,909 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on g6-fence, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 3dcfada73..a5f21e53a 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -2284,6 +2284,12 @@ func (a *Service) wake(e *actEntry) {
republish = republish || listed
}
e.err = err
+ if e.writeFenced {
+ // A wake the write fence cancelled (writefence.go): every
+ // waiter gets the lost lease's answer, never the cancellation
+ // (which reads as a caller that went away).
+ e.err = fmt.Errorf("%w (write fence: %v)", ErrHALeaseUnavailable, err)
+ }
outcome := &stopObservation{uncertain: true}
if w != nil && w.stopOutcome != nil {
outcome = w.stopOutcome
diff --git a/internal/activator/haleaseloss.go b/internal/activator/haleaseloss.go
index ce1521b94..d3b6c2426 100644
--- a/internal/activator/haleaseloss.go
+++ b/internal/activator/haleaseloss.go
@@ -94,6 +94,12 @@ func haUnexpectedLoss(e *actEntry, err error) bool {
// may spend their handles during release; that alone is not a loss.
func (a *Service) haLeaseRefusalLocked(rt registry.Route) error {
e := a.entries[rt.Host]
+ if e != nil && e.state == actWaking && e.writeFenced {
+ // The write fence cancelled this wake (writefence.go): the failed
+ // wake's cleanup is its one stop owner, so nothing is latched or
+ // begun here, and no request waits on that cleanup.
+ return ErrHALeaseUnavailable
+ }
if e != nil && (e.route.HA || haHeld(nil, e.rep)) && !e.gen.Stateless {
health := servingError(e)
if e.state == actAwake && health != nil {
diff --git a/internal/activator/writefence_test.go b/internal/activator/writefence_test.go
index f7a502013..faf2bbbc6 100644
--- a/internal/activator/writefence_test.go
+++ b/internal/activator/writefence_test.go
@@ -3,11 +3,14 @@ package activator
import (
"context"
"errors"
+ "net/http"
+ "net/http/httptest"
"sync"
"sync/atomic"
"testing"
"time"
+ "github.com/carlosframework/platform/internal/edge"
"github.com/carlosframework/platform/internal/hafresh"
"github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/lease"
@@ -534,69 +537,210 @@ func TestWriteFenceDuringABlockedPublisherOpen(t *testing.T) {
waitClosed(t, "the watcher to end", ended, 5*time.Second)
}
+// wakeDirect wakes s's host the way a request's begin does (one waking
+// entry, then its wake), but synchronously and with no request after it:
+// it returns once the wake goroutine's whole body has run, and nothing
+// else has looked at the entry.
+func wakeDirect(s *haSvc) *actEntry {
+ e := &actEntry{host: s.rt.Host, route: s.rt, state: actWaking, ready: make(chan struct{})}
+ s.a.mu.Lock()
+ s.a.putEntryLocked(s.rt.Host, e)
+ s.a.mu.Unlock()
+ s.a.wake(e)
+ return e
+}
+
// F1: the event lands after doWake has returned and before the entry is
-// awake, when cancelling the wake does nothing. The awake transition reads
-// the mark and begins the stop there, so the entry is never awake (OnWake,
-// which that transition calls only for an awake entry, never hears of it):
-// one stop, one release, and the request is answered 503, never served.
+// awake, when cancelling the wake does nothing. The wake's own awake
+// transition reads the mark and begins StopLeaseLost: with no request
+// after the wake and the wake joined, the entry is already stopping. The
+// unfenced control goes awake. Then one stop, one release, and 503.
func TestWriteFenceBetweenWakeAndAwake(t *testing.T) {
- s := haService(t, "shop.example.com")
- reps := retainFenceRep(s, nil)
- fenceCleanup(t, s, nil)
- var woken atomic.Int32
- s.a.OnWake = func(registry.Route) { woken.Add(1) }
- var r *fenceTestRep
- var e *actEntry
- var once sync.Once
- s.a.wakeReturned = func(host string) {
- once.Do(func() {
- select {
- case r = <-reps:
- default:
- t.Error("the wake started no replica")
- return
+ for _, fenced := range []bool{false, true} {
+ t.Run(map[bool]string{false: "control", true: "fenced"}[fenced], func(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ reps := retainFenceRep(s, nil)
+ fenceCleanup(t, s, nil)
+ var r *fenceTestRep
+ var once sync.Once
+ s.a.wakeReturned = func(host string) {
+ once.Do(func() {
+ select {
+ case r = <-reps:
+ default:
+ t.Fatal("the wake started no replica")
+ }
+ if !fenced {
+ return
+ }
+ s.a.mu.Lock()
+ e := s.a.entries[host]
+ s.a.mu.Unlock()
+ r.trip()
+ // The watcher acts while the entry is still waking:
+ // its cancel finds a wake that has already returned.
+ waitFenced(t, s, e)
+ })
+ }
+ e := wakeDirect(s)
+ if r == nil {
+ t.Fatal("the hook never ran")
}
s.a.mu.Lock()
- e = s.a.entries[host]
+ state, why, stop, marked, werr := e.state, e.stopWhy, e.stopped, e.writeFenced, e.err
s.a.mu.Unlock()
- r.trip()
- // The watcher acts while the entry is still waking: its
- // cancel finds a wake that has already returned.
- for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(10 * time.Millisecond) {
- s.a.mu.Lock()
- marked := e.writeFenced
- s.a.mu.Unlock()
- if marked {
- return
- }
- if time.Now().After(deadline) {
- t.Error("the watcher never marked the waking entry")
- return
+ if werr != nil {
+ t.Fatalf("the wake failed: %v", werr)
+ }
+ if !fenced {
+ if state != actAwake || stop != nil || marked {
+ t.Fatalf("control: state %v, stop began %v, marked %v; want awake", state, stop != nil, marked)
}
+ s.stopForTest(e)
+ assertOneRelease(t, s, r)
+ return
+ }
+ if state != actStopping || why != StopLeaseLost || stop == nil {
+ t.Fatalf("after the wake: state %v, reason %q, stop began %v; want stopping on %q", state, why, stop != nil, StopLeaseLost)
}
+ haRouteOn(t, s, nil)
+ assertLostResponse(t, s)
+ waitClosed(t, "the stop", stop, 10*time.Second)
+ assertOneRelease(t, s, r)
})
}
- _, err := s.wakeForTest(context.Background())
- if !errors.Is(err, ErrHALeaseUnavailable) {
- t.Fatalf("the request after the event: %v, want %v", err, ErrHALeaseUnavailable)
+}
+
+// servedAnswer is one member request's answer through ServeHTTP.
+type servedAnswer struct {
+ code int
+ header http.Header
+ body string
+ proxied bool
+}
+
+func serveRequest(s *haSvc, ctx context.Context) servedAnswer {
+ req := httptest.NewRequest("GET", "http://shop.example.com/", nil).WithContext(ctx)
+ w := httptest.NewRecorder()
+ var proxied atomic.Bool
+ s.a.ServeHTTP(w, req, s.rt, http.HandlerFunc(func(http.ResponseWriter, *http.Request) { proxied.Store(true) }))
+ return servedAnswer{code: w.Code, header: w.Header(), body: w.Body.String(), proxied: proxied.Load()}
+}
+
+func assertLostAnswer(t *testing.T, a servedAnswer) {
+ t.Helper()
+ if a.code != 503 || a.header.Get("Retry-After") != "10" || a.header.Get("X-Carlos-Holder") != "none" || a.body != edge.HAUnavailableMessage+"\n" || a.proxied {
+ t.Errorf("answer: status=%d headers=%v body=%q proxy=%v; want the lost lease's 503", a.code, a.header, a.body, a.proxied)
}
- if r == nil || e == nil {
- t.Fatal("the hook never ran")
+}
+
+// fencedPublisherWake starts s's wake whose files publisher's open blocks
+// on the store, and returns once that open is blocked: the replica, and
+// the waking entry (captured as replication starts).
+func fencedPublisherWake(t *testing.T, s *haSvc, start func()) (*fenceTestRep, *blockingFilesStore, func() *actEntry) {
+ t.Helper()
+ store := &blockingFilesStore{Store: s.b.FilesStore, entered: make(chan struct{}), quit: make(chan struct{})}
+ s.b.FilesStore = store
+ t.Cleanup(func() { close(store.quit) })
+ var wakeEntry atomic.Pointer[actEntry]
+ reps := retainFenceRep(s, func(*fenceTestRep) {
+ s.a.mu.Lock()
+ wakeEntry.Store(s.a.entries[s.rt.Host])
+ s.a.mu.Unlock()
+ s.b.haWakes.takeFiles(s.rt.Host)
+ store.armed.Store(true)
+ })
+ fenceCleanup(t, s, nil)
+ start()
+ var r *fenceTestRep
+ select {
+ case r = <-reps:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the wake never started replication")
+ }
+ waitClosed(t, "the publisher's open to block", store.entered, 10*time.Second)
+ return r, store, wakeEntry.Load
+}
+
+// A fenced waking entry answers a new request with the lost lease's 503
+// at once, while its failed wake's cleanup (its one stop owner) is still
+// running: the request neither waits on that cleanup nor starts a stop.
+func TestWriteFenceWakingAnswersAtOnce(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ haRouteOn(t, s, nil)
+ cleaning, release := make(chan struct{}), make(chan struct{})
+ var releaseOnce, cleanOnce sync.Once
+ open := func() { releaseOnce.Do(func() { close(release) }) }
+ t.Cleanup(open)
+ prev := s.ctl.stopHook
+ s.ctl.stopHook = func(id string, role instancectl.Role) {
+ cleanOnce.Do(func() {
+ close(cleaning)
+ <-release
+ })
+ if prev != nil {
+ prev(id, role)
+ }
}
+ woke := make(chan error, 1)
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ t.Cleanup(cancel)
+ r, store, entry := fencedPublisherWake(t, s, func() {
+ go func() {
+ _, err := s.wakeForTest(ctx)
+ woke <- err
+ }()
+ })
+ r.trip()
+ store.armed.Store(false)
+ e := entry()
+ waitFenced(t, s, e)
+ waitClosed(t, "the failed wake's cleanup to block", cleaning, 10*time.Second)
s.a.mu.Lock()
- why, stop := e.stopWhy, e.stopped
+ state, current := e.state, s.a.entries[s.rt.Host]
s.a.mu.Unlock()
- if why != StopLeaseLost || stop == nil {
- t.Fatalf("stop reason %q, began %v; want %q", why, stop != nil, StopLeaseLost)
+ if state != actWaking || current != e {
+ t.Fatalf("the cleanup is blocked, yet the entry is %v (current %v)", state, current == e)
}
- haRouteOn(t, s, nil)
assertLostResponse(t, s)
- waitClosed(t, "the stop", stop, 10*time.Second)
- assertOneRelease(t, s, r)
- // OnWake runs on its own goroutine, started before e.ready closed:
- // by the stop's end it has run, had the entry been awake.
- if n := woken.Load(); n != 0 {
- t.Errorf("the fenced entry was reported woken %d times: it was awake", n)
+ s.a.mu.Lock()
+ began := e.stopped != nil
+ s.a.mu.Unlock()
+ if began {
+ t.Fatal("the request began a stop on the waking entry")
+ }
+ open()
+ select {
+ case err := <-woke:
+ if !errors.Is(err, ErrHALeaseUnavailable) {
+ t.Errorf("the wake's own caller: %v, want %v", err, ErrHALeaseUnavailable)
+ }
+ case <-time.After(15 * time.Second):
+ t.Fatal("the wake did not end")
+ }
+ if c := r.closes.Load(); c != 1 {
+ t.Errorf("the replica closed %d times, want the failed wake's one close", c)
+ }
+}
+
+// A caller already waiting on the wake when the event cancels it gets the
+// lost lease's 503, never the cancellation's empty answer.
+func TestWriteFenceWaitingCallerGetsTheLossAnswer(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ haRouteOn(t, s, nil)
+ answered := make(chan servedAnswer, 1)
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ t.Cleanup(cancel)
+ r, store, _ := fencedPublisherWake(t, s, func() {
+ go func() { answered <- serveRequest(s, ctx) }()
+ })
+ r.trip()
+ store.armed.Store(false)
+ select {
+ case a := <-answered:
+ assertLostAnswer(t, a)
+ case <-time.After(15 * time.Second):
+ t.Fatal("the waiting caller got no answer")
}
}