oficina / docs Public

Live push slice 1a: warm handles behind DOCS_WARM_HANDLE (default off)

Spec 2026-11-26-live-push-design.md §3.5, rules 1-8: Store.ApplyUpdate
keeps the replayed document handle between update POSTs instead of
replaying the whole document for every one (internal/docs/warm.go).
- ApplyUpdate splits into applyCold (unchanged) and commitUpdate (the one
  transaction, returning MAX(seq) before the insert); applyWarm in front
  when the switch is on.
- A clean core rejection keeps the handle; a full log, trap or recovered
  instance replays cold inside the same POST. Any failure after Apply
  drops the handle; its seq advances only after commit; a MAX(seq)
  mismatch (another process, the agent path) drops it.
- Re-seeded at the snapshot cadence: snapshot at the handle's seq, Apply,
  commit, drop, so a handle never nears core.MaxRetainedUpdates.
- LRU by count (64) and ResidentBytes (128 MB); one over-cap handle is not
  kept; idle 60 s, swept by POSTs and by every stream heartbeat; dropped
  on grants, revoke, visibility, delete, drain and close.
- The agent paths' transaction-bound Store copies (boundTo) never use warm
  handles: their commit is a savepoint the caller can still roll back.
- core.Handle gains RetainedUpdates and ResidentBytes.
- $DOCS_WARM_HANDLE on/off, unset off, anything else refuses to start.
Tests: >4,096 POSTs to one warm document, re-seed order, writer revoked
between Apply and commit, cold fallback, rejection, a property test with
failed and cancelled commits, injected traps, drops and a second store on
the same database, caps, access drops, heartbeat sweep, the switch, and a
relative timing gate (warm faster than replay on ~20 pages, same process,
best of three: 818 against 6,115 µs median). Each new test was seen to
fail by breaking its rule. go test ./... and -race on internal/docs pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 05844cc8e812073e79644ef6ddb76ae7bf67b242 parent 0255fca
12 files changed, +1,031 −14
  • cmd/docs/main.go +8 −0
  • internal/core/core.go +22 −0
  • internal/docs/agent_store.go +1 −2
  • internal/docs/agent_update.go +2 −4
  • internal/docs/app.go +17 −1
  • internal/docs/delete.go +1 −0
  • internal/docs/store.go +43 −7
  • internal/docs/stream.go +3 −0
  • internal/docs/suite_feed.go +1 −0
  • internal/docs/team_access.go +3 −0
  • internal/docs/warm.go +333 −0
  • internal/docs/warm_test.go +597 −0
