oficina / docs Public

Live push 1b: team streams survive a contended lease and never open without one (#175 finding 4, Docs side)

roster.Lease.Remaining and Valid use TryLock and answer "expired" when
another goroutine holds the roster cache's mutex (every request's admission
takes it), and teammode.Access latches Unknown the first time it sees that.
Docs' stream guard kept the opening request's Access and asked it at every
delivery, so one lost TryLock ended the stream for good (measured: 8 of 10
of today's team streams ended during 300 concurrent POSTs). And at open, a
lost TryLock left the stream with no lease deadline at all.
- Each delivery asks the roster for a fresh Access (teammode's own rule: "a
  stream asks for a new one before each delivery"); a zero lease or Unknown
  standing is asked again up to four times, 2 ms apart, before it is
  believed. A stream opened on a lease continues only while the fresh
  standing is a Member in the role it opened with (a role change still ends
  it, as TestTeamStreamPublicationKeepsAListedLeaseAndClosesAChangedOne
  holds), never past its original deadline; read permission is checked
  under the fresh standing.
- At open, a Member's zero lease is asked again; a Member whose lease stays
  unreadable gets 503 (retried by the client), never a stream without a
  deadline.
The roster fix itself (an RLock or an atomic snapshot) is Home's, in
progress elsewhere.

Tests: TestTeamStreamSurvivesAContendedLease (one lease read answering 0
mid-stream: the next frame still arrives; with one try only, the stream
ends); TestTeamStreamNeverOpensWithoutALease (a lease that stays 0: 503,
200 without the fix; one lost read at open: the stream opens on a lease
and says bye lease). The test seam is teamRuntime.leaseRemaining.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 1e25812010095eb7579e0a4c92c80e6f9cfa0285 parent abe631d
5 files changed, +187 −14
  • internal/docs/errors_test.go +1 −1
  • internal/docs/push_test.go +83 −0
  • internal/docs/stream.go +18 −1
  • internal/docs/team_config.go +4 −0
  • internal/docs/team_stream.go +81 −12
diff --git a/internal/docs/errors_test.go b/internal/docs/errors_test.go
index 6ea7318..4bf35fa 100644
--- a/internal/docs/errors_test.go
+++ b/internal/docs/errors_test.go
@@ -257,7 +257,7 @@ func TestEveryPlainTextErrorIsClassified(t *testing.T) {
"native.go:nativeJSON": {1, "native API JSON"},
"native.go:handlers.nativeList": {2, "native API JSON"},
"search.go:handlers.searchJSON": {3, "jump-to palette JSON"},
- "stream.go:handlers.stream": {8, "live update stream (and its 400 for a bad push cursor)"},
+ "stream.go:handlers.stream": {9, "live update stream (its 400 for a bad push cursor, its 503 for a team lease it cannot read)"},
"team_access.go:teamRuntime.admission": {1, "shared guard, identity missing: a wiring failure, not a page state"},
"team_emission.go:writeGuardedBody": {1, "response already guarded"},
}
diff --git a/internal/docs/push_test.go b/internal/docs/push_test.go
index d947e4f..14a9b8d 100644
--- a/internal/docs/push_test.go
+++ b/internal/docs/push_test.go
@@ -19,6 +19,7 @@ import (
"strconv"
"strings"
"sync"
+ "sync/atomic"
"testing"
"time"
@@ -1222,3 +1223,85 @@ func TestLogEpochSurvivesAStartBetweenAnotherStartsTwoWrites(t *testing.T) {
t.Fatal("a start between another start's database write and its file write rotated the epoch")
}
}
+
+// teamPushFixture is a linked team member (alice) on a team instance with
+// push on: a fixture for the team-mode stream tests.
+func teamPushFixture(t *testing.T) (*pushFixture, *teamRouterFixture) {
+ t.Helper()
+ tf := newTeamRouterFixtureWith(t, false, false)
+ tf.app.handlers.livePush = true
+ tf.app.store.recordOrigin = tf.app.handlers.pushRegistry.record
+ b := tf.browser()
+ b.localSignin(t, "alice@example.com")
+ b.linkProof(t, teamSubject('a'), "alice@example.com")
+ routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL("/"))
+ srv := httptest.NewServer(tf.app.Handler())
+ t.Cleanup(srv.Close)
+ f := &pushFixture{t: t, app: tf.app, srv: srv, doc: tf.own, ctx: context.Background(), host: strings.TrimPrefix(bridgeOrigin, "https://")}
+ for _, c := range b.cookies {
+ f.cookies = append(f.cookies, c)
+ }
+ return f, tf
+}
+
+// contendedLease makes the next n lease reads answer 0, as a roster whose
+// TryLock loses does (#175 finding 4).
+func contendedLease(f *pushFixture, n *atomic.Int32) {
+ f.app.store.team.leaseRemaining = func(a *requestAccess) time.Duration {
+ if n.Add(-1) >= 0 {
+ return 0
+ }
+ return a.Remaining()
+ }
+}
+
+// #175 finding 4: one lease read lost to contention mid-stream does not end
+// the stream; each delivery asks afresh.
+func TestTeamStreamSurvivesAContendedLease(t *testing.T) {
+ f, _ := teamPushFixture(t)
+ var lost atomic.Int32
+ contendedLease(f, &lost)
+ s := f.open(f.cookies, "?push=1&since="+strconv.FormatInt(f.currentSeq(), 10), nil)
+ s.hello(t)
+ lost.Store(1)
+ if code, _ := f.postHost(f.update(1, "after a lost TryLock"), ""); code != http.StatusNoContent {
+ t.Fatalf("POST %d", code)
+ }
+ if fr := s.next(t); fr.event != "push" {
+ t.Fatalf("%+v, want the push the contended stream still owes", fr)
+ }
+}
+
+// #175 finding 4: a Member's stream never opens without a lease deadline. A
+// lease that stays unreadable is refused (503); one read lost to contention
+// is asked again, and the stream opens on a lease (it says bye lease).
+func TestTeamStreamNeverOpensWithoutALease(t *testing.T) {
+ f, _ := teamPushFixture(t)
+ var lost atomic.Int32
+ contendedLease(f, &lost)
+ lost.Store(1 << 20)
+ req, _ := http.NewRequest(http.MethodGet, f.srv.URL+"/d/"+f.doc.Sqid+"/stream?push=1&since=0", nil)
+ req.Host = f.host
+ for _, c := range f.cookies {
+ req.AddCookie(c)
+ }
+ res, err := f.srv.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ if res.StatusCode != http.StatusServiceUnavailable {
+ t.Fatalf("a stream with no readable lease answered %d, want 503", res.StatusCode)
+ }
+ lost.Store(1)
+ f.app.handlers.pushLeaseLead = 24 * time.Hour // a lease timer exists: bye lease at once
+ s := f.open(f.cookies, "?push=1&since=0", nil)
+ s.hello(t)
+ fr := s.next(t)
+ for fr.event == "push" {
+ fr = s.next(t)
+ }
+ if fr.event != "bye" || fr.data != "lease" {
+ t.Fatalf("%+v, want bye lease: the stream opened without a lease deadline", fr)
+ }
+}
diff --git a/internal/docs/stream.go b/internal/docs/stream.go
index b8078e2..11fe4eb 100644
--- a/internal/docs/stream.go
+++ b/internal/docs/stream.go
@@ -8,6 +8,7 @@ import (
"strings"
"time"
+ "amadan.net/oficina/home/roster"
"amadan.net/rastrillo/rastrillo"
)
@@ -106,9 +107,25 @@ func (h *handlers) stream(w http.ResponseWriter, r *http.Request) {
http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable)
return
}
+ // A Member's stream rests on a lease and never opens without its
+ // deadline (#175 finding 4: a lost TryLock here used to open it
+ // with none). A zero lease or Unknown standing is asked again; a
+ // Member with no lease left after that is refused (503, retried).
+ lease := h.store.team.lease(a)
+ if lease <= 0 && a.Subject() != "" && a.state() != roster.NotMember {
+ fresh, left := h.store.team.freshLease(r.Context(), requestIdentity{Actor: a.actor, HomeSubject: a.Subject()})
+ if fresh != nil && fresh.state() == roster.Member {
+ if left <= 0 {
+ http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable)
+ return
+ }
+ a, lease = fresh, left
+ }
+ }
guard = &teamStreamGuard{store: h.store, access: a, request: r, docID: doc.ID}
- if lease := a.Remaining(); lease > 0 {
+ if lease > 0 {
guard.deadline = time.Now().Add(lease)
+ guard.role = a.Role()
}
if _, ok := guard.check(); !ok {
http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable)
diff --git a/internal/docs/team_config.go b/internal/docs/team_config.go
index d4caedd..c7f6ae3 100644
--- a/internal/docs/team_config.go
+++ b/internal/docs/team_config.go
@@ -6,6 +6,7 @@ import (
"database/sql"
"errors"
"net/http"
+ "time"
"amadan.net/oficina/home/handoff/seal"
"amadan.net/oficina/home/roster"
@@ -72,6 +73,9 @@ type teamRuntime struct {
principals *principalstore.Store
bindings roster.Bindings
db *sql.DB
+ // leaseRemaining stands in for Access.Remaining in tests (a contended
+ // roster answers 0; team_stream.go). nil in production.
+ leaseRemaining func(*requestAccess) time.Duration
}
func newTeamRuntime(ctx context.Context, settings *teamSettings, db *sql.DB, home *homeSettings) (*teamRuntime, error) {
diff --git a/internal/docs/team_stream.go b/internal/docs/team_stream.go
index d794351..d36ed12 100644
--- a/internal/docs/team_stream.go
+++ b/internal/docs/team_stream.go
@@ -5,6 +5,7 @@ import (
"net/http"
"time"
+ "amadan.net/oficina/home/roster"
"amadan.net/rastrillo/rastrillo/sessions"
)
@@ -16,28 +17,87 @@ type teamStreamGuard struct {
// deadline is the Member lease's, fixed when the stream opened; zero
// for a stream that rests on no lease (a guest's, or Unknown's, grant).
deadline time.Time
+ // role is the roster role the stream opened with. A fresh standing
+ // continues the stream only with the same role: a publication that
+ // changes it ends the stream, and the reconnect is decided afresh.
+ role string
}
-// remaining is how long the stream may run before it must re-decide. A
-// leased stream ends with its lease (Access.Remaining is 0 once the lease
-// has lapsed or the standing has gone Unknown), and never past the deadline
-// it opened with.
+// remaining is how long the stream may run before it must re-decide: the
+// opening lease's, never past the deadline it opened with. Used at open;
+// each delivery asks afresh (check).
func (g *teamStreamGuard) remaining() time.Duration {
if g.deadline.IsZero() {
return defaultStreamWriteDeadline
}
- return min(g.access.Remaining(), time.Until(g.deadline))
+ return min(g.store.team.lease(g.access), time.Until(g.deadline))
}
-// A stream never renews its lease. Reconnection obtains fresh admission, so a
-// blocked cache publisher cannot hold an expired stream open during refresh.
+// Lease contention (#175 finding 4). roster.Lease.Remaining and Valid use
+// TryLock and answer "expired" when another goroutine holds the roster
+// cache's mutex, which every request's admission takes; and
+// teammode.Access latches Unknown the first time it sees that. A stream
+// that kept its opening Access therefore died for good at the first lost
+// TryLock. teammode's own rule is that a stream asks for a new Access
+// before each delivery, so check does, and a zero lease or Unknown standing
+// is asked again a few times before it is believed: contention passes, an
+// expired lease does not.
+const (
+ leaseTries = 4
+ leaseRetryWait = 2 * time.Millisecond
+)
+
+// lease is a.Remaining(), or the tests' stand-in for a contended roster.
+func (t *teamRuntime) lease(a *requestAccess) time.Duration {
+ if t.leaseRemaining != nil {
+ return t.leaseRemaining(a)
+ }
+ return a.Remaining()
+}
+
+// freshLease asks the roster for id's standing now, again while it reads as
+// a Member with no lease left or as Unknown. It returns the last Access and
+// its lease (0 for a standing that rests on none).
+func (t *teamRuntime) freshLease(ctx context.Context, id requestIdentity) (*requestAccess, time.Duration) {
+ var a *requestAccess
+ for try := 0; try < leaseTries; try++ {
+ if try > 0 {
+ select {
+ case <-ctx.Done():
+ return a, 0
+ case <-time.After(leaseRetryWait):
+ }
+ }
+ a = t.resolveAccess(ctx, id)
+ switch a.state() {
+ case roster.Member:
+ if left := t.lease(a); left > 0 {
+ return a, left
+ }
+ case roster.NotMember:
+ return a, 0
+ }
+ }
+ return a, 0
+}
+
+// check re-decides the stream before a delivery: the session is still the
+// one it opened with, the person still the same, a fresh Access for them
+// (with its lease, for a stream that opened on one), and read permission
+// under that fresh standing. A stream never outlives the deadline it
+// opened with: reconnection obtains fresh admission.
func (g *teamStreamGuard) check() (time.Duration, bool) {
t := g.store.team
- remaining := g.remaining()
- if t == nil || t.home == nil || t.readSession == nil || remaining <= 0 {
+ if t == nil || t.home == nil || t.readSession == nil {
+ return 0, false
+ }
+ limit := defaultStreamWriteDeadline
+ if !g.deadline.IsZero() {
+ limit = min(limit, time.Until(g.deadline))
+ }
+ if limit <= 0 {
return 0, false
}
- limit := min(remaining, defaultStreamWriteDeadline)
ctx, cancel := context.WithTimeout(g.request.Context(), limit)
defer cancel()
if _, present, ok := homeCookie(g.request, t.home.sessionCookie); !ok || !present {
@@ -52,10 +112,19 @@ func (g *teamStreamGuard) check() (time.Duration, bool) {
if e != nil || !sameActor(id.Actor, g.access.actor) || id.HomeSubject != g.access.Subject() {
return 0, false
}
- if e = g.store.checkPermission(ctx, g.store.db.WithContext(ctx), id.Actor, g.docID, permissionRead); e != nil {
+ fresh, left := t.freshLease(ctx, id)
+ remaining := defaultStreamWriteDeadline
+ if !g.deadline.IsZero() {
+ // Opened on a Member lease: it must still hold one, in the role it
+ // opened with.
+ if fresh.state() != roster.Member || left <= 0 || fresh.Role() != g.role {
+ return 0, false
+ }
+ remaining = min(left, time.Until(g.deadline))
+ }
+ if e = g.store.checkPermission(withAccess(ctx, fresh), g.store.db.WithContext(ctx), id.Actor, g.docID, permissionRead); e != nil {
return 0, false
}
- remaining = g.remaining()
if ctx.Err() != nil || remaining <= 0 {
return 0, false
}