oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3// Warm handles (warm.go; the live-push spec's §3.5 and §9.1). Each test
4// names the rule it holds.
5
6import (
7 "bytes"
8 "context"
9 "errors"
10 "fmt"
11 "log/slog"
12 "math/rand"
13 "net/http/httptest"
14 "sort"
15 "strings"
16 "sync"
17 "sync/atomic"
18 "testing"
19 "time"
20
21 "amadan.net/oficina/home/roster"
22 "github.com/carlosframework/docs/internal/core"
23 "gorm.io/gorm"
24)
25
26type warmFixture struct {
27 t *testing.T
28 app *App
29 s *Store
30 owner int64
31 actor Actor
32 doc *Document
33 ctx context.Context
34}
35
36func newWarmFixture(t *testing.T) *warmFixture {
37 t.Helper()
38 app, err := NewForTestWith(t, Config{WarmHandle: true})
39 if err != nil {
40 t.Fatalf("NewForTestWith: %v", err)
41 }
42 ctx := context.Background()
43 owner := app.TestPerson(t, "owner@example.com")
44 doc, err := app.Store().Create(ctx, owner, "Warm")
45 if err != nil {
46 t.Fatalf("Create: %v", err)
47 }
48 return &warmFixture{t: t, app: app, s: app.store, owner: owner, actor: localActor(owner, "owner@example.com"), doc: doc, ctx: ctx}
49}
50
51// word returns a valid update that adds one paragraph, "word<k>".
52func (f *warmFixture) word(k int) []byte {
53 f.t.Helper()
54 u, err := f.app.core.InitialUpdate(f.ctx, f.doc.GUID, uint64(100000+k), []core.InitialBlock{{Text: fmt.Sprintf("word%d", k)}})
55 if err != nil {
56 f.t.Fatalf("InitialUpdate: %v", err)
57 }
58 return u
59}
60
61func (f *warmFixture) post(update []byte) (int64, error) {
62 return f.s.ApplyUpdate(f.ctx, f.doc, f.actor, update)
63}
64
65func (f *warmFixture) mustPost(update []byte) int64 {
66 f.t.Helper()
67 seq, err := f.post(update)
68 if err != nil {
69 f.t.Fatalf("ApplyUpdate: %v", err)
70 }
71 return seq
72}
73
74// entry is the cache's entry for the fixture's document, or nil.
75func (f *warmFixture) entry() *warmEntry {
76 f.s.warm.mu.Lock()
77 defer f.s.warm.mu.Unlock()
78 return f.s.warm.entries[f.doc.ID]
79}
80
81func (f *warmFixture) warmText() (string, bool) {
82 f.t.Helper()
83 e := f.entry()
84 if e == nil || e.h == nil {
85 return "", false
86 }
87 text, err := e.h.Text(f.ctx)
88 if err != nil {
89 f.t.Fatalf("warm Text: %v", err)
90 }
91 return text, true
92}
93
94// rowsText replays the log's rows up to seq (all when seq < 0) into a fresh
95// handle, with no snapshot: the ground truth.
96func (f *warmFixture) rowsText(upto int64) string {
97 f.t.Helper()
98 q := f.s.db.WithContext(f.ctx).Where("doc_id = ?", f.doc.ID)
99 if upto >= 0 {
100 q = q.Where("seq <= ?", upto)
101 }
102 var rows []DocUpdate
103 if err := q.Order("seq ASC").Find(&rows).Error; err != nil {
104 f.t.Fatal(err)
105 }
106 h, err := f.s.core.NewDoc(f.ctx, f.doc.GUID, f.doc.ClientID)
107 if err != nil {
108 f.t.Fatal(err)
109 }
110 defer h.Close(f.ctx)
111 for i := range rows {
112 if err := f.s.openContentUpdate(f.doc.GUID, &rows[i]); err != nil {
113 f.t.Fatal(err)
114 }
115 if i > 0 && i%1000 == 0 {
116 // Past a few thousand rows a handle would refuse more; rebuild
117 // from its own snapshot as replay does.
118 state, err := h.Snapshot(f.ctx)
119 if err != nil {
120 f.t.Fatal(err)
121 }
122 h.Close(f.ctx)
123 if h, err = f.s.core.NewDoc(f.ctx, f.doc.GUID, f.doc.ClientID); err != nil {
124 f.t.Fatal(err)
125 }
126 if err := h.Apply(f.ctx, state); err != nil {
127 f.t.Fatal(err)
128 }
129 }
130 if err := h.Apply(f.ctx, rows[i].UpdateBin); err != nil {
131 f.t.Fatalf("raw replay of row %d: %v", rows[i].Seq, err)
132 }
133 }
134 text, err := h.Text(f.ctx)
135 if err != nil {
136 f.t.Fatal(err)
137 }
138 return text
139}
140
141// coldText is what an ordinary replay (snapshot plus tail) gives.
142func (f *warmFixture) coldText() string {
143 f.t.Helper()
144 h, _, _, err := f.s.replay(f.ctx, f.doc)
145 if err != nil {
146 f.t.Fatal(err)
147 }
148 defer h.Close(f.ctx)
149 text, err := h.Text(f.ctx)
150 if err != nil {
151 f.t.Fatal(err)
152 }
153 return text
154}
155
156func sortedWords(text string) string {
157 words := strings.Fields(text)
158 sort.Strings(words)
159 return strings.Join(words, " ")
160}
161
162// Rule 4, finding 1 of the review: a warm handle must never reach
163// core.MaxRetainedUpdates, where Apply refuses and the web's save queue
164// would drop the batch. 4,200 POSTs to one document, none refused.
165func TestWarmHandleOutlivesMaxRetainedUpdates(t *testing.T) {
166 if testing.Short() {
167 t.Skip("4,200 POSTs")
168 }
169 f := newWarmFixture(t)
170 update := f.word(1) // the same bytes every time: Yjs integrates a repeat as nothing
171 most := 0
172 const n = core.MaxRetainedUpdates + 104
173 for i := 0; i < n; i++ {
174 if _, err := f.post(update); err != nil {
175 t.Fatalf("POST %d of %d refused: %v", i+1, n, err)
176 }
177 if e := f.entry(); e != nil && e.h != nil && e.h.RetainedUpdates() > most {
178 most = e.h.RetainedUpdates()
179 }
180 }
181 if most > snapshotCadence+2 {
182 t.Errorf("a warm handle retained %d updates; re-seeding should keep it near %d", most, snapshotCadence)
183 }
184 snap, err := f.s.newestSnapshot(f.ctx, f.doc.ID)
185 if err != nil || snap == nil || snap.Seq < n-snapshotCadence-1 {
186 t.Errorf("newest snapshot %+v after %d POSTs: re-seeding should keep one within %d rows", snap, n, snapshotCadence)
187 }
188}
189
190// Rule 4's order: snapshot from the warm state at the handle's seq (before
191// this POST's update), Apply, commit, drop; the next POST replays.
192func TestWarmHandleReseedsAtTheSnapshotCadence(t *testing.T) {
193 f := newWarmFixture(t)
194 for k := 1; k <= snapshotCadence; k++ {
195 f.mustPost(f.word(k))
196 }
197 if e := f.entry(); e == nil || e.h == nil || e.seq != snapshotCadence {
198 t.Fatalf("after %d POSTs the handle should be warm at seq %d", snapshotCadence, snapshotCadence)
199 }
200 seq := f.mustPost(f.word(snapshotCadence + 1))
201 snap, err := f.s.newestSnapshot(f.ctx, f.doc.ID)
202 if err != nil || snap == nil {
203 t.Fatalf("no snapshot after the cadence: %v", err)
204 }
205 if snap.Seq != snapshotCadence {
206 t.Errorf("snapshot at seq %d, want %d (the state before POST %d)", snap.Seq, snapshotCadence, seq)
207 }
208 if e := f.entry(); e != nil && e.h != nil {
209 t.Error("the handle should be dropped after the re-seeding POST")
210 }
211 f.mustPost(f.word(snapshotCadence + 2))
212 e := f.entry()
213 if e == nil || e.h == nil || e.snap != snapshotCadence || e.seq != snapshotCadence+2 {
214 t.Fatalf("the next POST should replay from the snapshot: %+v", e)
215 }
216 if got, _ := f.warmText(); sortedWords(got) != sortedWords(f.rowsText(-1)) {
217 t.Error("the re-seeded handle differs from a replay of the log")
218 }
219}
220
221// Rule 3, finding 2 of the review: a writer revoked between the warm Apply
222// and the commit. The POST fails, the handle is dropped, and nothing the
223// refused update wrote survives into the next snapshot.
224func TestWarmHandleIsDroppedWhenTheWriterIsRevokedBeforeCommit(t *testing.T) {
225 f := newWarmFixture(t)
226 writer := f.app.TestPerson(t, "writer@example.com")
227 if err := f.s.Grant(f.ctx, f.owner, f.doc.Sqid, "writer@example.com", RoleWriter); err != nil {
228 t.Fatalf("Grant: %v", err)
229 }
230 writerActor := localActor(writer, "writer@example.com")
231 if _, err := f.s.ApplyUpdate(f.ctx, f.doc, writerActor, f.word(1)); err != nil {
232 t.Fatalf("writer's first POST: %v", err)
233 }
234 if _, ok := f.warmText(); !ok {
235 t.Fatal("the handle should be warm")
236 }
237 f.s.warmBeforeCommit = func(ctx context.Context, tx *gorm.DB, doc *Document) error {
238 // Inside the transaction: the grant goes, so the transaction's own
239 // closing permission check refuses.
240 return tx.Where("doc_id = ? AND subject = ?", doc.ID, "writer@example.com").Delete(&Grant{}).Error
241 }
242 if _, err := f.s.ApplyUpdate(f.ctx, f.doc, writerActor, f.word(666)); !errors.Is(err, ErrNotWritable) {
243 t.Fatalf("POST after revocation: %v, want ErrNotWritable", err)
244 }
245 f.s.warmBeforeCommit = nil
246 if _, ok := f.warmText(); ok {
247 t.Fatal("a handle that applied an uncommitted update must be dropped")
248 }
249 // Enough owner POSTs to cross the cadence, so the next snapshot is
250 // written from a handle rebuilt after the failure.
251 for k := 2; k <= snapshotCadence+3; k++ {
252 f.mustPost(f.word(k))
253 }
254 snap, err := f.s.newestSnapshot(f.ctx, f.doc.ID)
255 if err != nil || snap == nil {
256 t.Fatalf("no snapshot: %v", err)
257 }
258 h, err := f.s.core.NewDoc(f.ctx, f.doc.GUID, f.doc.ClientID)
259 if err != nil {
260 t.Fatal(err)
261 }
262 defer h.Close(f.ctx)
263 if err := h.Apply(f.ctx, snap.State); err != nil {
264 t.Fatal(err)
265 }
266 snapText, _ := h.Text(f.ctx)
267 if strings.Contains(snapText, "word666") {
268 t.Fatal("the refused update reached a snapshot")
269 }
270 if sortedWords(snapText) != sortedWords(f.rowsText(snap.Seq)) {
271 t.Error("the snapshot differs from a replay of the rows it covers")
272 }
273}
274
275// Rule 2: anything but a clean rejection from the warm Apply (a full log,
276// a trap, a recovered instance) redoes the POST cold; the POST succeeds.
277func TestWarmHandleFallsBackToAColdReplay(t *testing.T) {
278 for _, injected := range []error{core.ErrUpdateLogFull, errors.New("trap: unreachable")} {
279 t.Run(injected.Error(), func(t *testing.T) {
280 f := newWarmFixture(t)
281 f.mustPost(f.word(1))
282 f.s.warmApplyHook = func(*core.Handle) error { return injected }
283 seq, err := f.post(f.word(2))
284 f.s.warmApplyHook = nil
285 if err != nil || seq != 2 {
286 t.Fatalf("POST = %d, %v; the cold path should have taken it", seq, err)
287 }
288 if _, ok := f.warmText(); ok {
289 t.Error("the failed handle should be gone")
290 }
291 f.mustPost(f.word(3))
292 if got, ok := f.warmText(); !ok || sortedWords(got) != sortedWords(f.rowsText(-1)) {
293 t.Error("the next POST should warm a fresh handle equal to the log")
294 }
295 })
296 }
297}
298
299// Rule 2, review #174 finding 1: a rejection is not clean. An update whose
300// first struct integrates and whose second is refused (ERR_APPLY) answers
301// 400 with the first struct already in the handle's store; the handle must
302// go, or the next snapshot persists content no row holds. Garbage the
303// decoder refuses drops it too (one replay on the next POST).
304func TestWarmHandleIsDroppedWhenAnUpdateIsRejected(t *testing.T) {
305 for _, c := range []struct {
306 name string
307 update []byte
308 }{{"half-applied", halfApplyingUpdate()}, {"undecodable", []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}} {
309 t.Run(c.name, func(t *testing.T) {
310 f := newWarmFixture(t)
311 f.mustPost(f.word(1))
312 _, err := f.post(c.update)
313 var rejection *updateRejection
314 if !errors.As(err, &rejection) {
315 t.Fatalf("%s: %v, want an update rejection", c.name, err)
316 }
317 if _, ok := f.warmText(); ok {
318 t.Fatal("a rejected update left the warm handle")
319 }
320 for k := 2; k <= snapshotCadence+2; k++ {
321 f.mustPost(f.word(k))
322 }
323 snap, err := f.s.newestSnapshot(f.ctx, f.doc.ID)
324 if err != nil || snap == nil {
325 t.Fatalf("no snapshot: %v", err)
326 }
327 if bytes.Contains(snap.State, []byte("INJECTED")) {
328 t.Fatal("the refused update's first struct reached a snapshot")
329 }
330 if e := f.entry(); e != nil && e.h != nil {
331 state, _ := e.h.Snapshot(f.ctx)
332 if bytes.Contains(state, []byte("INJECTED")) {
333 t.Fatal("the warm handle holds the refused update's first struct")
334 }
335 }
336 })
337 }
338}
339
340// Review finding 2: a panic between Apply and commit (net/http recovers it
341// and the process lives) must not leave the applied, uncommitted handle.
342func TestWarmHandleIsDroppedAfterAPanicBeforeCommit(t *testing.T) {
343 f := newWarmFixture(t)
344 f.mustPost(f.word(1))
345 f.s.warmBeforeCommit = func(context.Context, *gorm.DB, *Document) error { panic("injected") }
346 func() {
347 defer func() { _ = recover() }()
348 f.post(f.word(2))
349 }()
350 f.s.warmBeforeCommit = nil
351 if _, ok := f.warmText(); ok {
352 t.Fatal("the handle that applied word2 survived the panic")
353 }
354 f.mustPost(f.word(3))
355 got, ok := f.warmText()
356 if !ok || strings.Contains(got, "word2") || sortedWords(got) != sortedWords(f.rowsText(-1)) {
357 t.Fatalf("after the panic the warm handle differs from the log: %q", got)
358 }
359}
360
361// Review finding 3: an entry dropped between acquire's lookup and its lock
362// (a revoke, a delete, a cap eviction) is no longer the cache's. The POST
363// that holds it must close its handle on release, not keep an orphan that
364// nothing would ever sweep, cap or drop.
365func TestWarmHandleOrphanedBetweenLookupAndLockIsClosed(t *testing.T) {
366 f := newWarmFixture(t)
367 var orphan *warmEntry
368 f.s.warm.afterLookup = func(e *warmEntry) {
369 f.s.warm.afterLookup = nil
370 orphan = e
371 f.s.warm.drop(f.ctx, f.doc.ID)
372 }
373 f.mustPost(f.word(1))
374 if orphan == nil {
375 t.Fatal("the seam did not run")
376 }
377 if orphan.h != nil {
378 orphan.h.Close(f.ctx)
379 t.Fatal("an entry dropped between lookup and lock kept an open handle")
380 }
381 if n, _ := f.s.warm.stats(); n != 0 {
382 t.Fatalf("%d handles", n)
383 }
384}
385
386// Review finding 6: an entry left without a handle (a failed commit, a
387// re-seed) leaves the map, so it cannot push a real handle out of the
388// count cap.
389func TestWarmEntriesWithoutAHandleDoNotCount(t *testing.T) {
390 f := newWarmFixture(t)
391 other, err := f.s.Create(f.ctx, f.owner, "Other")
392 if err != nil {
393 t.Fatal(err)
394 }
395 f.s.warm.maxHandles = 1
396 f.mustPost(f.word(1))
397 f.s.warmBeforeCommit = func(context.Context, *gorm.DB, *Document) error { return errors.New("injected") }
398 u, _ := f.app.core.InitialUpdate(f.ctx, other.GUID, 777, []core.InitialBlock{{Text: "other"}})
399 if _, err := f.s.ApplyUpdate(f.ctx, other, f.actor, u); err == nil {
400 t.Fatal("the injected failure did not fail the POST")
401 }
402 f.s.warmBeforeCommit = nil
403 if _, ok := f.warmText(); !ok {
404 t.Fatal("an empty entry evicted the only real handle")
405 }
406 f.s.warm.mu.Lock()
407 n := len(f.s.warm.entries)
408 f.s.warm.mu.Unlock()
409 if n != 1 {
410 t.Fatalf("%d entries, want 1", n)
411 }
412}
413
414// Review finding 7: a request cancelled mid-Apply drops the handle quietly:
415// no rule 2 warning (the canary watches it) and no cold retry.
416func TestWarmHandleCancelledMidApplyIsQuiet(t *testing.T) {
417 f := newWarmFixture(t)
418 f.mustPost(f.word(1))
419 var logs bytes.Buffer
420 f.s.logger = slog.New(slog.NewTextHandler(&logs, nil))
421 ctx, cancel := context.WithCancel(f.ctx)
422 replays := 0
423 f.s.warmApplyHook = func(*core.Handle) error { cancel(); return errors.New("core: deadline: context canceled") }
424 f.s.warmBeforeCommit = func(context.Context, *gorm.DB, *Document) error { replays++; return nil }
425 _, err := f.s.ApplyUpdate(ctx, f.doc, f.actor, f.word(2))
426 f.s.warmApplyHook, f.s.warmBeforeCommit = nil, nil
427 if !errors.Is(err, context.Canceled) {
428 t.Fatalf("err = %v, want context.Canceled", err)
429 }
430 if replays != 0 {
431 t.Error("a cancelled request was retried cold")
432 }
433 if strings.Contains(logs.String(), "warm handle dropped") {
434 t.Errorf("a cancelled request logged the rule 2 warning: %s", logs.String())
435 }
436}
437
438// concurrentPOSTs runs goroutines × per POSTs, goroutine g posting to
439// docs[(g+i)%len(docs)], each a fresh paragraph from its own Yjs client.
440func (f *warmFixture) concurrentPOSTs(docs []*Document, goroutines, per int, next *atomic.Int64) {
441 f.t.Helper()
442 var wg sync.WaitGroup
443 errs := make(chan error, goroutines)
444 for g := 0; g < goroutines; g++ {
445 wg.Add(1)
446 go func(g int) {
447 defer wg.Done()
448 for i := 0; i < per; i++ {
449 d := docs[(g+i)%len(docs)]
450 k := next.Add(1)
451 u, err := f.app.core.InitialUpdate(f.ctx, d.GUID, uint64(300000+k), []core.InitialBlock{{Text: fmt.Sprintf("c%d", k)}})
452 if err == nil {
453 _, err = f.s.ApplyUpdate(f.ctx, d, f.actor, u)
454 }
455 if err != nil {
456 errs <- fmt.Errorf("goroutine %d POST %d: %w", g, i, err)
457 return
458 }
459 }
460 }(g)
461 }
462 wg.Wait()
463 close(errs)
464 for err := range errs {
465 f.t.Fatal(err)
466 }
467}
468
469// Review #174, delta finding 1: POSTs queued on one document's entry must
470// share its handle. Deleting a handle-less entry while others waited on it
471// made each waiter replay and each new POST start a second entry that went
472// stale: 501 replays and 431 stale drops for 8 × 100 POSTs, against a
473// handful with the reference count. No drops, no sweeps: only contention.
474func TestWarmHandleContentionDoesNotReplay(t *testing.T) {
475 f := newWarmFixture(t)
476 per := 100
477 if testing.Short() {
478 per = 40
479 }
480 var next atomic.Int64
481 f.concurrentPOSTs([]*Document{f.doc}, 8, per, &next)
482 c := &f.s.warm.counts
483 replays, stale, reseeds, hits := c.replays.Load(), c.stale.Load(), c.reseeds.Load(), c.hits.Load()
484 t.Logf("%d POSTs: %d replays, %d stale, %d re-seeds, %d warm hits", 8*per, replays, stale, reseeds, hits)
485 // One replay to start, one after each re-seed; a little slack.
486 if replays > reseeds+3 || stale > 2 {
487 t.Fatalf("contention replays: %d replays, %d stale for %d POSTs (%d re-seeds)", replays, stale, 8*per, reseeds)
488 }
489 if sortedWords(f.coldText()) != sortedWords(f.rowsText(-1)) {
490 t.Fatal("a cold replay differs from the log")
491 }
492}
493
494// Rule 1 and the cache's locking, run under -race in the gate (review #174,
495// delta finding 2: the earlier version never reached the warm path under
496// -short). Pre-filled so a re-seed runs under the detector; then three
497// phases, each by 8 goroutines: no churn (warm hits must dominate), drops
498// and sweeps on a clock past warmIdle, and a one-handle cap with two
499// documents (concurrent cap eviction). At the end the log, a cold replay
500// and any warm handle agree.
501func TestWarmHandlesUnderConcurrentPOSTs(t *testing.T) {
502 per := 60
503 if testing.Short() {
504 per = 25
505 }
506 f := newWarmFixture(t)
507 second, err := f.s.Create(f.ctx, f.owner, "Second")
508 if err != nil {
509 t.Fatal(err)
510 }
511 docs := []*Document{f.doc, second}
512 var next atomic.Int64
513 for k := 0; k < snapshotCadence-40; k++ {
514 f.mustPost(f.word(int(next.Add(1)) + 900000))
515 }
516 c := &f.s.warm.counts
517
518 // No churn: the warm path, and a re-seed, under the detector.
519 hits0, reseeds0 := c.hits.Load(), c.reseeds.Load()
520 f.concurrentPOSTs(docs[:1], 8, per, &next)
521 if hits := c.hits.Load() - hits0; hits < int64(8*per/2) {
522 t.Fatalf("no-churn phase: %d warm hits in %d POSTs", hits, 8*per)
523 }
524 if c.reseeds.Load() == reseeds0 {
525 t.Fatal("no-churn phase: no re-seed ran")
526 }
527
528 // Churn: drops and sweeps every 20 ms on a clock that moves past warmIdle.
529 var clockMu sync.Mutex
530 clock := time.Now()
531 f.s.warm.mu.Lock()
532 f.s.warm.now = func() time.Time { clockMu.Lock(); defer clockMu.Unlock(); return clock }
533 f.s.warm.mu.Unlock()
534 stop := make(chan struct{})
535 var churn sync.WaitGroup
536 churn.Add(1)
537 go func() {
538 defer churn.Done()
539 for i := 0; ; i++ {
540 select {
541 case <-stop:
542 return
543 case <-time.After(20 * time.Millisecond):
544 }
545 switch i % 3 {
546 case 0:
547 f.s.warm.drop(f.ctx, docs[i%2].ID)
548 case 1:
549 clockMu.Lock()
550 clock = clock.Add(warmIdle + time.Second)
551 clockMu.Unlock()
552 f.s.warm.sweep(f.ctx)
553 default:
554 f.s.warm.stats()
555 }
556 }
557 }()
558 f.concurrentPOSTs(docs, 8, per, &next)
559 close(stop)
560 churn.Wait()
561
562 // A one-handle cap with two documents: eviction under concurrency.
563 f.s.warm.mu.Lock()
564 f.s.warm.maxHandles = 1
565 f.s.warm.mu.Unlock()
566 f.concurrentPOSTs(docs, 8, per, &next)
567 if n, _ := f.s.warm.stats(); n > 1 {
568 t.Fatalf("%d handles kept under a cap of 1", n)
569 }
570
571 for _, d := range docs {
572 g := &warmFixture{t: t, app: f.app, s: f.s, owner: f.owner, actor: f.actor, doc: d, ctx: f.ctx}
573 truth := sortedWords(g.rowsText(-1))
574 if sortedWords(g.coldText()) != truth {
575 t.Fatalf("document %d: a cold replay differs from the log", d.ID)
576 }
577 if warm, ok := g.warmText(); ok && sortedWords(warm) != truth {
578 t.Fatalf("document %d: the warm handle differs from the log", d.ID)
579 }
580 }
581 t.Logf("replays %d, hits %d, stale %d, re-seeds %d", c.replays.Load(), c.hits.Load(), c.stale.Load(), c.reseeds.Load())
582}
583
584// Team mode with sealed rows, as production stores them (review finding 4):
585// a linked member's POSTs through the router keep a warm handle, cross the
586// snapshot cadence through the team branch, and agree with the log; a
587// member removed from the roster is refused before any handle is touched.
588func TestWarmHandleInTeamModeWithSealedRows(t *testing.T) {
589 f := newTeamRouterFixtureWith(t, false, true)
590 if f.app.store.warm == nil {
591 t.Fatal("the team fixture did not turn warm handles on")
592 }
593 var encoding int
594 f.app.store.db.Raw("SELECT content_encoding FROM doc_updates LIMIT 1").Scan(&encoding)
595 if encoding != 1 {
596 t.Fatalf("rows are not sealed (content_encoding %d)", encoding)
597 }
598 b := f.browser()
599 b.localSignin(t, "alice@example.com")
600 b.linkProof(t, teamSubject('a'), "alice@example.com")
601 routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL("/"))
602 g := &warmFixture{t: t, app: f.app, s: f.app.store, doc: f.own, ctx: context.Background()}
603 for k := 1; k <= snapshotCadence+3; k++ {
604 if code := b.update(f.own, g.word(k)); code != 204 {
605 t.Fatalf("team POST %d: %d", k, code)
606 }
607 }
608 snap, err := g.s.newestSnapshot(g.ctx, f.own.ID)
609 if err != nil || snap == nil || snap.Seq < snapshotCadence {
610 t.Fatalf("no team-mode snapshot at the cadence: %+v %v", snap, err)
611 }
612 warm, ok := g.warmText()
613 if !ok || sortedWords(warm) != sortedWords(g.rowsText(-1)) || sortedWords(g.coldText()) != sortedWords(g.rowsText(-1)) {
614 t.Fatal("in team mode the warm handle, a cold replay and the log disagree")
615 }
616 f.clock.step(roster.RetryAfter)
617 f.directory.change([]roster.MemberEntry{{Subject: teamSubject('b'), Role: "member"}}, false)
618 if e := f.app.store.team.cache.Refresh(t.Context()); e != nil {
619 t.Fatal(e)
620 }
621 if code := b.update(f.own, g.word(9999)); code != 404 {
622 t.Fatalf("a removed member's POST answered %d", code)
623 }
624 if strings.Contains(g.rowsText(-1), "word9999") {
625 t.Fatal("a removed member's update reached the log")
626 }
627}
628
629// Rules 2–3 and 8 together: random POSTs, failed commits, injected Apply
630// failures, rejections (undecodable and half-applying), drops and commits by another Store on the same
631// database (a second process, or the agent path). After every step the
632// log holds exactly the committed words, and a warm handle, when there is
633// one after a POST of its own, equals a replay of the log.
634func TestWarmHandleMatchesAColdReplayUnderFailures(t *testing.T) {
635 seeds := 8
636 if testing.Short() {
637 seeds = 2
638 }
639 for seed := 1; seed <= seeds; seed++ {
640 t.Run(fmt.Sprint("seed", seed), func(t *testing.T) {
641 f := newWarmFixture(t)
642 other := NewStore(f.s.db, f.s.core, false, f.s.logger) // another process: no shared cache
643 rng := rand.New(rand.NewSource(int64(seed)))
644 committed := map[string]bool{}
645 refused := map[string]bool{}
646 for step := 0; step < 60; step++ {
647 k := seed*1000 + step
648 word := fmt.Sprintf("word%d", k)
649 warmAfterPost := false
650 switch op := rng.Intn(11); {
651 case op == 10:
652 if _, err := f.post(halfApplyingUpdate()); err == nil {
653 t.Fatal("a half-applying update was accepted")
654 }
655 case op < 4:
656 f.mustPost(f.word(k))
657 committed[word] = true
658 warmAfterPost = true
659 case op == 4:
660 f.s.warmBeforeCommit = func(context.Context, *gorm.DB, *Document) error { return errors.New("injected: commit failed") }
661 if _, err := f.post(f.word(k)); err == nil {
662 t.Fatal("a failed commit reported success")
663 }
664 f.s.warmBeforeCommit = nil
665 refused[word] = true
666 case op == 5:
667 f.s.warmApplyHook = func(*core.Handle) error { return errors.New("injected: trap") }
668 f.mustPost(f.word(k))
669 f.s.warmApplyHook = nil
670 committed[word] = true
671 case op == 6:
672 if _, err := other.ApplyUpdate(f.ctx, f.doc, f.actor, f.word(k)); err != nil {
673 t.Fatalf("other store: %v", err)
674 }
675 committed[word] = true
676 case op == 7:
677 f.s.warm.drop(f.ctx, f.doc.ID)
678 case op == 8:
679 if _, err := f.post([]byte{0xff, 0xff, 0xff}); err == nil {
680 t.Fatal("garbage accepted")
681 }
682 default:
683 ctx, cancel := context.WithCancel(f.ctx)
684 f.s.warmBeforeCommit = func(context.Context, *gorm.DB, *Document) error { cancel(); return ctx.Err() }
685 if _, err := f.s.ApplyUpdate(ctx, f.doc, f.actor, f.word(k)); err == nil {
686 t.Fatal("a cancelled commit reported success")
687 }
688 f.s.warmBeforeCommit = nil
689 refused[word] = true
690 }
691 truth := f.rowsText(-1)
692 for w := range committed {
693 if !strings.Contains(truth, w+" ") && !strings.HasSuffix(truth, w) && !strings.Contains(truth, w+"\n") {
694 t.Fatalf("step %d: committed %s missing from the log", step, w)
695 }
696 }
697 for w := range refused {
698 if strings.Contains(truth, w) {
699 t.Fatalf("step %d: refused %s is in the log", step, w)
700 }
701 }
702 if e := f.entry(); e != nil && e.h != nil {
703 if state, _ := e.h.Snapshot(f.ctx); bytes.Contains(state, []byte("INJECTED")) {
704 t.Fatalf("step %d: the warm handle holds a refused update", step)
705 }
706 }
707 if warmAfterPost {
708 if got, ok := f.warmText(); ok && sortedWords(got) != sortedWords(truth) {
709 t.Fatalf("step %d: the warm handle differs from the log", step)
710 }
711 }
712 }
713 if sortedWords(f.coldText()) != sortedWords(f.rowsText(-1)) {
714 t.Fatal("a cold replay differs from the log")
715 }
716 })
717 }
718}
719
720// Rule 5: least recently used out first, by count and by bytes, and one
721// handle larger than the byte cap is never kept.
722func TestWarmHandlesAreBoundedByCountAndBytes(t *testing.T) {
723 f := newWarmFixture(t)
724 docs := []*Document{f.doc}
725 for i := 0; i < 2; i++ {
726 d, err := f.s.Create(f.ctx, f.owner, fmt.Sprint("Warm ", i))
727 if err != nil {
728 t.Fatal(err)
729 }
730 docs = append(docs, d)
731 }
732 post := func(d *Document, k int) {
733 u, err := f.app.core.InitialUpdate(f.ctx, d.GUID, uint64(200000+k), []core.InitialBlock{{Text: fmt.Sprint("x", k)}})
734 if err != nil {
735 t.Fatal(err)
736 }
737 if _, err := f.s.ApplyUpdate(f.ctx, d, f.actor, u); err != nil {
738 t.Fatal(err)
739 }
740 }
741 kept := func(d *Document) bool {
742 f.s.warm.mu.Lock()
743 defer f.s.warm.mu.Unlock()
744 e := f.s.warm.entries[d.ID]
745 return e != nil && e.kept
746 }
747
748 post(docs[0], 1)
749 _, one := f.s.warm.stats()
750 if one == 0 {
751 t.Fatal("no bytes counted for a warm handle")
752 }
753
754 f.s.warm.maxHandles = 2
755 post(docs[1], 2)
756 post(docs[2], 3)
757 if n, _ := f.s.warm.stats(); n != 2 || kept(docs[0]) {
758 t.Errorf("count cap 2: %d handles, oldest kept %v", n, kept(docs[0]))
759 }
760
761 f.s.warm.maxHandles = warmMaxHandles
762 f.s.warm.maxBytes = one*2 + one/2
763 post(docs[0], 4)
764 if n, b := f.s.warm.stats(); n != 2 || b > f.s.warm.maxBytes || kept(docs[1]) {
765 t.Errorf("byte cap for two: %d handles, %d bytes, oldest kept %v", n, b, kept(docs[1]))
766 }
767
768 f.s.warm.maxBytes = one / 2
769 post(docs[2], 5)
770 if kept(docs[2]) {
771 t.Error("a handle larger than the byte cap was kept")
772 }
773}
774
775// Rule 6: delete, grant, revoke and visibility drop the document's handle;
776// drain drops every handle and keeps no more.
777func TestWarmHandleIsDroppedWhenAccessChanges(t *testing.T) {
778 cases := []struct {
779 name string
780 change func(f *warmFixture) error
781 }{
782 {"grant", func(f *warmFixture) error {
783 return f.s.Grant(f.ctx, f.owner, f.doc.Sqid, "reader@example.com", RoleReader)
784 }},
785 {"revoke", func(f *warmFixture) error {
786 return f.s.Revoke(f.ctx, f.owner, f.doc.Sqid, "reader@example.com")
787 }},
788 {"visibility", func(f *warmFixture) error {
789 return f.s.SetVisibility(f.ctx, f.owner, f.doc.Sqid, VisibilityPrivate)
790 }},
791 {"delete", func(f *warmFixture) error { return f.s.Delete(f.ctx, f.owner, f.doc.Sqid) }},
792 }
793 for _, c := range cases {
794 t.Run(c.name, func(t *testing.T) {
795 f := newWarmFixture(t)
796 f.mustPost(f.word(1))
797 if _, ok := f.warmText(); !ok {
798 t.Fatal("not warm")
799 }
800 if err := c.change(f); err != nil {
801 t.Fatalf("%s: %v", c.name, err)
802 }
803 if _, ok := f.warmText(); ok {
804 t.Errorf("%s left the warm handle", c.name)
805 }
806 })
807 }
808 t.Run("drain", func(t *testing.T) {
809 f := newWarmFixture(t)
810 f.mustPost(f.word(1))
811 f.app.Drain()
812 if n, _ := f.s.warm.stats(); n != 0 {
813 t.Fatalf("%d handles after drain", n)
814 }
815 f.mustPost(f.word(2))
816 if n, _ := f.s.warm.stats(); n != 0 {
817 t.Errorf("a drained cache kept a handle")
818 }
819 })
820}
821
822// Rule 7: an open stream's heartbeat sweeps handles idle for warmIdle,
823// with no POST to do it.
824func TestWarmHandleIsSweptByTheStreamHeartbeat(t *testing.T) {
825 f := newWarmFixture(t)
826 f.mustPost(f.word(1))
827 clock := time.Now()
828 f.s.warm.mu.Lock()
829 f.s.warm.now = func() time.Time { return clock }
830 f.s.warm.mu.Unlock()
831 clock = clock.Add(warmIdle + time.Second)
832
833 streamDurations(t, f.app, 50*time.Millisecond, 5*time.Second)
834 srv := httptest.NewServer(f.app.Handler())
835 defer srv.Close()
836 res, body := openStream(t, srv, f.app, "owner@example.com", "/d/"+f.doc.Sqid+"/stream")
837 defer res.Body.Close()
838 nextEvent(t, body, 2*time.Second) // the connect event
839 if name, _ := nextEvent(t, body, 2*time.Second); name != "ping" {
840 t.Fatalf("want a heartbeat, got %q", name)
841 }
842 if _, ok := f.warmText(); ok {
843 t.Error("an idle handle survived the heartbeat")
844 }
845}
846
847// The agent paths' Store copies run inside the caller's transaction and
848// must never use (or advance) a warm handle.
849func TestAStoreBoundToATransactionHasNoWarmHandles(t *testing.T) {
850 f := newWarmFixture(t)
851 if f.s.boundTo(f.s.db).warm != nil {
852 t.Fatal("boundTo kept the warm cache")
853 }
854 if f.s.warm == nil {
855 t.Fatal("boundTo changed the original")
856 }
857}
858
859// Off, nothing is kept: every POST replays, as before slice 1a.
860func TestWarmHandleSwitchOff(t *testing.T) {
861 app, err := NewForTest(t)
862 if err != nil {
863 t.Fatal(err)
864 }
865 if app.store.warm != nil {
866 t.Fatal("warm handles are on by default; the spec keeps them off until slice 1a is proven")
867 }
868 for _, c := range []struct {
869 in string
870 want bool
871 bad bool
872 }{{"", false, false}, {"off", false, false}, {"on", true, false}, {"1", true, false}, {"yes", false, true}} {
873 got, err := ParseWarmHandle(c.in)
874 if got != c.want || (err != nil) != c.bad {
875 t.Errorf("ParseWarmHandle(%q) = %v, %v", c.in, got, err)
876 }
877 }
878}
879
880// The slice's relative timing gate (the spec's §9.2, applied to 1a): on a
881// ~20-page document, in the same process and the same run, a POST through
882// a warm handle takes less time than one that replays. Best of three
883// medians each, so a loaded machine slows both sides alike; no absolute
884// threshold. It fails, never skips.
885func TestWarmHandleIsFasterThanAReplay(t *testing.T) {
886 f := newWarmFixture(t)
887 blocks := make([]core.InitialBlock, 150)
888 para := strings.Repeat("lorem ipsum dolor sit amet consectetur ", 10) // ~400 characters
889 for i := range blocks {
890 blocks[i] = core.InitialBlock{Text: fmt.Sprint(i, " ", para)}
891 }
892 seed, err := f.app.core.InitialUpdate(f.ctx, f.doc.GUID, 99, blocks)
893 if err != nil {
894 t.Fatal(err)
895 }
896 f.mustPost(seed)
897 measure := func(warm bool, from int) float64 {
898 cache := f.s.warm
899 if !warm {
900 f.s.warm = nil
901 }
902 defer func() { f.s.warm = cache }()
903 var times []float64
904 for k := from; k < from+30; k++ {
905 start := time.Now()
906 f.mustPost(f.word(k))
907 times = append(times, float64(time.Since(start).Microseconds()))
908 }
909 sort.Float64s(times)
910 return times[len(times)/2]
911 }
912 best := func(warm bool, base int) float64 {
913 b := measure(warm, base)
914 for r := 1; r < 3; r++ {
915 b = min(b, measure(warm, base+r*100))
916 }
917 return b
918 }
919 cold := best(false, 1000)
920 warm := best(true, 2000)
921 t.Logf("median POST: replay %.0f µs, warm %.0f µs", cold, warm)
922 if warm >= cold {
923 t.Fatalf("a warm POST (%.0f µs) is not faster than a replay (%.0f µs)", warm, cold)
924 }
925}
926
927// halfApplyingUpdate is the review's case (#174, finding 1): a Yjs v1
928// update whose first struct is valid (the string "INJECTED" under a named
929// root) and whose second names that string item as its parent, which yrs
930// refuses with InvalidParent only after it has integrated the first. The
931// core answers it as a rejection (ERR_APPLY), with the first struct
932// already in the document.
933func halfApplyingUpdate() []byte {
934 const client = 4242
935 b := []byte{1, 2} // one client group, two structs
936 b = append(b, client&0x7f|0x80, client>>7)
937 b = append(b, 0) // clock 0
938 b = append(b, 0x04, 1) // struct 1: ContentString, parent is a named root
939 b = append(b, 1, 'x') // the root's name
940 b = append(b, 8) // "INJECTED", 8 characters: clocks 0-7
941 b = append(b, "INJECTED"...)
942 b = append(b, 0x04, 0) // struct 2: ContentString, parent is an item id
943 b = append(b, client&0x7f|0x80, client>>7, 0) // (client, clock 0): struct 1, not a type
944 b = append(b, 3, 'a', 'b', 'c')
945 return append(b, 0) // empty delete set
946}
947