oficina / docs Public

Live push slice 1a: POSTs queued on an entry share its handle (#174 delta 1)

The finding-6 fix deleted a handle-less entry on release even while other
POSTs waited on its mutex, so each waiter replayed into an entry that was
no longer the cache's and discarded it, and each new POST started a
second entry that went stale. Fable measured 8 x 100 POSTs to one
document: 501 replays, 431 stale, 14.7 s. The entry now counts the POSTs
holding or waiting for it (refs, under the cache's mu: ++ in acquire, --
in release) and a handle-less entry leaves the map only when refs is 0
(dead, orphaned and closed entries still close at once). The count cap
counts only entries that keep a handle. warmCounts (replays, hits, stale,
reseeds) say what the cache did.

TestWarmHandleContentionDoesNotReplay: 8 x 100 POSTs to one document, no
drops: 4 replays, 0 stale, 3 re-seeds, 796 warm hits in ~2 s; without the
reference count 504 replays, 455 stale, and it fails.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev ca487aea7e41d5d24e36d480a01e5ebe461d2a6c parent d5c10e2
2 files changed, +94 −4
  • internal/docs/warm.go +37 −4
  • internal/docs/warm_test.go +57 −0
diff --git a/internal/docs/warm.go b/internal/docs/warm.go
index 7ac37f5..6635568 100644
--- a/internal/docs/warm.go
+++ b/internal/docs/warm.go
@@ -61,6 +61,7 @@ import (
"fmt"
"sort"
"sync"
+ "sync/atomic"
"time"
"github.com/carlosframework/docs/internal/core"
@@ -82,6 +83,11 @@ type warmEntry struct {
snap int64 // the newest snapshot's seq, as far as the handle knows
used time.Time
dead bool // dropped while held: the holder closes it on release
+ // refs counts the POSTs that hold or wait for this entry, under the
+ // cache's mu. A handle-less entry leaves the map only when nobody waits
+ // on it: deleting it under waiters made each of them replay and every
+ // new POST start a second entry (review #174, delta finding 1).
+ refs int
// pending: an update has been applied to h and not yet committed. Set
// before Apply and cleared only after the commit, so release closes the
// handle on every other way out, a panic included (review finding 2).
@@ -104,6 +110,15 @@ type warmCache struct {
// afterLookup is a test seam: it runs in acquire between finding the
// entry and locking it, the window review finding 3 is about.
afterLookup func(e *warmEntry)
+ // counts says what the cache did; tests and probes read it.
+ counts warmCounts
+}
+
+// warmCounts are cumulative: replays (a handle built by a replay), hits (an
+// update applied to a kept handle), stale (dropped by rule 3's MAX(seq)
+// check), reseeds (rule 4).
+type warmCounts struct {
+ replays, hits, stale, reseeds atomic.Int64
}
func newWarmCache() *warmCache {
@@ -124,6 +139,7 @@ func (c *warmCache) acquire(ctx context.Context, docID int64) *warmEntry {
c.entries[docID] = e
}
e.used = c.now()
+ e.refs++
hook := c.afterLookup
c.mu.Unlock()
if hook != nil {
@@ -152,13 +168,17 @@ func (c *warmCache) release(ctx context.Context, e *warmEntry) {
bytes = e.h.ResidentBytes()
}
c.mu.Lock()
+ e.refs--
mine := c.entries[e.docID] == e
- if e.dead || !mine || c.closed || bytes > c.maxBytes || e.h == nil {
+ if e.dead || !mine || c.closed || bytes > c.maxBytes {
e.close(ctx)
bytes = 0
if mine {
delete(c.entries, e.docID)
}
+ } else if e.h == nil && e.refs == 0 {
+ // Handle-less and nobody waiting: leave the map (finding 6).
+ delete(c.entries, e.docID)
}
e.bytes, e.kept = bytes, e.h != nil
e.used = c.now()
@@ -199,22 +219,28 @@ func (c *warmCache) sweepLocked(ctx context.Context, keep int64) {
}
// capLocked evicts least recently used entries until both caps hold.
+// Only entries that keep a handle count: one waiting for its first replay
+// holds nothing yet.
func (c *warmCache) capLocked(ctx context.Context) {
var total uint64
list := make([]*warmEntry, 0, len(c.entries))
for _, e := range c.entries {
- total += e.bytes
- list = append(list, e)
+ if e.kept {
+ total += e.bytes
+ list = append(list, e)
+ }
}
if total <= c.maxBytes && len(list) <= c.maxHandles {
return
}
sort.Slice(list, func(i, j int) bool { return list[i].used.Before(list[j].used) })
+ kept := len(list)
for _, e := range list {
- if total <= c.maxBytes && len(c.entries) <= c.maxHandles {
+ if total <= c.maxBytes && kept <= c.maxHandles {
return
}
total -= e.bytes
+ kept--
c.evictLocked(ctx, e)
}
}
@@ -285,6 +311,9 @@ func (s *Store) applyWarm(ctx context.Context, doc *Document, actor Actor, updat
return 0, err
}
e.h, e.seq, e.snap = h, replayedSeq, lastSnapshotSeq
+ s.warm.counts.replays.Add(1)
+ } else {
+ s.warm.counts.hits.Add(1)
}
// Rule 4, with D3's placement: the snapshot is the state before this
@@ -304,6 +333,7 @@ func (s *Store) applyWarm(ctx context.Context, doc *Document, actor Actor, updat
} else {
e.snap = e.seq
reseed = true
+ s.warm.counts.reseeds.Add(1)
}
}
@@ -336,6 +366,9 @@ func (s *Store) applyWarm(ctx context.Context, doc *Document, actor Actor, updat
return 0, err
}
e.pending = false
+ if before != e.seq {
+ s.warm.counts.stale.Add(1)
+ }
if before != e.seq || reseed {
e.close(ctx) // rule 3 (stale) or rule 4 (re-seed)
} else {
diff --git a/internal/docs/warm_test.go b/internal/docs/warm_test.go
index c28e181..47636ec 100644
--- a/internal/docs/warm_test.go
+++ b/internal/docs/warm_test.go
@@ -14,6 +14,7 @@ import (
"sort"
"strings"
"sync"
+ "sync/atomic"
"testing"
"time"
@@ -434,6 +435,62 @@ func TestWarmHandleCancelledMidApplyIsQuiet(t *testing.T) {
}
}
+// concurrentPOSTs runs goroutines × per POSTs, goroutine g posting to
+// docs[(g+i)%len(docs)], each a fresh paragraph from its own Yjs client.
+func (f *warmFixture) concurrentPOSTs(docs []*Document, goroutines, per int, next *atomic.Int64) {
+ f.t.Helper()
+ var wg sync.WaitGroup
+ errs := make(chan error, goroutines)
+ for g := 0; g < goroutines; g++ {
+ wg.Add(1)
+ go func(g int) {
+ defer wg.Done()
+ for i := 0; i < per; i++ {
+ d := docs[(g+i)%len(docs)]
+ k := next.Add(1)
+ u, err := f.app.core.InitialUpdate(f.ctx, d.GUID, uint64(300000+k), []core.InitialBlock{{Text: fmt.Sprintf("c%d", k)}})
+ if err == nil {
+ _, err = f.s.ApplyUpdate(f.ctx, d, f.actor, u)
+ }
+ if err != nil {
+ errs <- fmt.Errorf("goroutine %d POST %d: %w", g, i, err)
+ return
+ }
+ }
+ }(g)
+ }
+ wg.Wait()
+ close(errs)
+ for err := range errs {
+ f.t.Fatal(err)
+ }
+}
+
+// Review #174, delta finding 1: POSTs queued on one document's entry must
+// share its handle. Deleting a handle-less entry while others waited on it
+// made each waiter replay and each new POST start a second entry that went
+// stale: 501 replays and 431 stale drops for 8 × 100 POSTs, against a
+// handful with the reference count. No drops, no sweeps: only contention.
+func TestWarmHandleContentionDoesNotReplay(t *testing.T) {
+ f := newWarmFixture(t)
+ per := 100
+ if testing.Short() {
+ per = 40
+ }
+ var next atomic.Int64
+ f.concurrentPOSTs([]*Document{f.doc}, 8, per, &next)
+ c := &f.s.warm.counts
+ replays, stale, reseeds, hits := c.replays.Load(), c.stale.Load(), c.reseeds.Load(), c.hits.Load()
+ t.Logf("%d POSTs: %d replays, %d stale, %d re-seeds, %d warm hits", 8*per, replays, stale, reseeds, hits)
+ // One replay to start, one after each re-seed; a little slack.
+ if replays > reseeds+3 || stale > 2 {
+ t.Fatalf("contention replays: %d replays, %d stale for %d POSTs (%d re-seeds)", replays, stale, 8*per, reseeds)
+ }
+ if sortedWords(f.coldText()) != sortedWords(f.rowsText(-1)) {
+ t.Fatal("a cold replay differs from the log")
+ }
+}
+
// Rule 1 and the cache's locking, under -race in the gate: 8 goroutines ×
// 150 POSTs to two documents, with drops and sweeps (on a clock that moves
// past warmIdle) between them. Every POST succeeds, and at the end the log,