oficina / home Public

roster: signal a finished refresh after releasing the cache lock closed

On branch roster-flight-unlock

One-line fix in roster/cache.go (startRefresh's flight goroutine): release c.mu before close(f.done), not after.

Why. The flight closed f.done while still holding the cache lock. A waiter woken by that close (Refresh, or a Check waiting on the flight) that immediately asks Lease.Valid()/Remaining() can meet the lock. Both use TryLock and read contention as "not valid", so a lease the roster still confirms is reported invalid. In apps this is a rare spurious retryable 503; in tests it is TestLeaseSurvivesAnotherMembersChange failing once under -race on hub CI (team-keygen @ e1b01e4, which does not touch roster; main passed the same code).

Evidence. Diagnosis is from reading the code. I could NOT reproduce it locally: 800 runs (-race -count=400 -cpu 4,8, six CPU burners) all passed, probably because the runtime normally lets the closer reach Unlock before the woken waiter runs. A regression test that only checks TryLock after Refresh also passed on the old code, so I did not commit it: a test that cannot fail on the bug proves nothing. f.err is written before the close, so the receive still observes it (the channel close gives happens-before).

Ask. Fable review: is the diagnosis right, is there another way that test can see an invalid lease, and is there a deterministic test worth having (e.g. a seam)? This blocks team-keygen (#102), which is approved but red on this flake.

Reviewer: Claude Fable 5.1 (claude-fable-5-1) — review @ 12b19ea

APPROVED. Review only: nothing edited, committed, merged or deployed; everything below ran in a scratch worktree (/tmp/fable-roster-unlock2, removed). The branch is exactly origin/main d36a413 plus one commit touching only roster/cache.go; gofmt and go vet clean; cd roster && CGO_ENABLED=1 go test -race -count=1 ./... green (8.7 s), which is how the Makefile's test-race runs this package.

1. Diagnosis

Right, and I made it causal rather than inferred. Mutant A: old order with a 2 ms sleep between close(f.done) and Unlock. All three runs fail with exactly the CI line, lease_test.go:306: another member's change ended this lease, and TestLeaseSurvivesUnchangedPublicationOnItsOwnDeadline fails the same way at :232. The window is real and the message matches; the only thing CI left open was whether the scheduler ever lands in it, and under -race on a loaded runner it evidently did once.

Other paths to Valid()==false in that test, walked through:

  • fences: the fake clock steps wall and mono together (one step of 30 s), so observe() never fences; the generation fence in fetch is unreachable because the fixture signs with f.record.Generation; no UpdateRecord. c.fences stays 0 == l.fences.
  • deadline: lease deadline = start(0) + 60 s; Valid runs at n = 30 s.
  • since/version: the lease is at version 2 (after the first publish). The second publish keeps since[p1] = 2 because old role == new role ("owner") and bumps version to 3; current() takes the version > l.version branch and finds owner, owner, 2 <= 2. Correct.
  • initial Check flight: Check's post-wake path uses Lock, not TryLock, so it is immune to this window; it returns Member with the lease above.
  • startRefresh returning an existing flight: by the time refreshTo runs, c.flight was set nil under the lock before the first close, so a fresh flight starts. RetryAfter: attempted=true, lastAttempt=0, now=30 s >= 5 s, no backoff. Blocked is false.
  • Refresh returning ErrUnavailable would Fatal inside refreshTo at lease_test.go:217 with a different message, so that is excluded.

The one residual path with the same message: the first Check returning Decision{State: Unknown} (Lease.cache nil, so Valid is false) if the first flight's real-time 5 s FetchTimeout (context.WithTimeout, not the fake clock) expired, i.e. the goroutine stalled 5 s between startRefresh and publish's ctx.Err() check. The test never asserts state(t, d, Member) after the first check, so it cannot tell the two apart. Far less plausible than the lock window (one in-memory round trip), but it survives this fix; see N1.

2. Fix

Correct and complete.

  • Happens-before for f.err: write under c.mu -> Unlock -> close(f.done) -> receive in Refresh/Check -> read. The close still orders the write before every receive. Mutant C (f.err written after the close) draws 17 race reports and 8 failing tests, so the suite guards this edge.
  • Mutant B: new order with 2 ms sleeps both before and after the close: full roster suite green x3. Nothing else in the flight needs the lock (defer cancel() does not).
  • The new window where c.flight == nil but done is not yet closed is harmless: a Refresh/Check in it starts a second flight (or is held by RetryAfter), and the old waiters are woken a few instructions later with the first flight's err; fence() finds no flight to cancel because the first has already published. No invariant in Check, Refresh, UpdateRecord or publish depends on "flight == nil implies done closed".
  • Other instances: TryLock exists only in Lease.Valid/Remaining; the only channel close in non-test code is this one (grep over the module; the other close() hits are file/db methods in internal/). teammode/access.go (State, Remaining, Guard) and runtime.go (AdmitUnlinked) call Valid/Remaining after a Check that has already unlocked, so they only meet contention from an unrelated concurrent cache user, the designed case. connect/ has no roster or teammode lock use. No other close-under-lock or TryLock-after-wake pattern.

3. TryLock -> Unknown

Keep it. The reason in the Lease doc comment is a real deadlock: publish holds c.mu across durable.Save, and Access.State/Guard run inside the app's SQLite writer transaction that Save needs. A blocking Valid there would wedge the process. After this fix the remaining contention is only genuine concurrent cache use (another request's Check, a publish, UpdateRecord), each sub-millisecond except the Save, once per 30 s, and teammode already renders it as a retryable 503 or a "partial" list, never a 404. That is the contract #98 approved and it still holds. If the 503 ever shows up in the logs, the cheap hardening is a bounded spin (two or three runtime.Gosched() retries of TryLock) before returning false: it cannot deadlock because it still gives up. Not needed now.

4. Deterministic test

Yes, and it is cheap. Add signalled func() to Cache (nil in production), captured under the lock in the flight goroutine and called right after the close:

c.mu.Lock()
f.err = err
c.flight = nil
hook := c.signalled
c.mu.Unlock()
close(f.done)
if hook != nil {
	hook()
}

Test: take a lease, step 30 s, set c.signalled (under c.mu) to block on a gate, run Refresh in a goroutine and wait for it to return, call d.Lease.Valid(), open the gate, fail if Valid was false. The closer is parked at the exact point where the signal has happened, so whether it still holds the lock there is the only thing measured. I ran it in the scratch worktree: 30/30 pass on 12b19ea, 5/5 fail on the old order with "lease read as contended while the refresh was signalling", no race reports. Capturing the hook under the lock matters: reading the field after Unlock races with the test's write. It pins the invariant "the flight holds no lock when it signals", which is exactly what a future tidy-up would undo. Worth a follow-up commit on this branch; not blocking.

Notes (non-blocking)

  • N1 roster/lease_test.go:302: add state(t, d, Member) after the first check in TestLeaseSurvivesAnotherMembersChange (the sibling at :221 already has it) so a recurrence names the FetchTimeout path instead of masquerading as this one.
  • N2 Tests that expect Valid()==false (TestLeaseEndsOnRoleChange, ...RemovalAndReAdd...) passed under Mutant A: contention is indistinguishable from the real reason there. Fine; the seam test is the positive control.

Unblocks #102.

Merged as ddde992 (squash) after Fable's APPROVED verdict; CI green at 7db3832, which adds Fable's deterministic seam test and N1. Not deployed (roster is a library the apps build against; it ships with their next build).