carlos / platform Public

region-ha p1b-1: Confirmer single-flights describes per owner and builds one client

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev cee5095c46a4e5dbdb0a0b4510c3665d782e98e5 parent 779775e
2 files changed, +253 −36
  • internal/termfence/confirm.go +73 −36
  • internal/termfence/confirm_test.go +180 −0
diff --git a/internal/termfence/confirm.go b/internal/termfence/confirm.go
index 0c61ffb0a..dddb64e45 100644
--- a/internal/termfence/confirm.go
+++ b/internal/termfence/confirm.go
@@ -52,8 +52,8 @@ func SameAccountTerminated(self boxid.Cloud, iid string, o Observation) error {
// EC2 in this box's own account and region and nowhere else. One describe
// per instance id per TTL; the cache lives as long as the process.
type Confirmer struct {
- // API builds the EC2 client for region. It is called once, on the
- // first describe, and the client is kept.
+ // API builds the EC2 client for region. It is called until it first
+ // succeeds, never concurrently, and the client it returns is kept.
API func(ctx context.Context, region string) (EC2, error)
// Self is this box's proven cloud identity.
Self func() boxid.Cloud
@@ -62,10 +62,13 @@ type Confirmer struct {
// Logf is log.Printf when nil.
Logf func(string, ...any)
- mu sync.Mutex
- api EC2
- cache map[string]confirmed
- evident map[string]bool // instances whose first evidence is logged
+ apiMu sync.Mutex // serializes client construction; spans every iid
+ api EC2
+
+ mu sync.Mutex // guards the fields below; never held across a call out
+ cache map[string]confirmed
+ inflight map[string]*flight
+ evident map[string]bool // instances whose first evidence is logged
}
type confirmed struct {
@@ -74,6 +77,14 @@ type confirmed struct {
err error
}
+// flight is the one describe in progress for an instance id. Waiters take
+// its answer; res is written before done is closed.
+type flight struct {
+ done chan struct{}
+ res confirmed
+ waiters int
+}
+
func (c *Confirmer) now() time.Time {
if c.Now != nil {
return c.Now()
@@ -94,6 +105,10 @@ func (c *Confirmer) logf(format string, a ...any) {
// a describe does not prove: another state, another account or region, an
// instance AWS no longer lists. A describe failure, or a Self that is not
// a complete identity, is an error.
+//
+// At most one describe per instance id is in flight: callers that arrive
+// while one runs wait for it and take its answer, and the answer is cached
+// before they are released.
func (c *Confirmer) Terminated(ctx context.Context, iid string) (bool, error) {
self := c.Self()
if !self.Complete() {
@@ -102,54 +117,76 @@ func (c *Confirmer) Terminated(ctx context.Context, iid string) (bool, error) {
if iid == "" || iid == self.InstanceID {
return false, nil
}
- if e, ok := c.cached(iid); ok {
+ c.mu.Lock()
+ if e, ok := c.cache[iid]; ok && c.now().Before(e.until) {
+ c.mu.Unlock()
return e.yes, e.err
}
- e := c.ask(ctx, self, iid)
- ttl := ConfirmNegativeTTL
- if e.yes {
- ttl = ConfirmPositiveTTL
+ if f, ok := c.inflight[iid]; ok {
+ f.waiters++
+ c.mu.Unlock()
+ select {
+ case <-f.done:
+ return f.res.yes, f.res.err
+ case <-ctx.Done():
+ return false, ctx.Err()
+ }
}
- e.until = c.now().Add(ttl)
- c.mu.Lock()
- if c.cache == nil {
- c.cache = map[string]confirmed{}
+ f := &flight{done: make(chan struct{})}
+ if c.inflight == nil {
+ c.inflight = map[string]*flight{}
}
- c.cache[iid] = e
+ c.inflight[iid] = f
c.mu.Unlock()
- return e.yes, e.err
+
+ // Publish and release even if ask panics.
+ f.res = confirmed{err: errors.New("termfence: the describe did not finish")}
+ defer func() {
+ c.publish(iid, f)
+ close(f.done)
+ }()
+ f.res = c.ask(ctx, self, iid)
+ return f.res.yes, f.res.err
}
-func (c *Confirmer) cached(iid string) (confirmed, bool) {
+// publish caches f's answer and ends the flight, in one step under the
+// mutex. An unexpired positive answer is never replaced by a negative or an
+// error.
+func (c *Confirmer) publish(iid string, f *flight) {
c.mu.Lock()
defer c.mu.Unlock()
- e, ok := c.cache[iid]
- if !ok || !c.now().Before(e.until) {
- return confirmed{}, false
+ delete(c.inflight, iid)
+ now := c.now()
+ if old, ok := c.cache[iid]; ok && old.yes && now.Before(old.until) && !f.res.yes {
+ f.res = old
+ return
+ }
+ ttl := ConfirmNegativeTTL
+ if f.res.yes {
+ ttl = ConfirmPositiveTTL
+ }
+ f.res.until = now.Add(ttl)
+ if c.cache == nil {
+ c.cache = map[string]confirmed{}
}
- return e, true
+ c.cache[iid] = f.res
}
-// client returns the kept client, building it on first use. The mutex is
-// not held across API: two first callers may each build one, and the first
-// to finish is kept.
+// client returns the kept client, building it on first use. Construction is
+// serialized across instance ids, the first success is kept, and a failure
+// is not: the next call tries again.
func (c *Confirmer) client(ctx context.Context, region string) (EC2, error) {
- c.mu.Lock()
- api := c.api
- c.mu.Unlock()
- if api != nil {
- return api, nil
+ c.apiMu.Lock()
+ defer c.apiMu.Unlock()
+ if c.api != nil {
+ return c.api, nil
}
api, err := c.API(ctx, region)
if err != nil {
return nil, err
}
- c.mu.Lock()
- defer c.mu.Unlock()
- if c.api == nil {
- c.api = api
- }
- return c.api, nil
+ c.api = api
+ return api, nil
}
// ask makes one describe and decides. The mutex is not held across it.
diff --git a/internal/termfence/confirm_test.go b/internal/termfence/confirm_test.go
index 67a729d21..ea937d816 100644
--- a/internal/termfence/confirm_test.go
+++ b/internal/termfence/confirm_test.go
@@ -6,9 +6,11 @@ import (
"fmt"
"strings"
"sync"
+ "sync/atomic"
"testing"
"time"
+ "github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service/ec2/types"
@@ -211,3 +213,181 @@ func TestConfirmNegativeCachedTenSeconds(t *testing.T) {
t.Fatalf("after ttl: got %v, %v, %d describes", ok, err, len(r.f.regions))
}
}
+
+// gatedEC2 answers every describe with out once release is closed, and
+// counts the calls. entered gets a value each time a describe starts.
+type gatedEC2 struct {
+ out *ec2.DescribeInstancesOutput
+ calls atomic.Int32
+ entered chan string
+ release chan struct{}
+}
+
+func (g *gatedEC2) DescribeInstances(_ context.Context, in *ec2.DescribeInstancesInput, _ ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) {
+ g.calls.Add(1)
+ g.entered <- in.InstanceIds[0]
+ <-g.release
+ out := *g.out
+ out.Reservations = []types.Reservation{{OwnerId: g.out.Reservations[0].OwnerId,
+ Instances: []types.Instance{{InstanceId: aws.String(in.InstanceIds[0]), State: g.out.Reservations[0].Instances[0].State}}}}
+ return &out, nil
+}
+
+func (c *Confirmer) waitersFor(iid string) int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if f, ok := c.inflight[iid]; ok {
+ return f.waiters
+ }
+ return -1
+}
+
+func TestConfirmConcurrentCallersShareOneDescribe(t *testing.T) {
+ const n = 8
+ g := &gatedEC2{out: describe("111122223333", "i-b", types.InstanceStateNameTerminated),
+ entered: make(chan string, n), release: make(chan struct{})}
+ r := newConfirmRig(&fakeEC2{})
+ r.c.API = func(context.Context, string) (EC2, error) { return g, nil }
+ var wg sync.WaitGroup
+ got := make([]bool, n)
+ errs := make([]error, n)
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ got[i], errs[i] = r.c.Terminated(context.Background(), "i-b")
+ }()
+ }
+ <-g.entered // the one describe is in flight; the rest must queue behind it
+ for r.c.waitersFor("i-b") != n-1 {
+ time.Sleep(time.Millisecond)
+ }
+ close(g.release)
+ wg.Wait()
+ for i := range got {
+ if !got[i] || errs[i] != nil {
+ t.Fatalf("caller %d: %v, %v", i, got[i], errs[i])
+ }
+ }
+ if g.calls.Load() != 1 || r.count("termfence: describe i-b") != 1 || r.count("termfence: i-b confirmed") != 1 {
+ t.Fatalf("describes %d, logs %q", g.calls.Load(), r.logs)
+ }
+ // The answer was cached before the waiters left.
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); !ok || err != nil || g.calls.Load() != 1 {
+ t.Fatalf("after: %v, %v, %d describes", ok, err, g.calls.Load())
+ }
+}
+
+func TestConfirmWaiterLeavesWhenItsContextEnds(t *testing.T) {
+ g := &gatedEC2{out: describe("111122223333", "i-b", types.InstanceStateNameTerminated),
+ entered: make(chan string, 2), release: make(chan struct{})}
+ r := newConfirmRig(&fakeEC2{})
+ r.c.API = func(context.Context, string) (EC2, error) { return g, nil }
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ r.c.Terminated(context.Background(), "i-b")
+ }()
+ <-g.entered
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if ok, err := r.c.Terminated(ctx, "i-b"); ok || !errors.Is(err, context.Canceled) {
+ t.Fatalf("got %v, %v", ok, err)
+ }
+ close(g.release)
+ <-done
+}
+
+func TestConfirmPositiveIsNeverOverwrittenByANegative(t *testing.T) {
+ r := newConfirmRig(&fakeEC2{out: describe("111122223333", "i-b", types.InstanceStateNameTerminated)})
+ t0 := r.at
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); !ok || err != nil {
+ t.Fatalf("got %v, %v", ok, err)
+ }
+ // A later reply that says running, or fails, is not even asked for.
+ r.f.out = describe("111122223333", "i-b", types.InstanceStateNameRunning)
+ for _, d := range []time.Duration{11 * time.Second, time.Hour, 23 * time.Hour} {
+ r.at = t0.Add(d)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); !ok || err != nil {
+ t.Fatalf("at %v: %v, %v", d, ok, err)
+ }
+ }
+ if len(r.f.regions) != 1 {
+ t.Fatalf("describes %d", len(r.f.regions))
+ }
+ // And a negative that finishes late, publishing over an unexpired
+ // positive, leaves the positive in place and answers with it.
+ late := &flight{done: make(chan struct{}), res: confirmed{}}
+ r.c.mu.Lock()
+ r.c.inflight["i-b"] = late
+ r.c.mu.Unlock()
+ r.c.publish("i-b", late)
+ if !late.res.yes {
+ t.Fatalf("late negative answered %+v", late.res)
+ }
+ r.at = t0.Add(23*time.Hour + 30*time.Minute)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); !ok || err != nil || len(r.f.regions) != 1 {
+ t.Fatalf("after late negative: %v, %v, %d describes", ok, err, len(r.f.regions))
+ }
+}
+
+func TestConfirmConcurrentFirstCallsBuildOneClient(t *testing.T) {
+ const n = 6
+ f := &fakeEC2{}
+ r := newConfirmRig(f)
+ var built atomic.Int32
+ r.c.API = func(context.Context, string) (EC2, error) {
+ built.Add(1)
+ time.Sleep(20 * time.Millisecond) // long enough for every caller to arrive
+ return &safeEC2{out: describe("111122223333", "i-x", types.InstanceStateNameRunning)}, nil
+ }
+ var wg sync.WaitGroup
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if _, err := r.c.Terminated(context.Background(), "i-"+string(rune('b'+i))); err != nil {
+ t.Error(err)
+ }
+ }()
+ }
+ wg.Wait()
+ if built.Load() != 1 {
+ t.Fatalf("API called %d times", built.Load())
+ }
+}
+
+// safeEC2 answers any instance id with out's state, safe for concurrent use.
+type safeEC2 struct{ out *ec2.DescribeInstancesOutput }
+
+func (s *safeEC2) DescribeInstances(_ context.Context, in *ec2.DescribeInstancesInput, _ ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) {
+ return describe(aws.ToString(s.out.Reservations[0].OwnerId), in.InstanceIds[0], s.out.Reservations[0].Instances[0].State.Name), nil
+}
+
+func TestConfirmClientConstructionFailureIsRetried(t *testing.T) {
+ r := newConfirmRig(&fakeEC2{})
+ boom := errors.New("no credentials")
+ calls := 0
+ r.c.API = func(context.Context, string) (EC2, error) {
+ calls++
+ if calls == 1 {
+ return nil, boom
+ }
+ return &safeEC2{out: describe("111122223333", "i-x", types.InstanceStateNameTerminated)}, nil
+ }
+ t0 := r.at
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); ok || !errors.Is(err, boom) {
+ t.Fatalf("first: %v, %v", ok, err)
+ }
+ // A different instance is not held back by the failure.
+ if ok, err := r.c.Terminated(context.Background(), "i-c"); !ok || err != nil {
+ t.Fatalf("i-c: %v, %v", ok, err)
+ }
+ r.at = t0.Add(11 * time.Second)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); !ok || err != nil {
+ t.Fatalf("retry: %v, %v", ok, err)
+ }
+ if calls != 2 {
+ t.Fatalf("API called %d times", calls)
+ }
+}