Live push slice 1a: fix Fable's branch review (#174)
1 HIGH: any error from Apply now drops the warm handle. A rejection was not clean: yrs integrates an update's structs one at a time, so a later struct refused (InvalidParent, ERR_APPLY) left the earlier ones in the handle, and the next snapshot persisted content no row held. Reproduced with a 28-byte update (halfApplyingUpdate); core.go's comment corrected. 2 an applied-but-uncommitted flag, set before Apply and cleared after commit, closes the handle on every other way out, a panic included. 3 release closes an entry that is no longer the cache's (dropped between acquire's lookup and lock), instead of keeping an orphan. 4 tests: 8 goroutines x 150 POSTs with drops and sweeps; team mode with sealed rows (newTeamRouterFixtureWith); the gate gains a CGO_ENABLED=1 -race step on the warm and stream tests (~2.5 min). 5 rule 6's narrower scope written down (roster changes: retention up to 60 s, not access; version restore must drop the handle, noted at the updated_at invariant); spec §3.5 rules 2 and 6 and the plan updated. 6 entries without a handle leave the map, so they don't count toward the 64 cap. 7 a request cancelled mid-Apply drops the handle quietly: no rule 2 warning, no cold retry. Each new test was seen to fail with its fix undone. go test ./..., vet, gofmt and the race step pass locally.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+469
−39
.amadan/ci.d/10-gate+10 −0docs/superpowers/plans/2026-11-26-live-push.md+36 −8docs/superpowers/specs/2026-11-26-live-push-design.md+28 −6internal/core/core.go+10 −3internal/docs/store.go+2 −0internal/docs/team_router_test.go+26 −0internal/docs/warm.go+55 −10internal/docs/warm_test.go+302 −12
diff --git a/.amadan/ci.d/10-gate b/.amadan/ci.d/10-gate| index 6551a92..b3ca718 100755 |
| --- a/.amadan/ci.d/10-gate |
| +++ b/.amadan/ci.d/10-gate |
| @@ -284,6 +284,16 @@ go vet ./... |
| # nothing compiles cannot rot silently. |
| go vet -tags browser ./internal/docs/ |
| go test ./... -count=1 |
| + |
| +echo "=== go: race detector on warm handles and the stream" |
| +# Everything above builds with CGO_ENABLED=0, which is the app's own |
| +# constraint, so no other step runs the race detector. It needs cgo and a C |
| +# compiler; the runner already has one, since cargo links its host test |
| +# binaries with it. Without one, this step fails loudly rather than skipping. |
| +# Scoped to the code with its own locking: the warm-handle cache (warm.go, |
| +# the live-push spec's §3.5, including an 8-goroutine stress test) and the |
| +# stream. -short trims the 4,200-POST test, which needs no detector. |
| +CGO_ENABLED=1 go test -race -short -count=1 -run 'Warm|BoundToATransaction|Stream' ./internal/docs/ |
| test -z "$(gofmt -l .)" || { echo "gate: gofmt"; gofmt -l .; exit 1; } |
| echo "=== go: build ./... (the app, not just the packages tests import)" |
diff --git a/docs/superpowers/plans/2026-11-26-live-push.md b/docs/superpowers/plans/2026-11-26-live-push.md| index 4e7e141..accbcfb 100644 |
| --- a/docs/superpowers/plans/2026-11-26-live-push.md |
| +++ b/docs/superpowers/plans/2026-11-26-live-push.md |
| @@ -50,10 +50,18 @@ Branch `feat/live-push-1a`. Spec §3.5 rules 1–8, §8 `DOCS_WARM_HANDLE`. |
| - **Sweep:** by every POST and every stream heartbeat; no timers of its |
| own. |
| - **Drop:** on `close` (drain and app close). |
| - - **Rules:** rule 2 (clean rejection keeps the handle; anything else |
| - replays cold in the same POST), rule 3 (drop on any failure after |
| - Apply; seq advances after commit; a `MAX(seq)` mismatch drops), rule 4 |
| - (snapshot at the handle's seq, Apply, commit, drop). |
| + - **Rules:** |
| + - rule 2: any Apply error drops the handle (a rejection can be half |
| + applied, review #174 finding 1); a full log, trap or recovered |
| + instance also replays cold in the same POST; a cancelled request |
| + does neither quietly; |
| + - rule 3: an applied-but-uncommitted flag closes the handle on every |
| + way out short of a commit, a panic included; seq advances after |
| + commit; a `MAX(seq)` mismatch drops; |
| + - rule 4: snapshot at the handle's seq, Apply, commit, drop; |
| + - release closes an entry that is no longer the cache's (dropped |
| + between acquire's lookup and lock), and removes entries left without |
| + a handle from the map, so they don't count toward the cap. |
| 3. `Store.ApplyUpdate`: split into `applyCold` (unchanged behaviour) and |
| `commitUpdate` (the one transaction, returning `MAX(seq)` before the |
| insert), with `applyWarm` in front when the switch is on. |
| @@ -73,11 +81,19 @@ Branch `feat/live-push-1a`. Spec §3.5 rules 1–8, §8 `DOCS_WARM_HANDLE`. |
| - Re-seed order and the next POST's replay from the new snapshot. |
| - A writer revoked between Apply and commit: the POST fails, the handle is |
| dropped, and the next snapshot equals a raw replay of the rows it covers. |
| -- Cold fallback on `ErrUpdateLogFull` and on a trap; a clean rejection keeps |
| - the handle. |
| +- Cold fallback on `ErrUpdateLogFull` and on a trap. |
| +- A rejected update drops the handle: the review's half-applying update |
| + (`halfApplyingUpdate`) and undecodable bytes. Neither reaches a snapshot. |
| +- A panic before commit; an entry orphaned between lookup and lock; |
| + handle-less entries not counted; a cancelled request neither retried nor |
| + logged. |
| +- 8 goroutines × 150 POSTs to two documents, with drops and sweeps; log, |
| + cold replay and warm handle agree. |
| +- Team mode with sealed rows: a linked member's POSTs warm and cross the |
| + snapshot cadence through the team branch; a removed member is refused. |
| - Property test (8 seeds × 60 steps): POSTs, failed commits, cancelled |
| - contexts, injected traps, rejections, drops, and commits by another Store |
| - on the same database. The log always holds exactly the committed updates, |
| + contexts, injected traps, undecodable and half-applying rejections, drops, |
| + and commits by another Store on the same database. The log always holds exactly the committed updates, |
| and a warm handle after its own POST equals a raw replay. |
| - Count and byte caps, LRU order, one over-cap handle not kept. |
| - Drops on grant, revoke, visibility, delete and drain. |
| @@ -96,6 +112,18 @@ sealed rows, 1 and 20 pages: |
| - latency at 50 ms RTT; |
| - warm-handle memory (`TestLivePushProbeWarmMemory`). |
| +**Race detector:** the gate builds with `CGO_ENABLED=0`, so a dedicated |
| +gate step runs |
| +`CGO_ENABLED=1 go test -race -short -count=1 -run 'Warm|BoundToATransaction|Stream' ./internal/docs/` |
| +(about 2.5 minutes). Run the same command locally before each server |
| +release that touches warm.go or stream.go. |
| + |
| +**Not dropped in 1a, on purpose** (spec §3.5 rule 6): |
| +- team roster changes: retention up to 60 s, not access; a candidate for |
| + 1b; |
| +- version restore: it doesn't exist yet, and must drop the handle when it |
| + does (a note sits at the `updated_at` invariant in `store.go`). |
| + |
| **Done when:** hub CI green; Fable branch review; canary with |
| `DOCS_WARM_HANDLE=on`. Then re-run `load-p1`/`load-p20` and the 5 + 5 shared |
| document against production-like settings, and flip the default on. |
diff --git a/docs/superpowers/specs/2026-11-26-live-push-design.md b/docs/superpowers/specs/2026-11-26-live-push-design.md| index 762878a..2215b98 100644 |
| --- a/docs/superpowers/specs/2026-11-26-live-push-design.md |
| +++ b/docs/superpowers/specs/2026-11-26-live-push-design.md |
| @@ -399,11 +399,23 @@ rules for keeping the replayed `core.Handle` between POSTs: |
| 1. **Taken under a per-document lock.** POSTs to one document already |
| serialise on the single SQLite writer. |
| 2. **Applied before the transaction**, as today's replayed handle is. |
| - - A clean core rejection (`RejectedError`) leaves the handle as it was; |
| - the POST answers 400 as today. |
| - - `ErrUpdateLogFull`, a trap or `RecoveredError`: drop the handle and |
| - replay cold **inside the same POST**, then carry on as today. The cache |
| - never fails a POST. |
| + - **Any error from `Apply` drops the handle.** A rejection |
| + (`RejectedError`) answers 400 as today, but it is not clean. yrs |
| + integrates an update's structs one at a time, so an update whose later |
| + struct is refused (`InvalidParent`, `ERR_APPLY`) leaves the earlier ones |
| + in the store, and the core's transaction commits them. A kept handle |
| + would carry that content into the next snapshot with no row holding it |
| + (branch review #174, finding 1). |
| + - `ErrUpdateLogFull`, a trap or `RecoveredError`: also replay cold |
| + **inside the same POST**, then carry on as today. The cache never fails |
| + a POST that a replay would take. |
| + - A request cancelled mid-Apply drops the handle quietly and is not |
| + retried. |
| + - An "applied, not committed" flag set before `Apply` closes the handle |
| + on every way out short of a commit, a panic included. |
| + - Making the core apply into a scratch transaction it can roll back would |
| + make a refused update change nothing. That is a core change with its |
| + own ABI test, not part of this spec. |
| 3. **Committed, or dropped.** Any failure after a successful `Apply` drops |
| the handle: the in-transaction permission check refusing (a writer |
| revoked mid-request), a cancelled context, a database error, the team |
| @@ -432,7 +444,17 @@ rules for keeping the replayed `core.Handle` between POSTs: |
| 6. **Dropped** on delete, restore, any change to the document's grants, |
| team or sealing state (no sealed plaintext stays resident after access |
| changes), after 60 s without a POST, and at shutdown (`hub.drain` closes |
| - them). |
| + them). As built in slice 1a: |
| + - grants, revoke, visibility, delete, drain and close drop it; |
| + - sealing is activated offline with the app stopped; |
| + - **team roster changes** arrive from outside and drop nothing, and nor |
| + does a grant changed by a second process during a deploy overlap. That |
| + is retention for at most 60 s, not access: permission is checked on |
| + every POST and inside the transaction. Dropping on a roster refresh is |
| + a candidate for slice 1b, which touches the team guard anyway. |
| + - **There is no version restore yet.** When there is, it must drop the |
| + handle: a restore that rewrites rows could leave `MAX(seq)` where it |
| + was, which rule 3 cannot see. |
| 7. **Swept by POSTs and by the stream's heartbeat.** `stream.go` has no |
| timer outside a live connection. Each POST sweeps the cache, and so does |
| every open stream's 15 s heartbeat, which is a timer inside a live |
diff --git a/internal/core/core.go b/internal/core/core.go| index 22bb2c4..4c64eb1 100644 |
| --- a/internal/core/core.go |
| +++ b/internal/core/core.go |
| @@ -532,11 +532,18 @@ func applyOn(ctx context.Context, timeout time.Duration, mod api.Module, docHand |
| } |
| // Apply applies update to the document. A clean rejection (a negative |
| -// error code from the guest, e.g. malformed wire bytes that yrs's decoder |
| -// catches) leaves the instance untouched and fully usable — that is the |
| +// error code from the guest) leaves the instance usable — that is the |
| // whole point of §5.2's per-document instance: most bad input never needs |
| // the instance discarded at all. That case comes back as a *RejectedError |
| -// (see Rejected). A trap or a deadline exceeded is different: the |
| +// (see Rejected). "Usable" is not "untouched": bytes the decoder refuses |
| +// (ERR_DECODE) change nothing, but an update that decodes and then fails |
| +// part-way (ERR_APPLY, e.g. a later struct's InvalidParent) leaves the |
| +// structs integrated before the failure in the document, because yrs |
| +// integrates them one at a time and the transaction commits on drop. A |
| +// caller that keeps a handle after a rejection holds that partial state |
| +// (Docs' warm handles drop it; live-push review #174, finding 1). Making |
| +// the guest apply into a scratch transaction it can roll back would close |
| +// this here; that is a core change with its own ABI test, not done yet. A trap or a deadline exceeded is different: the |
| // instance is discarded and rebuilt from every update applied here so |
| // far, and the triggering update is reported as an error but never |
| // retried or logged, so it can never itself be replayed into the rebuilt |
diff --git a/internal/docs/store.go b/internal/docs/store.go| index cb38f7e..426c14e 100644 |
| --- a/internal/docs/store.go |
| +++ b/internal/docs/store.go |
| @@ -836,6 +836,8 @@ func (s *Store) currentSeq(ctx context.Context, docID int64) (int64, error) { |
| // anywhere raising a hand. Today this is the only content write, so |
| // the invariant holds by having one writer; the writes that will test |
| // it are version restore (spec §14) and any future log compaction. |
| +// Both must also drop the document's warm handle (warm.go, rule 6): a |
| +// rewrite that leaves MAX(seq) where it was is invisible to rule 3. |
| // Note also that this bumps the COLUMN and not the *Document it was |
| // handed — a caller holding that struct has a stale UpdatedAt, which |
| // is why the cache takes its key from the row Store.List returned. |
diff --git a/internal/docs/team_router_test.go b/internal/docs/team_router_test.go| index ce2b5f3..04fd347 100644 |
| --- a/internal/docs/team_router_test.go |
| +++ b/internal/docs/team_router_test.go |
| @@ -78,6 +78,13 @@ func newTeamRouterFixture(t *testing.T) *teamRouterFixture { |
| return newTeamRouterFixtureWithDashboard(t, false) |
| } |
| func newTeamRouterFixtureWithDashboard(t *testing.T, dashboard bool) *teamRouterFixture { |
| + return newTeamRouterFixtureWith(t, dashboard, false) |
| +} |
| + |
| +// newTeamRouterFixtureWith can also run the team instance with warm |
| +// handles and content sealing on (warm_test.go): rows sealed as production |
| +// stores them, and DOCS_WARM_HANDLE on. |
| +func newTeamRouterFixtureWith(t *testing.T, dashboard, warmSealed bool) *teamRouterFixture { |
| t.Helper() |
| ctx := t.Context() |
| credential, e := family.Generate() |
| @@ -89,6 +96,25 @@ func newTeamRouterFixtureWithDashboard(t *testing.T, dashboard bool) *teamRouter |
| manifest, _ := json.Marshal(map[string]string{kid: base64.StdEncoding.EncodeToString(credential.SignPub())}) |
| home := HomeConfig{Issuer: bridgeIssuer, ConsumerID: "router-docs", KeysBase64: base64.StdEncoding.EncodeToString(manifest), DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{83}, 32))} |
| cfg := Config{DBPath: filepath.Join(t.TempDir(), "team.db"), Env: "development", Origin: bridgeOrigin, Home: &home, AllowedAddresses: "alice@example.com,bob@example.com", SampleDocuments: "0", Mailer: navigationMail{}, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))} |
| + if warmSealed { |
| + cfg.ContentKey = base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{71}, 32)) |
| + cfg.WarmHandle = true |
| + // Sealing is activated offline, as activatedContentApp does. |
| + first, e := New(cfg) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = first.Close(); e != nil { |
| + t.Fatal(e) |
| + } |
| + cipher, e := newContentCipher(cfg.ContentKey, "production") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = MaintainContent(ctx, ContentMaintenanceConfig{DBPath: cfg.DBPath, ContentKey: cfg.ContentKey, ExpectedFingerprint: cipher.fingerprint}); e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| app, e := New(cfg) |
| if e != nil { |
| t.Fatal(e) |
diff --git a/internal/docs/warm.go b/internal/docs/warm.go| index a57a2f7..7ac37f5 100644 |
| --- a/internal/docs/warm.go |
| +++ b/internal/docs/warm.go |
| @@ -15,11 +15,12 @@ package docs |
| // 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. |
| +// 2. Applied before the transaction, as the replayed handle always was. |
| +// Any error from Apply drops the handle. A rejection answers 400 as |
| +// before; it is not clean, since a refused update can leave its earlier |
| +// structs in the store (review #174, finding 1). Anything else |
| +// (ErrUpdateLogFull, a trap, RecoveredError) redoes the POST cold, so |
| +// the cache never fails a POST that a replay would take. |
| // 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 |
| @@ -37,6 +38,14 @@ package docs |
| // 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. |
| +// Narrower than the spec's rule 6, on purpose for now: |
| +// - Team roster changes arrive from outside and drop nothing; nor does a |
| +// grant changed by a second process during a deploy overlap. That |
| +// is retention only, for at most warmIdle: permission is checked on |
| +// every POST and again inside the transaction. |
| +// - There is no version restore yet. When there is, it must call |
| +// warm.drop: a restore that rewrites rows could leave MAX(seq) equal, |
| +// which rule 3's check would not notice. |
| // 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 |
| @@ -73,6 +82,10 @@ 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 |
| + // 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). |
| + pending bool |
| // Read and written under the cache's mu, so the caps and stats never |
| // look at a handle another goroutine is using. |
| @@ -88,6 +101,9 @@ type warmCache struct { |
| maxHandles int |
| idle time.Duration |
| now func() time.Time |
| + // 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) |
| } |
| func newWarmCache() *warmCache { |
| @@ -108,23 +124,39 @@ func (c *warmCache) acquire(ctx context.Context, docID int64) *warmEntry { |
| c.entries[docID] = e |
| } |
| e.used = c.now() |
| + hook := c.afterLookup |
| c.mu.Unlock() |
| + if hook != nil { |
| + hook(e) |
| + } |
| 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. |
| +// |
| +// It closes the handle when: an update is still pending (the POST did not |
| +// reach its commit, a panic included); the entry was dropped while held |
| +// (dead), or between acquire's two locks, so it is no longer the cache's |
| +// (an orphan nothing would ever sweep, cap or drop again: review finding |
| +// 3); the cache is closed; or the handle is over the byte cap. An entry |
| +// left without a handle leaves the map, so it does not count toward the |
| +// count cap (finding 6). |
| func (c *warmCache) release(ctx context.Context, e *warmEntry) { |
| + if e.pending { |
| + e.close(ctx) |
| + } |
| var bytes uint64 |
| if e.h != nil { |
| bytes = e.h.ResidentBytes() |
| } |
| c.mu.Lock() |
| - if e.dead || c.closed || bytes > c.maxBytes { |
| + mine := c.entries[e.docID] == e |
| + if e.dead || !mine || c.closed || bytes > c.maxBytes || e.h == nil { |
| e.close(ctx) |
| bytes = 0 |
| - if c.entries[e.docID] == e { |
| + if mine { |
| delete(c.entries, e.docID) |
| } |
| } |
| @@ -140,7 +172,7 @@ func (e *warmEntry) close(ctx context.Context) { |
| if e.h != nil { |
| e.h.Close(ctx) |
| } |
| - e.h, e.seq, e.snap = nil, 0, 0 |
| + e.h, e.seq, e.snap, e.pending = nil, 0, 0, false |
| } |
| // evictLocked removes e from the cache. c.mu is held; e.mu is taken if it |
| @@ -275,14 +307,26 @@ func (s *Store) applyWarm(ctx context.Context, doc *Document, actor Actor, updat |
| } |
| } |
| + e.pending = true |
| if err := s.warmApply(ctx, e.h, update); err != nil { |
| + // Rule 2: ANY error from Apply drops the handle. A rejection is not |
| + // clean: yrs integrates an update's structs one at a time, and a |
| + // later struct refused (InvalidParent, ERR_APPLY) leaves the earlier |
| + // ones in the store, which the core's transaction then commits |
| + // (review finding 1). The cold path threw that handle away; so does |
| + // this one. A rejection costs one replay on the next POST. |
| + e.close(ctx) |
| 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. |
| + if ctx.Err() != nil { |
| + // The client went away mid-Apply: not a sick handle, and a cold |
| + // retry would fail on the same context (finding 7). |
| + return 0, fmt.Errorf("docs: apply update to document %d: %w", doc.ID, ctx.Err()) |
| + } |
| + // A full log, a trap or a recovered instance: redo it cold. |
| s.logger.Warn("docs: warm handle dropped, replaying", "doc_id", doc.ID, "err", err) |
| - e.close(ctx) |
| return s.applyCold(ctx, doc, actor, update) |
| } |
| @@ -291,6 +335,7 @@ func (s *Store) applyWarm(ctx context.Context, doc *Document, actor Actor, updat |
| e.close(ctx) // rule 3: applied, not committed |
| return 0, err |
| } |
| + e.pending = false |
| 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 26ea436..c28e181 100644 |
| --- a/internal/docs/warm_test.go |
| +++ b/internal/docs/warm_test.go |
| @@ -4,16 +4,20 @@ package docs |
| // names the rule it holds. |
| import ( |
| + "bytes" |
| "context" |
| "errors" |
| "fmt" |
| + "log/slog" |
| "math/rand" |
| "net/http/httptest" |
| "sort" |
| "strings" |
| + "sync" |
| "testing" |
| "time" |
| + "amadan.net/oficina/home/roster" |
| "github.com/carlosframework/docs/internal/core" |
| "gorm.io/gorm" |
| ) |
| @@ -291,24 +295,280 @@ func TestWarmHandleFallsBackToAColdReplay(t *testing.T) { |
| } |
| } |
| -// Rule 2: a clean core rejection answers as before and leaves the handle. |
| -func TestWarmHandleSurvivesARejectedUpdate(t *testing.T) { |
| +// Rule 2, review #174 finding 1: a rejection is not clean. An update whose |
| +// first struct integrates and whose second is refused (ERR_APPLY) answers |
| +// 400 with the first struct already in the handle's store; the handle must |
| +// go, or the next snapshot persists content no row holds. Garbage the |
| +// decoder refuses drops it too (one replay on the next POST). |
| +func TestWarmHandleIsDroppedWhenAnUpdateIsRejected(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + update []byte |
| + }{{"half-applied", halfApplyingUpdate()}, {"undecodable", []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}} { |
| + t.Run(c.name, func(t *testing.T) { |
| + f := newWarmFixture(t) |
| + f.mustPost(f.word(1)) |
| + _, err := f.post(c.update) |
| + var rejection *updateRejection |
| + if !errors.As(err, &rejection) { |
| + t.Fatalf("%s: %v, want an update rejection", c.name, err) |
| + } |
| + if _, ok := f.warmText(); ok { |
| + t.Fatal("a rejected update left the warm handle") |
| + } |
| + for k := 2; k <= snapshotCadence+2; 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) |
| + } |
| + if bytes.Contains(snap.State, []byte("INJECTED")) { |
| + t.Fatal("the refused update's first struct reached a snapshot") |
| + } |
| + if e := f.entry(); e != nil && e.h != nil { |
| + state, _ := e.h.Snapshot(f.ctx) |
| + if bytes.Contains(state, []byte("INJECTED")) { |
| + t.Fatal("the warm handle holds the refused update's first struct") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Review finding 2: a panic between Apply and commit (net/http recovers it |
| +// and the process lives) must not leave the applied, uncommitted handle. |
| +func TestWarmHandleIsDroppedAfterAPanicBeforeCommit(t *testing.T) { |
| + f := newWarmFixture(t) |
| + f.mustPost(f.word(1)) |
| + f.s.warmBeforeCommit = func(context.Context, *gorm.DB, *Document) error { panic("injected") } |
| + func() { |
| + defer func() { _ = recover() }() |
| + f.post(f.word(2)) |
| + }() |
| + f.s.warmBeforeCommit = nil |
| + if _, ok := f.warmText(); ok { |
| + t.Fatal("the handle that applied word2 survived the panic") |
| + } |
| + f.mustPost(f.word(3)) |
| + got, ok := f.warmText() |
| + if !ok || strings.Contains(got, "word2") || sortedWords(got) != sortedWords(f.rowsText(-1)) { |
| + t.Fatalf("after the panic the warm handle differs from the log: %q", got) |
| + } |
| +} |
| + |
| +// Review finding 3: an entry dropped between acquire's lookup and its lock |
| +// (a revoke, a delete, a cap eviction) is no longer the cache's. The POST |
| +// that holds it must close its handle on release, not keep an orphan that |
| +// nothing would ever sweep, cap or drop. |
| +func TestWarmHandleOrphanedBetweenLookupAndLockIsClosed(t *testing.T) { |
| + f := newWarmFixture(t) |
| + var orphan *warmEntry |
| + f.s.warm.afterLookup = func(e *warmEntry) { |
| + f.s.warm.afterLookup = nil |
| + orphan = e |
| + f.s.warm.drop(f.ctx, f.doc.ID) |
| + } |
| + f.mustPost(f.word(1)) |
| + if orphan == nil { |
| + t.Fatal("the seam did not run") |
| + } |
| + if orphan.h != nil { |
| + orphan.h.Close(f.ctx) |
| + t.Fatal("an entry dropped between lookup and lock kept an open handle") |
| + } |
| + if n, _ := f.s.warm.stats(); n != 0 { |
| + t.Fatalf("%d handles", n) |
| + } |
| +} |
| + |
| +// Review finding 6: an entry left without a handle (a failed commit, a |
| +// re-seed) leaves the map, so it cannot push a real handle out of the |
| +// count cap. |
| +func TestWarmEntriesWithoutAHandleDoNotCount(t *testing.T) { |
| + f := newWarmFixture(t) |
| + other, err := f.s.Create(f.ctx, f.owner, "Other") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.s.warm.maxHandles = 1 |
| + f.mustPost(f.word(1)) |
| + f.s.warmBeforeCommit = func(context.Context, *gorm.DB, *Document) error { return errors.New("injected") } |
| + u, _ := f.app.core.InitialUpdate(f.ctx, other.GUID, 777, []core.InitialBlock{{Text: "other"}}) |
| + if _, err := f.s.ApplyUpdate(f.ctx, other, f.actor, u); err == nil { |
| + t.Fatal("the injected failure did not fail the POST") |
| + } |
| + f.s.warmBeforeCommit = nil |
| + if _, ok := f.warmText(); !ok { |
| + t.Fatal("an empty entry evicted the only real handle") |
| + } |
| + f.s.warm.mu.Lock() |
| + n := len(f.s.warm.entries) |
| + f.s.warm.mu.Unlock() |
| + if n != 1 { |
| + t.Fatalf("%d entries, want 1", n) |
| + } |
| +} |
| + |
| +// Review finding 7: a request cancelled mid-Apply drops the handle quietly: |
| +// no rule 2 warning (the canary watches it) and no cold retry. |
| +func TestWarmHandleCancelledMidApplyIsQuiet(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) |
| + var logs bytes.Buffer |
| + f.s.logger = slog.New(slog.NewTextHandler(&logs, nil)) |
| + ctx, cancel := context.WithCancel(f.ctx) |
| + replays := 0 |
| + f.s.warmApplyHook = func(*core.Handle) error { cancel(); return errors.New("core: deadline: context canceled") } |
| + f.s.warmBeforeCommit = func(context.Context, *gorm.DB, *Document) error { replays++; return nil } |
| + _, err := f.s.ApplyUpdate(ctx, f.doc, f.actor, f.word(2)) |
| + f.s.warmApplyHook, f.s.warmBeforeCommit = nil, nil |
| + if !errors.Is(err, context.Canceled) { |
| + t.Fatalf("err = %v, want context.Canceled", err) |
| + } |
| + if replays != 0 { |
| + t.Error("a cancelled request was retried cold") |
| + } |
| + if strings.Contains(logs.String(), "warm handle dropped") { |
| + t.Errorf("a cancelled request logged the rule 2 warning: %s", logs.String()) |
| + } |
| +} |
| + |
| +// 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, |
| +// a cold replay and any warm handle agree. (The review ran 8 × 400; each |
| +// POST here is a new Yjs client, and with drops forcing replays that many |
| +// clients made the replays themselves time out on a loaded machine.) |
| +func TestWarmHandlesUnderConcurrentPOSTs(t *testing.T) { |
| + per := 150 |
| + if testing.Short() { |
| + per = 40 |
| + } |
| + f := newWarmFixture(t) |
| + second, err := f.s.Create(f.ctx, f.owner, "Second") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + docs := []*Document{f.doc, second} |
| + var clockMu sync.Mutex |
| + clock := time.Now() |
| + f.s.warm.mu.Lock() |
| + f.s.warm.now = func() time.Time { clockMu.Lock(); defer clockMu.Unlock(); return clock } |
| + f.s.warm.mu.Unlock() |
| + stop := make(chan struct{}) |
| + var churn sync.WaitGroup |
| + churn.Add(1) |
| + go func() { |
| + defer churn.Done() |
| + for i := 0; ; i++ { |
| + select { |
| + case <-stop: |
| + return |
| + default: |
| + } |
| + switch i % 3 { |
| + case 0: |
| + f.s.warm.drop(f.ctx, docs[i%2].ID) |
| + case 1: |
| + clockMu.Lock() |
| + clock = clock.Add(warmIdle + time.Second) |
| + clockMu.Unlock() |
| + f.s.warm.sweep(f.ctx) |
| + default: |
| + f.s.warm.stats() |
| + } |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| + }() |
| + var wg sync.WaitGroup |
| + errs := make(chan error, 8) |
| + for g := 0; g < 8; g++ { |
| + wg.Add(1) |
| + go func(g int) { |
| + defer wg.Done() |
| + for i := 0; i < per; i++ { |
| + d := docs[(g+i)%2] |
| + u, err := f.app.core.InitialUpdate(f.ctx, d.GUID, uint64(300000+g*10000+i), []core.InitialBlock{{Text: fmt.Sprintf("g%di%d", g, i)}}) |
| + 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) |
| } |
| - 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") |
| + wg.Wait() |
| + close(stop) |
| + churn.Wait() |
| + close(errs) |
| + for err := range errs { |
| + t.Fatal(err) |
| + } |
| + for _, d := range docs { |
| + g := &warmFixture{t: t, app: f.app, s: f.s, owner: f.owner, actor: f.actor, doc: d, ctx: f.ctx} |
| + truth := sortedWords(g.rowsText(-1)) |
| + if got := len(strings.Fields(truth)); got != 8*per/2 { |
| + t.Fatalf("document %d holds %d words, want %d", d.ID, got, 8*per/2) |
| + } |
| + if sortedWords(g.coldText()) != truth { |
| + t.Fatalf("document %d: a cold replay differs from the log", d.ID) |
| + } |
| + if warm, ok := g.warmText(); ok && sortedWords(warm) != truth { |
| + t.Fatalf("document %d: the warm handle differs from the log", d.ID) |
| + } |
| + } |
| +} |
| + |
| +// Team mode with sealed rows, as production stores them (review finding 4): |
| +// a linked member's POSTs through the router keep a warm handle, cross the |
| +// snapshot cadence through the team branch, and agree with the log; a |
| +// member removed from the roster is refused before any handle is touched. |
| +func TestWarmHandleInTeamModeWithSealedRows(t *testing.T) { |
| + f := newTeamRouterFixtureWith(t, false, true) |
| + if f.app.store.warm == nil { |
| + t.Fatal("the team fixture did not turn warm handles on") |
| + } |
| + var encoding int |
| + f.app.store.db.Raw("SELECT content_encoding FROM doc_updates LIMIT 1").Scan(&encoding) |
| + if encoding != 1 { |
| + t.Fatalf("rows are not sealed (content_encoding %d)", encoding) |
| + } |
| + b := f.browser() |
| + b.localSignin(t, "alice@example.com") |
| + b.linkProof(t, teamSubject('a'), "alice@example.com") |
| + routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL("/")) |
| + g := &warmFixture{t: t, app: f.app, s: f.app.store, doc: f.own, ctx: context.Background()} |
| + for k := 1; k <= snapshotCadence+3; k++ { |
| + if code := b.update(f.own, g.word(k)); code != 204 { |
| + t.Fatalf("team POST %d: %d", k, code) |
| + } |
| + } |
| + snap, err := g.s.newestSnapshot(g.ctx, f.own.ID) |
| + if err != nil || snap == nil || snap.Seq < snapshotCadence { |
| + t.Fatalf("no team-mode snapshot at the cadence: %+v %v", snap, err) |
| + } |
| + warm, ok := g.warmText() |
| + if !ok || sortedWords(warm) != sortedWords(g.rowsText(-1)) || sortedWords(g.coldText()) != sortedWords(g.rowsText(-1)) { |
| + t.Fatal("in team mode the warm handle, a cold replay and the log disagree") |
| + } |
| + f.clock.step(roster.RetryAfter) |
| + f.directory.change([]roster.MemberEntry{{Subject: teamSubject('b'), Role: "member"}}, false) |
| + if e := f.app.store.team.cache.Refresh(t.Context()); e != nil { |
| + t.Fatal(e) |
| + } |
| + if code := b.update(f.own, g.word(9999)); code != 404 { |
| + t.Fatalf("a removed member's POST answered %d", code) |
| + } |
| + if strings.Contains(g.rowsText(-1), "word9999") { |
| + t.Fatal("a removed member's update reached the log") |
| } |
| } |
| // Rules 2–3 and 8 together: random POSTs, failed commits, injected Apply |
| -// failures, rejections, drops and commits by another Store on the same |
| +// failures, rejections (undecodable and half-applying), 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. |
| @@ -328,7 +588,11 @@ func TestWarmHandleMatchesAColdReplayUnderFailures(t *testing.T) { |
| k := seed*1000 + step |
| word := fmt.Sprintf("word%d", k) |
| warmAfterPost := false |
| - switch op := rng.Intn(10); { |
| + switch op := rng.Intn(11); { |
| + case op == 10: |
| + if _, err := f.post(halfApplyingUpdate()); err == nil { |
| + t.Fatal("a half-applying update was accepted") |
| + } |
| case op < 4: |
| f.mustPost(f.word(k)) |
| committed[word] = true |
| @@ -376,6 +640,11 @@ func TestWarmHandleMatchesAColdReplayUnderFailures(t *testing.T) { |
| t.Fatalf("step %d: refused %s is in the log", step, w) |
| } |
| } |
| + if e := f.entry(); e != nil && e.h != nil { |
| + if state, _ := e.h.Snapshot(f.ctx); bytes.Contains(state, []byte("INJECTED")) { |
| + t.Fatalf("step %d: the warm handle holds a refused update", step) |
| + } |
| + } |
| if warmAfterPost { |
| if got, ok := f.warmText(); ok && sortedWords(got) != sortedWords(truth) { |
| t.Fatalf("step %d: the warm handle differs from the log", step) |
| @@ -595,3 +864,24 @@ func TestWarmHandleIsFasterThanAReplay(t *testing.T) { |
| t.Fatalf("a warm POST (%.0f µs) is not faster than a replay (%.0f µs)", warm, cold) |
| } |
| } |
| + |
| +// halfApplyingUpdate is the review's case (#174, finding 1): a Yjs v1 |
| +// update whose first struct is valid (the string "INJECTED" under a named |
| +// root) and whose second names that string item as its parent, which yrs |
| +// refuses with InvalidParent only after it has integrated the first. The |
| +// core answers it as a rejection (ERR_APPLY), with the first struct |
| +// already in the document. |
| +func halfApplyingUpdate() []byte { |
| + const client = 4242 |
| + b := []byte{1, 2} // one client group, two structs |
| + b = append(b, client&0x7f|0x80, client>>7) |
| + b = append(b, 0) // clock 0 |
| + b = append(b, 0x04, 1) // struct 1: ContentString, parent is a named root |
| + b = append(b, 1, 'x') // the root's name |
| + b = append(b, 8) // "INJECTED", 8 characters: clocks 0-7 |
| + b = append(b, "INJECTED"...) |
| + b = append(b, 0x04, 0) // struct 2: ContentString, parent is an item id |
| + b = append(b, client&0x7f|0x80, client>>7, 0) // (client, clock 0): struct 1, not a type |
| + b = append(b, 3, 'a', 'b', 'c') |
| + return append(b, 0) // empty delete set |
| +} |