diff --git a/cmd/docs/main.go b/cmd/docs/main.go
index 770fc92..bd18046 100644
--- a/cmd/docs/main.go
+++ b/cmd/docs/main.go
@@ -258,6 +258,13 @@ func main() {
// which is what an unset allowlist reaching a public instance
// would otherwise silently mean.
allowedAddresses := os.Getenv("DOCS_ALLOWED_ADDRESSES")
+ // $DOCS_WARM_HANDLE: keep a replayed handle per document between update
+ // POSTs (the live-push spec's §3.5). on/off; unset is off.
+ warmHandle, err := docs.ParseWarmHandle(os.Getenv("DOCS_WARM_HANDLE"))
+ if err != nil {
+ logger.Error("docs: refusing to start", "err", err)
+ os.Exit(1)
+ }
// $DOCS_SAMPLE_DOCUMENTS opts a deployed instance into
// docs.Config.SampleDocuments — see its own doc comment for the
@@ -311,6 +318,7 @@ func main() {
Mailer: mailer,
AllowedAddresses: allowedAddresses,
SampleDocuments: sampleDocuments,
+ WarmHandle: warmHandle,
Logger: logger,
// The hub directory the app switcher's "All apps" goes to. The
// same variable Home itself reads (home origins.go).
diff --git a/internal/core/core.go b/internal/core/core.go
index 43d1bc8..22bb2c4 100644
--- a/internal/core/core.go
+++ b/internal/core/core.go
@@ -575,6 +575,28 @@ func (h *Handle) Apply(ctx context.Context, update []byte) error {
return &RejectedError{err}
}
+// RetainedUpdates is how many updates this handle has applied and keeps
+// for a rebuild: Apply refuses with ErrUpdateLogFull at MaxRetainedUpdates.
+// A caller that keeps a handle across many updates (Docs' warm handles)
+// watches it.
+func (h *Handle) RetainedUpdates() int { return len(h.applied) }
+
+// ResidentBytes estimates what this handle holds in memory: its module
+// instance's linear memory, which grows and never shrinks, plus the
+// retained updates. A caller that keeps handles bounds them by this.
+func (h *Handle) ResidentBytes() uint64 {
+ var n uint64
+ if h.mod != nil {
+ if m := h.mod.Memory(); m != nil {
+ n = uint64(m.Size())
+ }
+ }
+ for _, u := range h.applied {
+ n += uint64(len(u))
+ }
+ return n
+}
+
// Text returns the document's current text content. If the read itself
// traps or times out, the instance is discarded and rebuilt exactly as in
// Apply, and the read is retried once against the freshly rebuilt
diff --git a/internal/docs/agent_store.go b/internal/docs/agent_store.go
index ddcbbeb..d3759e9 100644
--- a/internal/docs/agent_store.go
+++ b/internal/docs/agent_store.go
@@ -322,8 +322,7 @@ func (a *documentAgent) create(ctx context.Context, p access.Principal, id reque
if !errors.Is(e, gorm.ErrRecordNotFound) {
return e
}
- store := *a.store
- store.db = tx
+ store := a.store.boundTo(tx)
created, e := store.CreateDraft(ctx, id.Actor.PersonID, input.Title, "")
if e != nil {
return e
diff --git a/internal/docs/agent_update.go b/internal/docs/agent_update.go
index 9470c7a..c5e534a 100644
--- a/internal/docs/agent_update.go
+++ b/internal/docs/agent_update.go
@@ -105,8 +105,7 @@ func (a *documentAgent) checkEditor(ctx context.Context, tx *gorm.DB, p access.P
return errIdentityRefused
}
if a.store.team == nil && !a.list.configured(actorAddress(id.Actor)) {
- store := *a.store
- store.db = tx
+ store := a.store.boundTo(tx)
allowed, err := store.HasGrant(ctx, actorAddress(id.Actor))
if err != nil {
return err
@@ -168,8 +167,7 @@ func (a *documentAgent) update(ctx context.Context, p access.Principal, id reque
if !errors.Is(e, gorm.ErrRecordNotFound) {
return e
}
- store := *a.store
- store.db = tx
+ store := a.store.boundTo(tx)
seq, e := store.currentSeq(ctx, doc.ID)
if e != nil {
return e
diff --git a/internal/docs/app.go b/internal/docs/app.go
index 7f544a7..ed6d08a 100644
--- a/internal/docs/app.go
+++ b/internal/docs/app.go
@@ -46,6 +46,12 @@ import (
// Config configures New.
type Config struct {
+ // WarmHandle keeps a replayed document handle between update POSTs
+ // ($DOCS_WARM_HANDLE, warm.go; the live-push spec's §3.5 and §8). Off,
+ // every POST replays the document, as it always has. Off by default
+ // until slice 1a is proven on production, then on.
+ WarmHandle bool
+
AgentIssuer string
AgentTeam string
Home *HomeConfig
@@ -318,7 +324,11 @@ type App struct {
// progress, cancels none, and so otherwise waits out its whole deadline on
// any editor that has a document open (hub.drain). Safe to call more
// than once.
-func (a *App) Drain() { a.handlers.hub.drain() }
+func (a *App) Drain() {
+ a.handlers.hub.drain()
+ // Every warm handle goes, and no new one is kept (warm.go, rule 6).
+ a.handlers.store.warm.close(context.Background())
+}
// BootSchema is everything New applies at boot, in apply order.
// migrate.Merge's argument order is apply order (rastrillo SKILL.md
@@ -475,6 +485,9 @@ func New(cfg Config) (*App, error) {
return nil, fmt.Errorf("docs: start core runtime: %w", err)
}
store := NewStore(d.G, rt, parseSampleDocuments(cfg.SampleDocuments), logger)
+ if cfg.WarmHandle {
+ store.warm = newWarmCache()
+ }
if state != nil {
store.content = cipher
}
@@ -874,6 +887,9 @@ func (a *App) Close() error {
if a.signinMail != nil {
a.signinMail.close()
}
+ if a.handlers != nil && a.handlers.store != nil {
+ a.handlers.store.warm.close(context.Background())
+ }
if a.core != nil {
if err := a.core.Close(context.Background()); err != nil {
errs = append(errs, err)
diff --git a/internal/docs/delete.go b/internal/docs/delete.go
index 38496fd..7f746c1 100644
--- a/internal/docs/delete.go
+++ b/internal/docs/delete.go
@@ -114,6 +114,7 @@ func (s *Store) Delete(ctx context.Context, owner int64, sqid string) error {
// standing over the row, deleted or not: the same rule
// (permissionScope), without the liveness the write is there to end.
func (s *Store) ownerDeletion(ctx context.Context, owner, docID int64) error {
+ defer s.warm.drop(ctx, docID) // warm.go, rule 6
actor := s.ownerActor(ctx, owner)
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
authorize := func(roster.State) error {
diff --git a/internal/docs/store.go b/internal/docs/store.go
index eca2322..cb38f7e 100644
--- a/internal/docs/store.go
+++ b/internal/docs/store.go
@@ -22,10 +22,21 @@ import (
// the update log, and the document's actual text read back through
// the real CRDT core rather than any column here — see Text.
type Store struct {
- team *teamRuntime
- db *gorm.DB
- core *core.Runtime
- content *contentCipher
+ // warm keeps a replayed handle per document between update POSTs
+ // (warm.go); nil means every POST replays, as it always did.
+ warm *warmCache
+ // warmBeforeCommit is a test seam: it runs inside commitUpdate's
+ // transaction, after the row is written and before the final
+ // permission check, so a test can revoke a writer or fail the
+ // transaction between a warm Apply and its commit. nil in production.
+ warmBeforeCommit func(ctx context.Context, tx *gorm.DB, doc *Document) error
+ // warmApplyHook is a test seam: an error it returns stands in for
+ // Handle.Apply's (warm.go, rule 2). nil in production.
+ warmApplyHook func(h *core.Handle) error
+ team *teamRuntime
+ db *gorm.DB
+ core *core.Runtime
+ content *contentCipher
// sampleDocuments mirrors Config.SampleDocuments, already parsed —
// see EnsurePerson's own doc comment for what it gates and why the
@@ -846,7 +857,18 @@ func (s *Store) ApplyUpdate(ctx context.Context, doc *Document, actor Actor, upd
if err := s.checkPermission(ctx, s.db.WithContext(ctx), actor, doc.ID, permissionWrite); err != nil {
return 0, err
}
+ // A warm handle when this Store keeps them (warm.go, the live-push
+ // spec's §3.5); otherwise, and as its own fallback, the replay below.
+ if s.warm != nil {
+ return s.applyWarm(ctx, doc, actor, update)
+ }
+ return s.applyCold(ctx, doc, actor, update)
+}
+// applyCold is ApplyUpdate as it has always been: replay the document,
+// snapshot at the cadence, apply, commit. The caller has checked write
+// permission.
+func (s *Store) applyCold(ctx context.Context, doc *Document, actor Actor, update []byte) (int64, error) {
h, replayedSeq, lastSnapshotSeq, err := s.replay(ctx, doc)
if err != nil {
return 0, err
@@ -895,7 +917,15 @@ func (s *Store) ApplyUpdate(ctx context.Context, doc *Document, actor Actor, upd
if err := h.Apply(ctx, update); err != nil {
return 0, fmt.Errorf("docs: apply update to document %d: %w", doc.ID, &updateRejection{err})
}
+ seq, _, err := s.commitUpdate(ctx, doc, actor, update)
+ return seq, err
+}
+// commitUpdate writes update as doc's next row, in the single-writer
+// transaction, and returns the seq it was given and the log's MAX(seq)
+// before it (which a warm handle compares with its own). Both paths of
+// ApplyUpdate end here, so there is one transaction to reason about.
+func (s *Store) commitUpdate(ctx context.Context, doc *Document, actor Actor, update []byte) (int64, int64, error) {
// MAX(seq) then INSERT used to be two separate statements, not one
// atomic step: two concurrent POSTs to this same document (Task 6's
// flush timer and its beforeunload beacon are exactly the pair that
@@ -930,7 +960,7 @@ func (s *Store) ApplyUpdate(ctx context.Context, doc *Document, actor Actor, upd
// (design D4: the seq is meaningful only when err == nil). Nothing
// about the single-writer MAX(seq)->INSERT guarantee above changes
// by observing the number the closure already computed.
- var assignedSeq int64
+ var assignedSeq, before int64
if err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := s.checkPermission(ctx, tx, actor, doc.ID, permissionWrite); err != nil {
return err
@@ -943,6 +973,7 @@ func (s *Store) ApplyUpdate(ctx context.Context, doc *Document, actor Actor, upd
return fmt.Errorf("docs: determine next seq for document %d: %w", doc.ID, err)
}
+ before = maxSeq
row := &DocUpdate{
DocID: doc.ID,
Seq: maxSeq + 1,
@@ -964,12 +995,17 @@ func (s *Store) ApplyUpdate(ctx context.Context, doc *Document, actor Actor, upd
return err
}
assignedSeq = row.Seq
+ if s.warmBeforeCommit != nil {
+ if err := s.warmBeforeCommit(ctx, tx, doc); err != nil {
+ return err
+ }
+ }
return s.checkPermission(ctx, tx, actor, doc.ID, permissionWrite)
}); err != nil {
- return 0, err
+ return 0, 0, err
}
- return assignedSeq, nil
+ return assignedSeq, before, nil
}
// Rename repeats write authorization within the transaction, as ApplyUpdate does.
diff --git a/internal/docs/stream.go b/internal/docs/stream.go
index f953822..29b3dea 100644
--- a/internal/docs/stream.go
+++ b/internal/docs/stream.go
@@ -210,6 +210,9 @@ func (h *handlers) stream(w http.ResponseWriter, r *http.Request) {
}
heartbeat.Reset(h.heartbeatInterval())
case <-heartbeat.C:
+ // The heartbeat is a timer inside a live connection, so it may
+ // also sweep idle warm handles (warm.go, rule 7).
+ h.store.warm.sweep(r.Context())
if !write(": ping\n\n") {
return
}
diff --git a/internal/docs/suite_feed.go b/internal/docs/suite_feed.go
index 335cc2c..6ea298a 100644
--- a/internal/docs/suite_feed.go
+++ b/internal/docs/suite_feed.go
@@ -180,6 +180,7 @@ func (s *Store) SetVisibility(ctx context.Context, owner int64, sqid string, v V
// The person's way in is Store.Delete (delete.go), behind the owner's
// guard; both go through softDelete, so neither can forget the feed row.
func (s *Store) deleteDocument(ctx context.Context, docID int64) error {
+ defer s.warm.drop(ctx, docID) // warm.go, rule 6
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
return softDelete(tx, docID)
})
diff --git a/internal/docs/team_access.go b/internal/docs/team_access.go
index 55b37dc..ee90f59 100644
--- a/internal/docs/team_access.go
+++ b/internal/docs/team_access.go
@@ -217,6 +217,9 @@ func (s *Store) snapshotPermission(ctx context.Context, db *gorm.DB, docID int64
// same latched Access matched to the actor; with team mode off it is
// ownership alone.
func (s *Store) ownerMutation(ctx context.Context, owner, docID int64, mutate func(*gorm.DB) error) error {
+ // Grants and visibility change who may read: no warm handle (and its
+ // decrypted state) outlives that (warm.go, rule 6).
+ defer s.warm.drop(ctx, docID)
actor := s.ownerActor(ctx, owner)
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
authorize := func(roster.State) error { return s.checkPermission(ctx, tx, actor, docID, permissionOwner) }
diff --git a/internal/docs/warm.go b/internal/docs/warm.go
new file mode 100644
index 0000000..a57a2f7
--- /dev/null
+++ b/internal/docs/warm.go
@@ -0,0 +1,333 @@
+package docs
+
+// Warm handles: the live-push spec's §3.5
+// (docs/superpowers/specs/2026-11-26-live-push-design.md), slice 1a.
+//
+// Store.ApplyUpdate used to replay the whole document for every POST: a
+// fresh WASM instance, the newest snapshot and up to 255 tail rows, then
+// the update. At 20 pages that was ~11 ms of CPU and ~8 MB of garbage per
+// keystroke batch, a third of the server's CPU. A warm handle is the
+// replayed core.Handle kept between POSTs, so a POST applies one update
+// (~15 µs) instead.
+//
+// The rules, each of which some test in warm_test.go holds:
+//
+// 1. One POST at a time per document: the entry's mutex is held from the
+// Apply to the commit. POSTs to one document already serialise on the
+// single SQLite writer, so this costs nothing.
+// 2. Applied before the transaction, as the replayed handle always was. A
+// clean core rejection leaves the handle as it was (the POST answers
+// 400, as before). Anything else from Apply (ErrUpdateLogFull, a trap,
+// RecoveredError) drops the handle and the POST is redone cold, so the
+// cache never fails a POST.
+// 3. Committed, or dropped. Any failure after a successful Apply drops the
+// handle, and its seq advances only after commit. If the log's MAX(seq)
+// inside the transaction is not the handle's seq (another process, the
+// agent path, a test), the row is still written, as a stale replay's
+// always was, and the handle is dropped.
+// 4. Re-seeded at the snapshot cadence: snapshot from the warm state at the
+// handle's seq, Apply, commit, then drop; the next POST replays from that
+// snapshot. A warm handle therefore never retains more than ~257
+// updates, far from core.MaxRetainedUpdates (4,096). A failed snapshot
+// write keeps the handle, as a failed cold one kept the log.
+// 5. Bounded: warmMaxBytes of ResidentBytes and warmMaxHandles handles,
+// least recently used out first; one handle above the byte cap is never
+// kept.
+// 6. Dropped on delete, on any change to a document's grants or
+// visibility, after warmIdle without a POST, and when the app drains or
+// closes. Sealing is activated offline (MaintainContent) with the app
+// stopped, so a process never sees it change under a handle.
+// 7. Swept by every POST and by every open stream's heartbeat (stream.go),
+// a timer inside a live connection: no timer of its own.
+// 8. Two processes on one database stay correct, because rule 3's check is
+// inside the transaction.
+//
+// A Store bound to a caller's transaction (the agent paths) never uses
+// warm handles: its "commit" is a savepoint the caller can still roll back
+// after ApplyUpdate returns, which rule 3 cannot see.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sort"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/docs/internal/core"
+ "gorm.io/gorm"
+)
+
+const (
+ warmIdle = 60 * time.Second
+ warmMaxHandles = 64
+ warmMaxBytes = 128 << 20
+)
+
+// warmEntry is one document's handle. mu is rule 1's per-document lock.
+type warmEntry struct {
+ mu sync.Mutex
+ docID int64
+ h *core.Handle
+ seq int64 // the log's MAX(seq) the handle holds
+ 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
+
+ // Read and written under the cache's mu, so the caps and stats never
+ // look at a handle another goroutine is using.
+ bytes uint64
+ kept bool
+}
+
+type warmCache struct {
+ mu sync.Mutex
+ entries map[int64]*warmEntry
+ closed bool
+ maxBytes uint64
+ maxHandles int
+ idle time.Duration
+ now func() time.Time
+}
+
+func newWarmCache() *warmCache {
+ return &warmCache{entries: map[int64]*warmEntry{}, maxBytes: warmMaxBytes, maxHandles: warmMaxHandles, idle: warmIdle, now: time.Now}
+}
+
+// acquire returns docID's entry locked, or nil when the cache is closed.
+func (c *warmCache) acquire(ctx context.Context, docID int64) *warmEntry {
+ c.mu.Lock()
+ if c.closed {
+ c.mu.Unlock()
+ return nil
+ }
+ c.sweepLocked(ctx, docID)
+ e := c.entries[docID]
+ if e == nil {
+ e = &warmEntry{docID: docID}
+ c.entries[docID] = e
+ }
+ e.used = c.now()
+ c.mu.Unlock()
+ e.mu.Lock()
+ return e
+}
+
+// release unlocks e after a POST, closing its handle if it was dropped
+// meanwhile or is too large to keep, and then enforces the caps.
+func (c *warmCache) release(ctx context.Context, e *warmEntry) {
+ var bytes uint64
+ if e.h != nil {
+ bytes = e.h.ResidentBytes()
+ }
+ c.mu.Lock()
+ if e.dead || c.closed || bytes > c.maxBytes {
+ e.close(ctx)
+ bytes = 0
+ if c.entries[e.docID] == e {
+ delete(c.entries, e.docID)
+ }
+ }
+ e.bytes, e.kept = bytes, e.h != nil
+ e.used = c.now()
+ e.mu.Unlock()
+ c.capLocked(ctx)
+ c.mu.Unlock()
+}
+
+// close drops e's handle. The caller holds e.mu.
+func (e *warmEntry) close(ctx context.Context) {
+ if e.h != nil {
+ e.h.Close(ctx)
+ }
+ e.h, e.seq, e.snap = nil, 0, 0
+}
+
+// evictLocked removes e from the cache. c.mu is held; e.mu is taken if it
+// is free, and otherwise e is marked dead for its holder to close.
+func (c *warmCache) evictLocked(ctx context.Context, e *warmEntry) {
+ delete(c.entries, e.docID)
+ e.bytes, e.kept = 0, false
+ if e.mu.TryLock() {
+ e.close(ctx)
+ e.mu.Unlock()
+ return
+ }
+ e.dead = true
+}
+
+// sweepLocked drops entries unused for c.idle (rule 7), except keep.
+func (c *warmCache) sweepLocked(ctx context.Context, keep int64) {
+ cutoff := c.now().Add(-c.idle)
+ for id, e := range c.entries {
+ if id != keep && e.used.Before(cutoff) {
+ c.evictLocked(ctx, e)
+ }
+ }
+}
+
+// capLocked evicts least recently used entries until both caps hold.
+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 total <= c.maxBytes && len(list) <= c.maxHandles {
+ return
+ }
+ sort.Slice(list, func(i, j int) bool { return list[i].used.Before(list[j].used) })
+ for _, e := range list {
+ if total <= c.maxBytes && len(c.entries) <= c.maxHandles {
+ return
+ }
+ total -= e.bytes
+ c.evictLocked(ctx, e)
+ }
+}
+
+// sweep is rule 7's entry point for the stream heartbeat. nil-safe.
+func (c *warmCache) sweep(ctx context.Context) {
+ if c == nil {
+ return
+ }
+ c.mu.Lock()
+ c.sweepLocked(ctx, 0)
+ c.mu.Unlock()
+}
+
+// drop forgets docID's handle (rule 6). nil-safe.
+func (c *warmCache) drop(ctx context.Context, docID int64) {
+ if c == nil {
+ return
+ }
+ c.mu.Lock()
+ if e := c.entries[docID]; e != nil {
+ c.evictLocked(ctx, e)
+ }
+ c.mu.Unlock()
+}
+
+// close drops every handle and keeps no more (drain, shutdown). nil-safe.
+func (c *warmCache) close(ctx context.Context) {
+ if c == nil {
+ return
+ }
+ c.mu.Lock()
+ c.closed = true
+ for _, e := range c.entries {
+ c.evictLocked(ctx, e)
+ }
+ c.mu.Unlock()
+}
+
+// stats reports how many handles are kept and their bytes (tests, probes).
+func (c *warmCache) stats() (handles int, bytes uint64) {
+ if c == nil {
+ return 0, 0
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ for _, e := range c.entries {
+ if e.kept {
+ handles++
+ bytes += e.bytes
+ }
+ }
+ return handles, bytes
+}
+
+// applyWarm is ApplyUpdate with a warm handle (rules 1–4). The caller has
+// checked write permission.
+func (s *Store) applyWarm(ctx context.Context, doc *Document, actor Actor, update []byte) (int64, error) {
+ e := s.warm.acquire(ctx, doc.ID)
+ if e == nil {
+ return s.applyCold(ctx, doc, actor, update)
+ }
+ defer s.warm.release(ctx, e)
+
+ if e.h == nil {
+ h, replayedSeq, lastSnapshotSeq, err := s.replay(ctx, doc)
+ if err != nil {
+ return 0, err
+ }
+ e.h, e.seq, e.snap = h, replayedSeq, lastSnapshotSeq
+ }
+
+ // Rule 4, with D3's placement: the snapshot is the state before this
+ // update, at the handle's seq.
+ reseed := false
+ if e.seq-e.snap >= snapshotCadence {
+ if err := s.writeSnapshot(ctx, doc, e.h, e.seq); err != nil {
+ if s.team != nil {
+ // As the cold path: in team mode the POST fails. The
+ // handle is unchanged (a snapshot only reads it).
+ if errors.Is(err, ErrNotWritable) {
+ return 0, err
+ }
+ return 0, errTeamUnavailable
+ }
+ s.logger.Error("docs: write snapshot", "doc_id", doc.ID, "seq", e.seq, "err", err)
+ } else {
+ e.snap = e.seq
+ reseed = true
+ }
+ }
+
+ if err := s.warmApply(ctx, e.h, update); err != nil {
+ var rejected *core.RejectedError
+ if errors.As(err, &rejected) {
+ return 0, fmt.Errorf("docs: apply update to document %d: %w", doc.ID, &updateRejection{err})
+ }
+ // A full log, a trap or a recovered instance: rule 2.
+ s.logger.Warn("docs: warm handle dropped, replaying", "doc_id", doc.ID, "err", err)
+ e.close(ctx)
+ return s.applyCold(ctx, doc, actor, update)
+ }
+
+ seq, before, err := s.commitUpdate(ctx, doc, actor, update)
+ if err != nil {
+ e.close(ctx) // rule 3: applied, not committed
+ return 0, err
+ }
+ if before != e.seq || reseed {
+ e.close(ctx) // rule 3 (stale) or rule 4 (re-seed)
+ } else {
+ e.seq = seq
+ }
+ return seq, nil
+}
+
+// warmApply is Handle.Apply, behind a seam the tests use to inject the
+// failures rule 2 is about.
+func (s *Store) warmApply(ctx context.Context, h *core.Handle, update []byte) error {
+ if s.warmApplyHook != nil {
+ if err := s.warmApplyHook(h); err != nil {
+ return err
+ }
+ }
+ return h.Apply(ctx, update)
+}
+
+// boundTo returns a copy of s whose queries run in tx, without warm
+// handles (see this file's header): the agent paths' ApplyUpdate commits a
+// savepoint the caller can still roll back.
+func (s *Store) boundTo(tx *gorm.DB) *Store {
+ c := *s
+ c.db = tx
+ c.warm = nil
+ return &c
+}
+
+// ParseWarmHandle reads $DOCS_WARM_HANDLE: on/off (also 1/0, true/false);
+// unset is off. Anything else is a startup refusal rather than a guess.
+func ParseWarmHandle(v string) (bool, error) {
+ switch v {
+ case "", "off", "0", "false":
+ return false, nil
+ case "on", "1", "true":
+ return true, nil
+ }
+ return false, fmt.Errorf("docs: DOCS_WARM_HANDLE must be on or off, not %q", v)
+}
diff --git a/internal/docs/warm_test.go b/internal/docs/warm_test.go
new file mode 100644
index 0000000..26ea436
--- /dev/null
+++ b/internal/docs/warm_test.go
@@ -0,0 +1,597 @@
+package docs
+
+// Warm handles (warm.go; the live-push spec's §3.5 and §9.1). Each test
+// names the rule it holds.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "math/rand"
+ "net/http/httptest"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/docs/internal/core"
+ "gorm.io/gorm"
+)
+
+type warmFixture struct {
+ t *testing.T
+ app *App
+ s *Store
+ owner int64
+ actor Actor
+ doc *Document
+ ctx context.Context
+}
+
+func newWarmFixture(t *testing.T) *warmFixture {
+ t.Helper()
+ app, err := NewForTestWith(t, Config{WarmHandle: true})
+ if err != nil {
+ t.Fatalf("NewForTestWith: %v", err)
+ }
+ ctx := context.Background()
+ owner := app.TestPerson(t, "owner@example.com")
+ doc, err := app.Store().Create(ctx, owner, "Warm")
+ if err != nil {
+ t.Fatalf("Create: %v", err)
+ }
+ return &warmFixture{t: t, app: app, s: app.store, owner: owner, actor: localActor(owner, "owner@example.com"), doc: doc, ctx: ctx}
+}
+
+// word returns a valid update that adds one paragraph, "word<k>".
+func (f *warmFixture) word(k int) []byte {
+ f.t.Helper()
+ u, err := f.app.core.InitialUpdate(f.ctx, f.doc.GUID, uint64(100000+k), []core.InitialBlock{{Text: fmt.Sprintf("word%d", k)}})
+ if err != nil {
+ f.t.Fatalf("InitialUpdate: %v", err)
+ }
+ return u
+}
+
+func (f *warmFixture) post(update []byte) (int64, error) {
+ return f.s.ApplyUpdate(f.ctx, f.doc, f.actor, update)
+}
+
+func (f *warmFixture) mustPost(update []byte) int64 {
+ f.t.Helper()
+ seq, err := f.post(update)
+ if err != nil {
+ f.t.Fatalf("ApplyUpdate: %v", err)
+ }
+ return seq
+}
+
+// entry is the cache's entry for the fixture's document, or nil.
+func (f *warmFixture) entry() *warmEntry {
+ f.s.warm.mu.Lock()
+ defer f.s.warm.mu.Unlock()
+ return f.s.warm.entries[f.doc.ID]
+}
+
+func (f *warmFixture) warmText() (string, bool) {
+ f.t.Helper()
+ e := f.entry()
+ if e == nil || e.h == nil {
+ return "", false
+ }
+ text, err := e.h.Text(f.ctx)
+ if err != nil {
+ f.t.Fatalf("warm Text: %v", err)
+ }
+ return text, true
+}
+
+// rowsText replays the log's rows up to seq (all when seq < 0) into a fresh
+// handle, with no snapshot: the ground truth.
+func (f *warmFixture) rowsText(upto int64) string {
+ f.t.Helper()
+ q := f.s.db.WithContext(f.ctx).Where("doc_id = ?", f.doc.ID)
+ if upto >= 0 {
+ q = q.Where("seq <= ?", upto)
+ }
+ var rows []DocUpdate
+ if err := q.Order("seq ASC").Find(&rows).Error; err != nil {
+ f.t.Fatal(err)
+ }
+ h, err := f.s.core.NewDoc(f.ctx, f.doc.GUID, f.doc.ClientID)
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ defer h.Close(f.ctx)
+ for i := range rows {
+ if err := f.s.openContentUpdate(f.doc.GUID, &rows[i]); err != nil {
+ f.t.Fatal(err)
+ }
+ if i > 0 && i%1000 == 0 {
+ // Past a few thousand rows a handle would refuse more; rebuild
+ // from its own snapshot as replay does.
+ state, err := h.Snapshot(f.ctx)
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ h.Close(f.ctx)
+ if h, err = f.s.core.NewDoc(f.ctx, f.doc.GUID, f.doc.ClientID); err != nil {
+ f.t.Fatal(err)
+ }
+ if err := h.Apply(f.ctx, state); err != nil {
+ f.t.Fatal(err)
+ }
+ }
+ if err := h.Apply(f.ctx, rows[i].UpdateBin); err != nil {
+ f.t.Fatalf("raw replay of row %d: %v", rows[i].Seq, err)
+ }
+ }
+ text, err := h.Text(f.ctx)
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ return text
+}
+
+// coldText is what an ordinary replay (snapshot plus tail) gives.
+func (f *warmFixture) coldText() string {
+ f.t.Helper()
+ h, _, _, err := f.s.replay(f.ctx, f.doc)
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ defer h.Close(f.ctx)
+ text, err := h.Text(f.ctx)
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ return text
+}
+
+func sortedWords(text string) string {
+ words := strings.Fields(text)
+ sort.Strings(words)
+ return strings.Join(words, " ")
+}
+
+// Rule 4, finding 1 of the review: a warm handle must never reach
+// core.MaxRetainedUpdates, where Apply refuses and the web's save queue
+// would drop the batch. 4,200 POSTs to one document, none refused.
+func TestWarmHandleOutlivesMaxRetainedUpdates(t *testing.T) {
+ if testing.Short() {
+ t.Skip("4,200 POSTs")
+ }
+ f := newWarmFixture(t)
+ update := f.word(1) // the same bytes every time: Yjs integrates a repeat as nothing
+ most := 0
+ const n = core.MaxRetainedUpdates + 104
+ for i := 0; i < n; i++ {
+ if _, err := f.post(update); err != nil {
+ t.Fatalf("POST %d of %d refused: %v", i+1, n, err)
+ }
+ if e := f.entry(); e != nil && e.h != nil && e.h.RetainedUpdates() > most {
+ most = e.h.RetainedUpdates()
+ }
+ }
+ if most > snapshotCadence+2 {
+ t.Errorf("a warm handle retained %d updates; re-seeding should keep it near %d", most, snapshotCadence)
+ }
+ snap, err := f.s.newestSnapshot(f.ctx, f.doc.ID)
+ if err != nil || snap == nil || snap.Seq < n-snapshotCadence-1 {
+ t.Errorf("newest snapshot %+v after %d POSTs: re-seeding should keep one within %d rows", snap, n, snapshotCadence)
+ }
+}
+
+// Rule 4's order: snapshot from the warm state at the handle's seq (before
+// this POST's update), Apply, commit, drop; the next POST replays.
+func TestWarmHandleReseedsAtTheSnapshotCadence(t *testing.T) {
+ f := newWarmFixture(t)
+ for k := 1; k <= snapshotCadence; k++ {
+ f.mustPost(f.word(k))
+ }
+ if e := f.entry(); e == nil || e.h == nil || e.seq != snapshotCadence {
+ t.Fatalf("after %d POSTs the handle should be warm at seq %d", snapshotCadence, snapshotCadence)
+ }
+ seq := f.mustPost(f.word(snapshotCadence + 1))
+ snap, err := f.s.newestSnapshot(f.ctx, f.doc.ID)
+ if err != nil || snap == nil {
+ t.Fatalf("no snapshot after the cadence: %v", err)
+ }
+ if snap.Seq != snapshotCadence {
+ t.Errorf("snapshot at seq %d, want %d (the state before POST %d)", snap.Seq, snapshotCadence, seq)
+ }
+ if e := f.entry(); e != nil && e.h != nil {
+ t.Error("the handle should be dropped after the re-seeding POST")
+ }
+ f.mustPost(f.word(snapshotCadence + 2))
+ e := f.entry()
+ if e == nil || e.h == nil || e.snap != snapshotCadence || e.seq != snapshotCadence+2 {
+ t.Fatalf("the next POST should replay from the snapshot: %+v", e)
+ }
+ if got, _ := f.warmText(); sortedWords(got) != sortedWords(f.rowsText(-1)) {
+ t.Error("the re-seeded handle differs from a replay of the log")
+ }
+}
+
+// Rule 3, finding 2 of the review: a writer revoked between the warm Apply
+// and the commit. The POST fails, the handle is dropped, and nothing the
+// refused update wrote survives into the next snapshot.
+func TestWarmHandleIsDroppedWhenTheWriterIsRevokedBeforeCommit(t *testing.T) {
+ f := newWarmFixture(t)
+ writer := f.app.TestPerson(t, "writer@example.com")
+ if err := f.s.Grant(f.ctx, f.owner, f.doc.Sqid, "writer@example.com", RoleWriter); err != nil {
+ t.Fatalf("Grant: %v", err)
+ }
+ writerActor := localActor(writer, "writer@example.com")
+ if _, err := f.s.ApplyUpdate(f.ctx, f.doc, writerActor, f.word(1)); err != nil {
+ t.Fatalf("writer's first POST: %v", err)
+ }
+ if _, ok := f.warmText(); !ok {
+ t.Fatal("the handle should be warm")
+ }
+ f.s.warmBeforeCommit = func(ctx context.Context, tx *gorm.DB, doc *Document) error {
+ // Inside the transaction: the grant goes, so the transaction's own
+ // closing permission check refuses.
+ return tx.Where("doc_id = ? AND subject = ?", doc.ID, "writer@example.com").Delete(&Grant{}).Error
+ }
+ if _, err := f.s.ApplyUpdate(f.ctx, f.doc, writerActor, f.word(666)); !errors.Is(err, ErrNotWritable) {
+ t.Fatalf("POST after revocation: %v, want ErrNotWritable", err)
+ }
+ f.s.warmBeforeCommit = nil
+ if _, ok := f.warmText(); ok {
+ t.Fatal("a handle that applied an uncommitted update must be dropped")
+ }
+ // Enough owner POSTs to cross the cadence, so the next snapshot is
+ // written from a handle rebuilt after the failure.
+ for k := 2; k <= snapshotCadence+3; k++ {
+ f.mustPost(f.word(k))
+ }
+ snap, err := f.s.newestSnapshot(f.ctx, f.doc.ID)
+ if err != nil || snap == nil {
+ t.Fatalf("no snapshot: %v", err)
+ }
+ h, err := f.s.core.NewDoc(f.ctx, f.doc.GUID, f.doc.ClientID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer h.Close(f.ctx)
+ if err := h.Apply(f.ctx, snap.State); err != nil {
+ t.Fatal(err)
+ }
+ snapText, _ := h.Text(f.ctx)
+ if strings.Contains(snapText, "word666") {
+ t.Fatal("the refused update reached a snapshot")
+ }
+ if sortedWords(snapText) != sortedWords(f.rowsText(snap.Seq)) {
+ t.Error("the snapshot differs from a replay of the rows it covers")
+ }
+}
+
+// Rule 2: anything but a clean rejection from the warm Apply (a full log,
+// a trap, a recovered instance) redoes the POST cold; the POST succeeds.
+func TestWarmHandleFallsBackToAColdReplay(t *testing.T) {
+ for _, injected := range []error{core.ErrUpdateLogFull, errors.New("trap: unreachable")} {
+ t.Run(injected.Error(), func(t *testing.T) {
+ f := newWarmFixture(t)
+ f.mustPost(f.word(1))
+ f.s.warmApplyHook = func(*core.Handle) error { return injected }
+ seq, err := f.post(f.word(2))
+ f.s.warmApplyHook = nil
+ if err != nil || seq != 2 {
+ t.Fatalf("POST = %d, %v; the cold path should have taken it", seq, err)
+ }
+ if _, ok := f.warmText(); ok {
+ t.Error("the failed handle should be gone")
+ }
+ f.mustPost(f.word(3))
+ if got, ok := f.warmText(); !ok || sortedWords(got) != sortedWords(f.rowsText(-1)) {
+ t.Error("the next POST should warm a fresh handle equal to the log")
+ }
+ })
+ }
+}
+
+// Rule 2: a clean core rejection answers as before and leaves the handle.
+func TestWarmHandleSurvivesARejectedUpdate(t *testing.T) {
+ f := newWarmFixture(t)
+ f.mustPost(f.word(1))
+ before, _ := f.warmText()
+ _, err := f.post([]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff})
+ var rejection *updateRejection
+ if !errors.As(err, &rejection) {
+ t.Fatalf("garbage: %v, want an update rejection", err)
+ }
+ after, ok := f.warmText()
+ if !ok || after != before || f.entry().seq != 1 {
+ t.Error("a rejected update should leave the warm handle as it was")
+ }
+}
+
+// Rules 2–3 and 8 together: random POSTs, failed commits, injected Apply
+// failures, rejections, drops and commits by another Store on the same
+// database (a second process, or the agent path). After every step the
+// log holds exactly the committed words, and a warm handle, when there is
+// one after a POST of its own, equals a replay of the log.
+func TestWarmHandleMatchesAColdReplayUnderFailures(t *testing.T) {
+ seeds := 8
+ if testing.Short() {
+ seeds = 2
+ }
+ for seed := 1; seed <= seeds; seed++ {
+ t.Run(fmt.Sprint("seed", seed), func(t *testing.T) {
+ f := newWarmFixture(t)
+ other := NewStore(f.s.db, f.s.core, false, f.s.logger) // another process: no shared cache
+ rng := rand.New(rand.NewSource(int64(seed)))
+ committed := map[string]bool{}
+ refused := map[string]bool{}
+ for step := 0; step < 60; step++ {
+ k := seed*1000 + step
+ word := fmt.Sprintf("word%d", k)
+ warmAfterPost := false
+ switch op := rng.Intn(10); {
+ case op < 4:
+ f.mustPost(f.word(k))
+ committed[word] = true
+ warmAfterPost = true
+ case op == 4:
+ f.s.warmBeforeCommit = func(context.Context, *gorm.DB, *Document) error { return errors.New("injected: commit failed") }
+ if _, err := f.post(f.word(k)); err == nil {
+ t.Fatal("a failed commit reported success")
+ }
+ f.s.warmBeforeCommit = nil
+ refused[word] = true
+ case op == 5:
+ f.s.warmApplyHook = func(*core.Handle) error { return errors.New("injected: trap") }
+ f.mustPost(f.word(k))
+ f.s.warmApplyHook = nil
+ committed[word] = true
+ case op == 6:
+ if _, err := other.ApplyUpdate(f.ctx, f.doc, f.actor, f.word(k)); err != nil {
+ t.Fatalf("other store: %v", err)
+ }
+ committed[word] = true
+ case op == 7:
+ f.s.warm.drop(f.ctx, f.doc.ID)
+ case op == 8:
+ if _, err := f.post([]byte{0xff, 0xff, 0xff}); err == nil {
+ t.Fatal("garbage accepted")
+ }
+ default:
+ ctx, cancel := context.WithCancel(f.ctx)
+ f.s.warmBeforeCommit = func(context.Context, *gorm.DB, *Document) error { cancel(); return ctx.Err() }
+ if _, err := f.s.ApplyUpdate(ctx, f.doc, f.actor, f.word(k)); err == nil {
+ t.Fatal("a cancelled commit reported success")
+ }
+ f.s.warmBeforeCommit = nil
+ refused[word] = true
+ }
+ truth := f.rowsText(-1)
+ for w := range committed {
+ if !strings.Contains(truth, w+" ") && !strings.HasSuffix(truth, w) && !strings.Contains(truth, w+"\n") {
+ t.Fatalf("step %d: committed %s missing from the log", step, w)
+ }
+ }
+ for w := range refused {
+ if strings.Contains(truth, w) {
+ t.Fatalf("step %d: refused %s is in the log", step, w)
+ }
+ }
+ if warmAfterPost {
+ if got, ok := f.warmText(); ok && sortedWords(got) != sortedWords(truth) {
+ t.Fatalf("step %d: the warm handle differs from the log", step)
+ }
+ }
+ }
+ if sortedWords(f.coldText()) != sortedWords(f.rowsText(-1)) {
+ t.Fatal("a cold replay differs from the log")
+ }
+ })
+ }
+}
+
+// Rule 5: least recently used out first, by count and by bytes, and one
+// handle larger than the byte cap is never kept.
+func TestWarmHandlesAreBoundedByCountAndBytes(t *testing.T) {
+ f := newWarmFixture(t)
+ docs := []*Document{f.doc}
+ for i := 0; i < 2; i++ {
+ d, err := f.s.Create(f.ctx, f.owner, fmt.Sprint("Warm ", i))
+ if err != nil {
+ t.Fatal(err)
+ }
+ docs = append(docs, d)
+ }
+ post := func(d *Document, k int) {
+ u, err := f.app.core.InitialUpdate(f.ctx, d.GUID, uint64(200000+k), []core.InitialBlock{{Text: fmt.Sprint("x", k)}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.s.ApplyUpdate(f.ctx, d, f.actor, u); err != nil {
+ t.Fatal(err)
+ }
+ }
+ kept := func(d *Document) bool {
+ f.s.warm.mu.Lock()
+ defer f.s.warm.mu.Unlock()
+ e := f.s.warm.entries[d.ID]
+ return e != nil && e.kept
+ }
+
+ post(docs[0], 1)
+ _, one := f.s.warm.stats()
+ if one == 0 {
+ t.Fatal("no bytes counted for a warm handle")
+ }
+
+ f.s.warm.maxHandles = 2
+ post(docs[1], 2)
+ post(docs[2], 3)
+ if n, _ := f.s.warm.stats(); n != 2 || kept(docs[0]) {
+ t.Errorf("count cap 2: %d handles, oldest kept %v", n, kept(docs[0]))
+ }
+
+ f.s.warm.maxHandles = warmMaxHandles
+ f.s.warm.maxBytes = one*2 + one/2
+ post(docs[0], 4)
+ if n, b := f.s.warm.stats(); n != 2 || b > f.s.warm.maxBytes || kept(docs[1]) {
+ t.Errorf("byte cap for two: %d handles, %d bytes, oldest kept %v", n, b, kept(docs[1]))
+ }
+
+ f.s.warm.maxBytes = one / 2
+ post(docs[2], 5)
+ if kept(docs[2]) {
+ t.Error("a handle larger than the byte cap was kept")
+ }
+}
+
+// Rule 6: delete, grant, revoke and visibility drop the document's handle;
+// drain drops every handle and keeps no more.
+func TestWarmHandleIsDroppedWhenAccessChanges(t *testing.T) {
+ cases := []struct {
+ name string
+ change func(f *warmFixture) error
+ }{
+ {"grant", func(f *warmFixture) error {
+ return f.s.Grant(f.ctx, f.owner, f.doc.Sqid, "reader@example.com", RoleReader)
+ }},
+ {"revoke", func(f *warmFixture) error {
+ return f.s.Revoke(f.ctx, f.owner, f.doc.Sqid, "reader@example.com")
+ }},
+ {"visibility", func(f *warmFixture) error {
+ return f.s.SetVisibility(f.ctx, f.owner, f.doc.Sqid, VisibilityPrivate)
+ }},
+ {"delete", func(f *warmFixture) error { return f.s.Delete(f.ctx, f.owner, f.doc.Sqid) }},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ f := newWarmFixture(t)
+ f.mustPost(f.word(1))
+ if _, ok := f.warmText(); !ok {
+ t.Fatal("not warm")
+ }
+ if err := c.change(f); err != nil {
+ t.Fatalf("%s: %v", c.name, err)
+ }
+ if _, ok := f.warmText(); ok {
+ t.Errorf("%s left the warm handle", c.name)
+ }
+ })
+ }
+ t.Run("drain", func(t *testing.T) {
+ f := newWarmFixture(t)
+ f.mustPost(f.word(1))
+ f.app.Drain()
+ if n, _ := f.s.warm.stats(); n != 0 {
+ t.Fatalf("%d handles after drain", n)
+ }
+ f.mustPost(f.word(2))
+ if n, _ := f.s.warm.stats(); n != 0 {
+ t.Errorf("a drained cache kept a handle")
+ }
+ })
+}
+
+// Rule 7: an open stream's heartbeat sweeps handles idle for warmIdle,
+// with no POST to do it.
+func TestWarmHandleIsSweptByTheStreamHeartbeat(t *testing.T) {
+ f := newWarmFixture(t)
+ f.mustPost(f.word(1))
+ clock := time.Now()
+ f.s.warm.mu.Lock()
+ f.s.warm.now = func() time.Time { return clock }
+ f.s.warm.mu.Unlock()
+ clock = clock.Add(warmIdle + time.Second)
+
+ streamDurations(t, f.app, 50*time.Millisecond, 5*time.Second)
+ srv := httptest.NewServer(f.app.Handler())
+ defer srv.Close()
+ res, body := openStream(t, srv, f.app, "owner@example.com", "/d/"+f.doc.Sqid+"/stream")
+ defer res.Body.Close()
+ nextEvent(t, body, 2*time.Second) // the connect event
+ if name, _ := nextEvent(t, body, 2*time.Second); name != "ping" {
+ t.Fatalf("want a heartbeat, got %q", name)
+ }
+ if _, ok := f.warmText(); ok {
+ t.Error("an idle handle survived the heartbeat")
+ }
+}
+
+// The agent paths' Store copies run inside the caller's transaction and
+// must never use (or advance) a warm handle.
+func TestAStoreBoundToATransactionHasNoWarmHandles(t *testing.T) {
+ f := newWarmFixture(t)
+ if f.s.boundTo(f.s.db).warm != nil {
+ t.Fatal("boundTo kept the warm cache")
+ }
+ if f.s.warm == nil {
+ t.Fatal("boundTo changed the original")
+ }
+}
+
+// Off, nothing is kept: every POST replays, as before slice 1a.
+func TestWarmHandleSwitchOff(t *testing.T) {
+ app, err := NewForTest(t)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if app.store.warm != nil {
+ t.Fatal("warm handles are on by default; the spec keeps them off until slice 1a is proven")
+ }
+ for _, c := range []struct {
+ in string
+ want bool
+ bad bool
+ }{{"", false, false}, {"off", false, false}, {"on", true, false}, {"1", true, false}, {"yes", false, true}} {
+ got, err := ParseWarmHandle(c.in)
+ if got != c.want || (err != nil) != c.bad {
+ t.Errorf("ParseWarmHandle(%q) = %v, %v", c.in, got, err)
+ }
+ }
+}
+
+// The slice's relative timing gate (the spec's §9.2, applied to 1a): on a
+// ~20-page document, in the same process and the same run, a POST through
+// a warm handle takes less time than one that replays. Best of three
+// medians each, so a loaded machine slows both sides alike; no absolute
+// threshold. It fails, never skips.
+func TestWarmHandleIsFasterThanAReplay(t *testing.T) {
+ f := newWarmFixture(t)
+ blocks := make([]core.InitialBlock, 150)
+ para := strings.Repeat("lorem ipsum dolor sit amet consectetur ", 10) // ~400 characters
+ for i := range blocks {
+ blocks[i] = core.InitialBlock{Text: fmt.Sprint(i, " ", para)}
+ }
+ seed, err := f.app.core.InitialUpdate(f.ctx, f.doc.GUID, 99, blocks)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.mustPost(seed)
+ measure := func(warm bool, from int) float64 {
+ cache := f.s.warm
+ if !warm {
+ f.s.warm = nil
+ }
+ defer func() { f.s.warm = cache }()
+ var times []float64
+ for k := from; k < from+30; k++ {
+ start := time.Now()
+ f.mustPost(f.word(k))
+ times = append(times, float64(time.Since(start).Microseconds()))
+ }
+ sort.Float64s(times)
+ return times[len(times)/2]
+ }
+ best := func(warm bool, base int) float64 {
+ b := measure(warm, base)
+ for r := 1; r < 3; r++ {
+ b = min(b, measure(warm, base+r*100))
+ }
+ return b
+ }
+ cold := best(false, 1000)
+ warm := best(true, 2000)
+ t.Logf("median POST: replay %.0f µs, warm %.0f µs", cold, warm)
+ if warm >= cold {
+ t.Fatalf("a warm POST (%.0f µs) is not faster than a replay (%.0f µs)", warm, cold)
+ }
+}