oficina / home Public

roster: lease answers contended reads from a published snapshot (#158)

Valid()/Remaining() used TryLock and reported an expired lease whenever
the cache lock was held, so team-mode streams closed and guarded writes
got spurious 503s. The cache now publishes an atomic snapshot on every
unlock and contended reads answer from it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from fix/roster-lease-remaining into main.
claude agent, operated by paul@keymail.dev 7e149ef7b08ec0f081d4add409673776a0e88a66 parent b4e00f1
2 files changed, +287 −58
  • roster/cache.go +107 −40
  • roster/lease_test.go +180 −18

CI passed — run details

CI log
amadan: .amadan/timeout: this job's budget is 20m0s (this runner allows up to 30m0s)
=== vet ===
CGO_ENABLED=0 go vet ./...
CGO_ENABLED=0 go vet -tags browser ./internal/home/
cd handoff && CGO_ENABLED=0 go vet ./...
cd roster && CGO_ENABLED=0 go vet ./...
cd dashboard && CGO_ENABLED=0 go vet ./...
cd connect && CGO_ENABLED=0 go vet ./...
cd teammode && CGO_ENABLED=0 go vet ./...
=== fmt ===
=== build ===
CGO_ENABLED=0 go build ./...
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build ./cmd/home ./cmd/oficina ./internal/operatorlaunch
cd handoff && CGO_ENABLED=0 go build ./...
cd roster && CGO_ENABLED=0 go build ./...
cd dashboard && CGO_ENABLED=0 go build ./...
cd connect && CGO_ENABLED=0 go build ./...
cd teammode && CGO_ENABLED=0 go build ./...
=== go-test ===
CGO_ENABLED=0 go test -count=1 ./...
?   	amadan.net/oficina/home/cmd/home	[no test files]
ok  	amadan.net/oficina/home/cmd/home-placeholder	0.807s
?   	amadan.net/oficina/home/cmd/oficina	[no test files]
ok  	amadan.net/oficina/home/internal/guardstest	0.187s
ok  	amadan.net/oficina/home/internal/home	56.802s
ok  	amadan.net/oficina/home/internal/home/directorydata	1.456s
ok  	amadan.net/oficina/home/internal/home/logtest	0.003s
ok  	amadan.net/oficina/home/internal/home/seal	0.005s
ok  	amadan.net/oficina/home/internal/home/sealtest	0.003s
ok  	amadan.net/oficina/home/internal/home/wisp	0.063s
ok  	amadan.net/oficina/home/internal/operator	6.505s
ok  	amadan.net/oficina/home/internal/operatorlaunch	4.143s
ok  	amadan.net/oficina/home/internal/provisioner	49.119s
cd handoff && CGO_ENABLED=0 go test -count=1 ./...
ok  	amadan.net/oficina/home/handoff	0.660s
ok  	amadan.net/oficina/home/handoff/seal	0.002s
cd roster && CGO_ENABLED=0 go test -count=1 ./...
ok  	amadan.net/oficina/home/roster	5.126s
cd dashboard && CGO_ENABLED=0 go test ./...
ok  	amadan.net/oficina/home/dashboard	(cached)
cd connect && CGO_ENABLED=0 go test -count=1 ./...
ok  	amadan.net/oficina/home/connect	1.397s
ok  	amadan.net/oficina/home/connect/linkstore	0.435s
cd teammode && CGO_ENABLED=0 go test -count=1 ./...
ok  	amadan.net/oficina/home/teammode	0.099s
?   	amadan.net/oficina/home/teammode/teammodetest	[no test files]
=== race ===
go test -race -count=1 ./internal/home/ ./internal/operator/ ./internal/operatorlaunch/ ./internal/home/directorydata/
ok  	amadan.net/oficina/home/internal/home	338.272s
ok  	amadan.net/oficina/home/internal/operator	82.853s
ok  	amadan.net/oficina/home/internal/operatorlaunch	22.391s
ok  	amadan.net/oficina/home/internal/home/directorydata	23.531s
ok  	amadan.net/oficina/home/internal/provisioner	399.556s
cd handoff && CGO_ENABLED=1 go test -race -count=1 ./...
ok  	amadan.net/oficina/home/handoff	12.882s
ok  	amadan.net/oficina/home/handoff/seal	1.014s
cd roster && CGO_ENABLED=1 go test -race -count=1 ./...
ok  	amadan.net/oficina/home/roster	7.000s
cd dashboard && CGO_ENABLED=1 go test -race -count=1 ./...
ok  	amadan.net/oficina/home/dashboard	1.064s
cd connect && CGO_ENABLED=1 go test -race -count=1 ./...
ok  	amadan.net/oficina/home/connect	6.246s
ok  	amadan.net/oficina/home/connect/linkstore	6.275s
cd teammode && CGO_ENABLED=1 go test -race -count=1 ./...
ok  	amadan.net/oficina/home/teammode	1.940s
?   	amadan.net/oficina/home/teammode/teammodetest	[no test files]
diff --git a/roster/cache.go b/roster/cache.go
index 2f52e9f..1ed632f 100644
--- a/roster/cache.go
+++ b/roster/cache.go
@@ -8,6 +8,7 @@ import (
"net/http"
"net/url"
"sync"
+ "sync/atomic"
"time"
"amadan.net/oficina/home/handoff"
@@ -27,6 +28,7 @@ const (
// Clock returns wall time and monotonic elapsed time from one observation. The
// elapsed value must never go backwards. Nil Config.Clock uses Go's monotonic clock.
+// Now may be called concurrently: a contended lease accessor reads it unlocked.
type Clock interface {
Now() (time.Time, time.Duration)
}
@@ -68,8 +70,16 @@ type Decision struct {
// Lease is an observation, not a stored authorization grant. Call Valid at the
// protected operation boundary; stream users must recheck and re-arm their timer
// from a new decision after renewal, or close when renewal cannot authorize it.
-// Both accessors refuse immediately on cache contention: a caller may hold the
+// Neither accessor ever waits for the cache's lock: a caller may hold the
// database writer that an in-flight durable publication needs to acquire.
+// When the lock is held, they answer from the state the cache last published
+// on releasing it (see view), checked against the clock read now — so a live
+// lease stays live while a concurrent Check holds the lock for a moment
+// (oficina/docs #175), and contention never extends a deadline or revives a
+// published removal or fence. An answer from the published state is one the
+// locked path would have given just before the holder's change. The clock
+// check is against the last published observation, not the holder's newer
+// one, so it differs from observe's in two bounded ways (see left).
//
// A lease names the subject and role it was decided for. A later successful
// publication does not end it while every publication since the lease has
@@ -89,47 +99,86 @@ type Lease struct {
role string
}
-// current reports whether the lease still holds against the cache state. The
-// caller holds c.mu and has called observe.
-func (l Lease) current(c *Cache, n time.Duration) bool {
- if !c.usable || n >= l.deadline || c.fences != l.fences || c.version < l.version {
+// current reports whether the lease still holds against the cache state v at
+// monotonic time n.
+func (l Lease) current(v view, n time.Duration) bool {
+ if !v.usable || n >= l.deadline || v.fences != l.fences || v.version < l.version {
return false
}
- if c.version == l.version {
+ if v.version == l.version {
return true
}
- role, ok := c.members[l.subject]
- return ok && role == l.role && c.since[l.subject] <= l.version
+ role, ok := v.members[l.subject]
+ return ok && role == l.role && v.since[l.subject] <= l.version
}
-func (l Lease) Valid() bool {
- if l.cache == nil {
- return false
- }
- c := l.cache
- if !c.mu.TryLock() {
- return false
- }
- defer c.mu.Unlock()
- _, n := c.observe()
- return l.current(c, n)
-}
-func (l Lease) Remaining() time.Duration {
+// left is the lease's remaining time, 0 once it no longer holds. It never
+// waits for c.mu: uncontended it observes under the lock (which may fence);
+// contended it answers from the last published view.
+func (l Lease) left() time.Duration {
if l.cache == nil {
return 0
}
c := l.cache
- if !c.mu.TryLock() {
- return 0
+ var v view
+ var n time.Duration
+ if c.mu.TryLock() {
+ _, n = c.observe()
+ v = c.state()
+ c.unlock()
+ } else {
+ p := c.published.Load()
+ if p == nil {
+ return 0
+ }
+ v = *p
+ // Read the clock after loading the view, so the view's observation
+ // precedes this one. The discrepancy is measured from the last
+ // PUBLISHED observation, which may be older than the one the holder
+ // just made, so over that longer span:
+ // - a wall-clock excursion that nets to zero (back past the
+ // tolerance, then forward) can go unseen here, deferring its
+ // fence by at most one lock hold: any fence observe makes is
+ // still made, by the holder or the next locked read, and
+ // published on release. Deferred, never skipped.
+ // - two backward slews, each under the tolerance, can sum past it
+ // and refuse this one read where observe would not: the safe
+ // direction, and nothing is fenced.
+ w, m := c.clock.Now()
+ if v.discrepant(w, m) {
+ return 0
+ }
+ n = m
}
- defer c.mu.Unlock()
- _, n := c.observe()
- if !l.current(c, n) {
+ if !l.current(v, n) {
return 0
}
return l.deadline - n
}
+func (l Lease) Valid() bool { return l.left() > 0 }
+func (l Lease) Remaining() time.Duration { return l.left() }
+
+// view is what a lease is checked against, published by every holder of
+// c.mu as it releases the lock. The maps are never mutated after
+// publication: publish replaces them.
+type view struct {
+ usable bool
+ version uint64
+ fences uint64
+ members map[string]string
+ since map[string]uint64
+ seen bool
+ wall time.Time
+ mono time.Duration
+}
+
+// discrepant is observe's clock fence, read-only: a contended reader cannot
+// fence the cache, so it refuses, and the next locked observe fences.
+func (v view) discrepant(w time.Time, m time.Duration) bool {
+ return v.seen && (m < v.mono || w.Round(0).Sub(v.wall.Round(0)).Nanoseconds()-(m-v.mono).Nanoseconds() < -ClockTolerance.Nanoseconds())
+}
+
type receipt struct {
Operation string `json:"operation"`
Digest string `json:"digest"`
@@ -153,7 +202,10 @@ type flight struct {
cancel context.CancelFunc
}
type Cache struct {
- mu sync.Mutex
+ mu sync.Mutex
+ // published is the view as of the last release of mu (unlock), read by
+ // a lease accessor that finds mu held.
+ published atomic.Pointer[view]
record VerifiedRecord
token string
client *http.Client
@@ -215,6 +267,7 @@ func New(ctx context.Context, cfg Config) (*Cache, error) {
return nil, e
}
c.evidence = ev
+ c.published.Store(&view{version: c.version})
return c, nil
}
func validEvidence(e evidence) bool {
@@ -298,7 +351,7 @@ func (c *Cache) save(ctx context.Context, e evidence) error {
// bindings. Durable failure changes neither the current floor nor usable lease.
func (c *Cache) UpdateRecord(ctx context.Context, r VerifiedRecord) error {
c.mu.Lock()
- defer c.mu.Unlock()
+ defer c.unlock()
if !r.valid || r.record.Bindings != c.record.record.Bindings || r.record.Sequence <= c.record.record.Sequence {
return ErrRefused
}
@@ -334,11 +387,25 @@ func (c *Cache) observe() (time.Time, time.Duration) {
return w, m
}
+// state is the lease-relevant cache state. The caller holds c.mu.
+func (c *Cache) state() view {
+ return view{usable: c.usable, version: c.version, fences: c.fences, members: c.members, since: c.since, seen: c.seen, wall: c.wall, mono: c.mono}
+}
+
+// unlock publishes the state for contended lease readers, then releases c.mu.
+// Every release of c.mu goes through it, so the published view is never
+// older than the last critical section to finish.
+func (c *Cache) unlock() {
+ v := c.state()
+ c.published.Store(&v)
+ c.mu.Unlock()
+}
+
func (c *Cache) Check(ctx context.Context, issuer, teamID, subject string) Decision {
c.mu.Lock()
b := c.record.record.Bindings
if issuer != b.Issuer || teamID != b.Team || !validMember(MemberEntry{subject, "member"}) {
- c.mu.Unlock()
+ c.unlock()
return Decision{State: Unknown}
}
_, now := c.observe()
@@ -350,10 +417,10 @@ func (c *Cache) Check(ctx context.Context, issuer, teamID, subject string) Decis
}
if usable {
d := c.decision(subject)
- c.mu.Unlock()
+ c.unlock()
return d
}
- c.mu.Unlock()
+ c.unlock()
if f != nil {
select {
case <-ctx.Done():
@@ -362,7 +429,7 @@ func (c *Cache) Check(ctx context.Context, issuer, teamID, subject string) Decis
}
}
c.mu.Lock()
- defer c.mu.Unlock()
+ defer c.unlock()
_, now = c.observe()
if !c.usable || now >= c.start+MaximumAge {
return Decision{State: Unknown}
@@ -383,7 +450,7 @@ func (c *Cache) Refresh(ctx context.Context) error {
c.mu.Lock()
_, now := c.observe()
f := c.startRefresh(now)
- c.mu.Unlock()
+ c.unlock()
if f == nil {
return ErrUnavailable
}
@@ -418,11 +485,11 @@ func (c *Cache) startRefresh(now time.Duration) *flight {
f.err = err
c.flight = nil
signalled := c.signalled
- c.mu.Unlock()
- // Signal only once the lock is free: a waiter that wakes on done and
- // asks Lease.Valid at once must not meet this goroutine's lock, which
- // TryLock reports as contention (Unknown). f.err is written before
- // the close, so the receive still sees it.
+ c.unlock()
+ // Signal only once the lock is free and the publication's view is
+ // published: a waiter that wakes on done and asks Lease.Valid at once
+ // must see the refresh it waited for, locked or contended (#104).
+ // f.err is written before the close, so the receive still sees it.
close(f.done)
if signalled != nil {
signalled()
@@ -478,7 +545,7 @@ func (c *Cache) fetch(ctx context.Context, r VerifiedRecord, version uint64, sta
c.evidence.Blocked = true
c.fence()
}
- c.mu.Unlock()
+ c.unlock()
return ErrRefused
}
if p.Type != "page" || *p.Index != index || p.Epoch < r.record.MinEpoch || (epoch != 0 && p.Epoch != epoch) {
@@ -505,7 +572,7 @@ func (c *Cache) fetch(ctx context.Context, r VerifiedRecord, version uint64, sta
}
func (c *Cache) publish(ctx context.Context, r VerifiedRecord, version uint64, start time.Duration, epoch int64, members []MemberEntry) error {
c.mu.Lock()
- defer c.mu.Unlock()
+ defer c.unlock()
_, now := c.observe()
if ctx.Err() != nil || c.version != version || c.record.digest != r.digest || now-start >= FetchTimeout || epoch < c.evidence.Epoch {
return ErrUnavailable
diff --git a/roster/lease_test.go b/roster/lease_test.go
index 5c1e1e0..e8d5e50 100644
--- a/roster/lease_test.go
+++ b/roster/lease_test.go
@@ -4,7 +4,9 @@ import (
"context"
"database/sql"
"net/http"
+ "os"
"path/filepath"
+ "strings"
"sync"
"testing"
"time"
@@ -107,8 +109,10 @@ func TestLeaseDoesNotWaitForSQLiteWriterPublication(t *testing.T) {
if timedOut {
t.Fatal("lease accessor blocked behind SQLite writer publication")
}
- if v || left != 0 {
- t.Fatal("contended lease granted standing")
+ // The publication has not finished, so the contended answer is the
+ // state before it: the lease, 30 s into its 60, is live with 30 s left.
+ if !v || left != 30*time.Second {
+ t.Fatalf("contended lease misread during publication: valid %v, remaining %v", v, left)
}
next := f.check(c, 1)
state(t, next, Member)
@@ -122,20 +126,18 @@ func TestLeaseDoesNotWaitForSQLiteWriterPublication(t *testing.T) {
}
}
-func TestLeaseContentionRefusesWithoutChangingAgeOrStanding(t *testing.T) {
- f := setup(t)
- c := f.cache()
- d := f.check(c, 1)
- f.clock.step(10 * time.Second)
- before := d.Lease.Remaining()
- c.mu.Lock()
+// contended asks Valid and Remaining from other goroutines while the caller
+// holds c.mu, as a concurrent Check or a publication does, and fails the test
+// if either waits for the lock.
+func contended(t *testing.T, c *Cache, l Lease) (bool, time.Duration) {
+ t.Helper()
valid := make(chan bool, 1)
left := make(chan time.Duration, 1)
- go func() { valid <- d.Lease.Valid() }()
- go func() { left <- d.Lease.Remaining() }()
- timedOut := false
+ go func() { valid <- l.Valid() }()
+ go func() { left <- l.Remaining() }()
var v bool
var n time.Duration
+ timedOut := false
select {
case v = <-valid:
case <-time.After(250 * time.Millisecond):
@@ -146,22 +148,182 @@ func TestLeaseContentionRefusesWithoutChangingAgeOrStanding(t *testing.T) {
case <-time.After(250 * time.Millisecond):
timedOut = true
}
- c.mu.Unlock()
if timedOut {
- t.Fatal("contended accessor waited")
+ c.mu.Unlock()
+ t.Fatal("contended accessor waited for the lock")
}
- if v || n != 0 {
- t.Fatal("contention granted standing")
+ return v, n
+}
+
+// A live lease is still live while another goroutine holds the cache's lock
+// (Docs #175: a concurrent Check's brief hold read as an expired lease, and
+// team-mode streams closed minutes before their deadline). The contended
+// answer is the cache's last published state, never a refusal for the hold.
+func TestLeaseContentionAnswersFromPublishedState(t *testing.T) {
+ f := setup(t)
+ c := f.cache()
+ d := f.check(c, 1)
+ f.clock.step(10 * time.Second)
+ before := d.Lease.Remaining()
+ if before != 50*time.Second {
+ t.Fatalf("remaining %v before contention", before)
+ }
+ c.mu.Lock()
+ v, n := contended(t, c, d.Lease)
+ c.mu.Unlock()
+ if !v || n != before {
+ t.Fatalf("contention refused a live lease: valid %v, remaining %v, want %v", v, n, before)
}
if !d.Lease.Valid() || d.Lease.Remaining() != before {
t.Fatal("contention changed the snapshot or deadline")
}
- f.clock.step(50 * time.Second)
- if d.Lease.Valid() || d.Lease.Remaining() != 0 {
+}
+
+// Contention never extends a lease: past its deadline the contended answer
+// refuses exactly as the locked one does.
+func TestLeaseContentionDoesNotExtendAge(t *testing.T) {
+ f := setup(t)
+ c := f.cache()
+ d := f.check(c, 1)
+ f.clock.step(MaximumAge)
+ c.mu.Lock()
+ v, n := contended(t, c, d.Lease)
+ c.mu.Unlock()
+ if v || n != 0 {
t.Fatal("contention extended age")
}
}
+// A removal that has been published ends the lease for a contended reader
+// too: the published state the reader sees is the one after the removal.
+func TestLeaseContentionSeesPublishedRemoval(t *testing.T) {
+ f := setup(t)
+ c := f.cache()
+ d := f.check(c, 1)
+ f.clock.step(30 * time.Second)
+ f.refreshTo(c, 2, []MemberEntry{{person(2), "member"}})
+ c.mu.Lock()
+ v, n := contended(t, c, d.Lease)
+ c.mu.Unlock()
+ if v || n != 0 {
+ t.Fatal("contended reader missed a published removal")
+ }
+}
+
+// A record update's fence is published when UpdateRecord returns: a reader
+// that then finds the lock held must not answer from the view before it.
+func TestLeaseContentionSeesRecordFence(t *testing.T) {
+ f := setup(t)
+ c := f.cache()
+ d := f.check(c, 1)
+ n := f.record
+ n.Sequence = 2
+ n.Operation = "op2"
+ if e := c.UpdateRecord(context.Background(), f.verify(n)); e != nil {
+ t.Fatal(e)
+ }
+ c.mu.Lock()
+ v, left := contended(t, c, d.Lease)
+ c.mu.Unlock()
+ if v || left != 0 {
+ t.Fatal("contended reader revived a lease the record fence ended")
+ }
+}
+
+// A clock fence made by a lease read is published too. The wall clock steps
+// back past the tolerance (the read fences), then forward again, so the
+// contended reader's own clock check against the last published observation
+// sees no net discrepancy and only the published fence can refuse it.
+func TestLeaseContentionSeesClockFenceFromALeaseRead(t *testing.T) {
+ f := setup(t)
+ c := f.cache()
+ d := f.check(c, 1)
+ f.clock.wallStep(-ClockTolerance - time.Nanosecond)
+ if d.Lease.Valid() {
+ t.Fatal("fence missed")
+ }
+ f.clock.wallStep(ClockTolerance + time.Nanosecond)
+ c.mu.Lock()
+ v, left := contended(t, c, d.Lease)
+ c.mu.Unlock()
+ if v || left != 0 {
+ t.Fatal("contended reader revived a lease a clock fence ended")
+ }
+}
+
+// Every release of c.mu must publish the view (unlock); a bare Unlock leaves
+// contended readers on a stale view. Two sites have tests above; this keeps
+// the rest honest: the one bare Unlock in cache.go is unlock's own.
+func TestEveryLockReleasePublishes(t *testing.T) {
+ raw, e := os.ReadFile("cache.go")
+ if e != nil {
+ t.Fatal(e)
+ }
+ src := string(raw)
+ if n := strings.Count(src, "c.mu.Unlock()"); n != 1 {
+ t.Fatalf("cache.go has %d bare c.mu.Unlock() calls; release the lock with c.unlock()", n)
+ }
+ start := strings.Index(src, "func (c *Cache) unlock() {")
+ at := strings.Index(src, "c.mu.Unlock()")
+ if start < 0 || at < start || strings.Contains(src[start:at], "\n}") {
+ t.Fatal("the bare c.mu.Unlock() is not inside unlock()")
+ }
+}
+
+// The production shape of #175: many requests' Checks take the lock briefly
+// while a stream's guard asks its lease. A live lease must never read as 0.
+func TestLeaseNeverReadsZeroUnderConcurrentChecks(t *testing.T) {
+ f := setup(t)
+ c := f.cache()
+ d := f.check(c, 1)
+ state(t, d, Member)
+ const checkers, readers, rounds = 4, 4, 2000
+ var wg sync.WaitGroup
+ stop := make(chan struct{})
+ for range checkers {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for {
+ select {
+ case <-stop:
+ return
+ default:
+ f.check(c, 1)
+ }
+ }
+ }()
+ }
+ var zeros, invalid sync.Map
+ var rwg sync.WaitGroup
+ for i := range readers {
+ rwg.Add(1)
+ go func() {
+ defer rwg.Done()
+ z, bad := 0, 0
+ for range rounds {
+ if d.Lease.Remaining() <= 0 {
+ z++
+ }
+ if !d.Lease.Valid() {
+ bad++
+ }
+ }
+ zeros.Store(i, z)
+ invalid.Store(i, bad)
+ }()
+ }
+ rwg.Wait()
+ close(stop)
+ wg.Wait()
+ z, bad := 0, 0
+ zeros.Range(func(_, v any) bool { z += v.(int); return true })
+ invalid.Range(func(_, v any) bool { bad += v.(int); return true })
+ if z != 0 || bad != 0 {
+ t.Fatalf("live lease read as lapsed under concurrent Checks: Remaining 0 %d/%d, Valid false %d/%d", z, readers*rounds, bad, readers*rounds)
+ }
+}
+
func TestLeaseContentionDoesNotSkipLaterClockFence(t *testing.T) {
f := setup(t)
c := f.cache()