| 1 | package docs |
| 2 | |
| 3 | // Warm handles: the live-push spec's §3.5 |
| 4 | // (docs/superpowers/specs/2026-11-26-live-push-design.md), slice 1a. |
| 5 | // |
| 6 | // Store.ApplyUpdate used to replay the whole document for every POST: a |
| 7 | // fresh WASM instance, the newest snapshot and up to 255 tail rows, then |
| 8 | // the update. At 20 pages that was ~11 ms of CPU and ~8 MB of garbage per |
| 9 | // keystroke batch, a third of the server's CPU. A warm handle is the |
| 10 | // replayed core.Handle kept between POSTs, so a POST applies one update |
| 11 | // (~15 µs) instead. |
| 12 | // |
| 13 | // The rules, each of which some test in warm_test.go holds: |
| 14 | // |
| 15 | // 1. One POST at a time per handle: the entry's mutex is held from the |
| 16 | // Apply to the commit. POSTs to one document already serialise on the |
| 17 | // single SQLite writer, so this costs nothing. It is per handle, not per |
| 18 | // document: when an entry leaves the map while held (a drop, an |
| 19 | // eviction), a new POST makes a new entry, so two POSTs to one document |
| 20 | // can run on separate handles. Rule 3's MAX(seq) check inside the |
| 21 | // transaction is what keeps that correct; the one that loses is dropped. |
| 22 | // 2. Applied before the transaction, as the replayed handle always was. |
| 23 | // Any error from Apply drops the handle. A rejection answers 400 as |
| 24 | // before; it is not clean, since a refused update can leave its earlier |
| 25 | // structs in the store (review #174, finding 1). Anything else |
| 26 | // (ErrUpdateLogFull, a trap, RecoveredError) redoes the POST cold, so |
| 27 | // the cache never fails a POST that a replay would take. |
| 28 | // 3. Committed, or dropped. Any failure after a successful Apply drops the |
| 29 | // handle, and its seq advances only after commit. If the log's MAX(seq) |
| 30 | // inside the transaction is not the handle's seq (another process, the |
| 31 | // agent path, a test), the row is still written, as a stale replay's |
| 32 | // always was, and the handle is dropped. |
| 33 | // 4. Re-seeded at the snapshot cadence: snapshot from the warm state at the |
| 34 | // handle's seq, Apply, commit, then drop; the next POST replays from that |
| 35 | // snapshot. A warm handle therefore never retains more than ~257 |
| 36 | // updates, far from core.MaxRetainedUpdates (4,096). A failed snapshot |
| 37 | // write keeps the handle, as a failed cold one kept the log. |
| 38 | // 5. Bounded: warmMaxBytes of ResidentBytes and warmMaxHandles handles, |
| 39 | // least recently used out first; one handle above the byte cap is never |
| 40 | // kept. |
| 41 | // 6. Dropped on delete, on any change to a document's grants or |
| 42 | // visibility, after warmIdle without a POST, and when the app drains or |
| 43 | // closes. Sealing is activated offline (MaintainContent) with the app |
| 44 | // stopped, so a process never sees it change under a handle. |
| 45 | // Narrower than the spec's rule 6, on purpose for now: |
| 46 | // - Team roster changes arrive from outside and drop nothing; nor does a |
| 47 | // grant changed by a second process during a deploy overlap. That |
| 48 | // is retention only, for at most warmIdle: permission is checked on |
| 49 | // every POST and again inside the transaction. |
| 50 | // - There is no version restore yet. When there is, it must call |
| 51 | // warm.drop: a restore that rewrites rows could leave MAX(seq) equal, |
| 52 | // which rule 3's check would not notice. |
| 53 | // 7. Swept by every POST and by every open stream's heartbeat (stream.go), |
| 54 | // a timer inside a live connection: no timer of its own. |
| 55 | // 8. Two processes on one database stay correct, because rule 3's check is |
| 56 | // inside the transaction. |
| 57 | // |
| 58 | // A Store bound to a caller's transaction (the agent paths) never uses |
| 59 | // warm handles: its "commit" is a savepoint the caller can still roll back |
| 60 | // after ApplyUpdate returns, which rule 3 cannot see. |
| 61 | |
| 62 | import ( |
| 63 | "context" |
| 64 | "errors" |
| 65 | "fmt" |
| 66 | "sort" |
| 67 | "sync" |
| 68 | "sync/atomic" |
| 69 | "time" |
| 70 | |
| 71 | "github.com/carlosframework/docs/internal/core" |
| 72 | "gorm.io/gorm" |
| 73 | ) |
| 74 | |
| 75 | const ( |
| 76 | warmIdle = 60 * time.Second |
| 77 | warmMaxHandles = 64 |
| 78 | warmMaxBytes = 128 << 20 |
| 79 | ) |
| 80 | |
| 81 | // warmEntry is one document's handle. mu is rule 1's per-document lock. |
| 82 | type warmEntry struct { |
| 83 | mu sync.Mutex |
| 84 | docID int64 |
| 85 | h *core.Handle |
| 86 | seq int64 // the log's MAX(seq) the handle holds |
| 87 | snap int64 // the newest snapshot's seq, as far as the handle knows |
| 88 | used time.Time |
| 89 | dead bool // dropped while held: the holder closes it on release |
| 90 | // refs counts the POSTs that hold or wait for this entry, under the |
| 91 | // cache's mu. A handle-less entry leaves the map only when nobody waits |
| 92 | // on it: deleting it under waiters made each of them replay and every |
| 93 | // new POST start a second entry (review #174, delta finding 1). |
| 94 | refs int |
| 95 | // pending: an update has been applied to h and not yet committed. Set |
| 96 | // before Apply and cleared only after the commit, so release closes the |
| 97 | // handle on every other way out, a panic included (review finding 2). |
| 98 | pending bool |
| 99 | |
| 100 | // Read and written under the cache's mu, so the caps and stats never |
| 101 | // look at a handle another goroutine is using. |
| 102 | bytes uint64 |
| 103 | kept bool |
| 104 | } |
| 105 | |
| 106 | type warmCache struct { |
| 107 | mu sync.Mutex |
| 108 | entries map[int64]*warmEntry |
| 109 | closed bool |
| 110 | maxBytes uint64 |
| 111 | maxHandles int |
| 112 | idle time.Duration |
| 113 | now func() time.Time |
| 114 | // afterLookup is a test seam: it runs in acquire between finding the |
| 115 | // entry and locking it, the window review finding 3 is about. |
| 116 | afterLookup func(e *warmEntry) |
| 117 | // counts says what the cache did; tests and probes read it. |
| 118 | counts warmCounts |
| 119 | } |
| 120 | |
| 121 | // warmCounts are cumulative: replays (a handle built by a replay), hits (an |
| 122 | // update applied to a kept handle), stale (dropped by rule 3's MAX(seq) |
| 123 | // check), reseeds (rule 4). |
| 124 | type warmCounts struct { |
| 125 | replays, hits, stale, reseeds atomic.Int64 |
| 126 | } |
| 127 | |
| 128 | func newWarmCache() *warmCache { |
| 129 | return &warmCache{entries: map[int64]*warmEntry{}, maxBytes: warmMaxBytes, maxHandles: warmMaxHandles, idle: warmIdle, now: time.Now} |
| 130 | } |
| 131 | |
| 132 | // acquire returns docID's entry locked, or nil when the cache is closed. |
| 133 | func (c *warmCache) acquire(ctx context.Context, docID int64) *warmEntry { |
| 134 | c.mu.Lock() |
| 135 | if c.closed { |
| 136 | c.mu.Unlock() |
| 137 | return nil |
| 138 | } |
| 139 | c.sweepLocked(ctx, docID) |
| 140 | e := c.entries[docID] |
| 141 | if e == nil { |
| 142 | e = &warmEntry{docID: docID} |
| 143 | c.entries[docID] = e |
| 144 | } |
| 145 | e.used = c.now() |
| 146 | e.refs++ |
| 147 | hook := c.afterLookup |
| 148 | c.mu.Unlock() |
| 149 | if hook != nil { |
| 150 | hook(e) |
| 151 | } |
| 152 | e.mu.Lock() |
| 153 | return e |
| 154 | } |
| 155 | |
| 156 | // release unlocks e after a POST, closing its handle if it was dropped |
| 157 | // meanwhile or is too large to keep, and then enforces the caps. |
| 158 | // |
| 159 | // It closes the handle when: an update is still pending (the POST did not |
| 160 | // reach its commit, a panic included); the entry was dropped while held |
| 161 | // (dead), or between acquire's two locks, so it is no longer the cache's |
| 162 | // (an orphan nothing would ever sweep, cap or drop again: review finding |
| 163 | // 3); the cache is closed; or the handle is over the byte cap. An entry |
| 164 | // left without a handle leaves the map, so it does not count toward the |
| 165 | // count cap (finding 6). |
| 166 | func (c *warmCache) release(ctx context.Context, e *warmEntry) { |
| 167 | if e.pending { |
| 168 | e.close(ctx) |
| 169 | } |
| 170 | var bytes uint64 |
| 171 | if e.h != nil { |
| 172 | bytes = e.h.ResidentBytes() |
| 173 | } |
| 174 | c.mu.Lock() |
| 175 | e.refs-- |
| 176 | mine := c.entries[e.docID] == e |
| 177 | if e.dead || !mine || c.closed || bytes > c.maxBytes { |
| 178 | e.close(ctx) |
| 179 | bytes = 0 |
| 180 | if mine { |
| 181 | delete(c.entries, e.docID) |
| 182 | } |
| 183 | } else if e.h == nil && e.refs == 0 { |
| 184 | // Handle-less and nobody waiting: leave the map (finding 6). |
| 185 | delete(c.entries, e.docID) |
| 186 | } |
| 187 | e.bytes, e.kept = bytes, e.h != nil |
| 188 | e.used = c.now() |
| 189 | e.mu.Unlock() |
| 190 | c.capLocked(ctx) |
| 191 | c.mu.Unlock() |
| 192 | } |
| 193 | |
| 194 | // close drops e's handle. The caller holds e.mu. |
| 195 | func (e *warmEntry) close(ctx context.Context) { |
| 196 | if e.h != nil { |
| 197 | e.h.Close(ctx) |
| 198 | } |
| 199 | e.h, e.seq, e.snap, e.pending = nil, 0, 0, false |
| 200 | } |
| 201 | |
| 202 | // evictLocked removes e from the cache. c.mu is held; e.mu is taken if it |
| 203 | // is free, and otherwise e is marked dead for its holder to close. |
| 204 | func (c *warmCache) evictLocked(ctx context.Context, e *warmEntry) { |
| 205 | delete(c.entries, e.docID) |
| 206 | e.bytes, e.kept = 0, false |
| 207 | if e.mu.TryLock() { |
| 208 | e.close(ctx) |
| 209 | e.mu.Unlock() |
| 210 | return |
| 211 | } |
| 212 | e.dead = true |
| 213 | } |
| 214 | |
| 215 | // sweepLocked drops entries unused for c.idle (rule 7), except keep. |
| 216 | func (c *warmCache) sweepLocked(ctx context.Context, keep int64) { |
| 217 | cutoff := c.now().Add(-c.idle) |
| 218 | for id, e := range c.entries { |
| 219 | if id != keep && e.used.Before(cutoff) { |
| 220 | c.evictLocked(ctx, e) |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | // capLocked evicts least recently used entries until both caps hold. |
| 226 | // Only entries that keep a handle count: one waiting for its first replay |
| 227 | // holds nothing yet. |
| 228 | func (c *warmCache) capLocked(ctx context.Context) { |
| 229 | var total uint64 |
| 230 | list := make([]*warmEntry, 0, len(c.entries)) |
| 231 | for _, e := range c.entries { |
| 232 | if e.kept { |
| 233 | total += e.bytes |
| 234 | list = append(list, e) |
| 235 | } |
| 236 | } |
| 237 | if total <= c.maxBytes && len(list) <= c.maxHandles { |
| 238 | return |
| 239 | } |
| 240 | sort.Slice(list, func(i, j int) bool { return list[i].used.Before(list[j].used) }) |
| 241 | kept := len(list) |
| 242 | for _, e := range list { |
| 243 | if total <= c.maxBytes && kept <= c.maxHandles { |
| 244 | return |
| 245 | } |
| 246 | total -= e.bytes |
| 247 | kept-- |
| 248 | c.evictLocked(ctx, e) |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | // sweep is rule 7's entry point for the stream heartbeat. nil-safe. |
| 253 | func (c *warmCache) sweep(ctx context.Context) { |
| 254 | if c == nil { |
| 255 | return |
| 256 | } |
| 257 | c.mu.Lock() |
| 258 | c.sweepLocked(ctx, 0) |
| 259 | c.mu.Unlock() |
| 260 | } |
| 261 | |
| 262 | // drop forgets docID's handle (rule 6). nil-safe. |
| 263 | func (c *warmCache) drop(ctx context.Context, docID int64) { |
| 264 | if c == nil { |
| 265 | return |
| 266 | } |
| 267 | c.mu.Lock() |
| 268 | if e := c.entries[docID]; e != nil { |
| 269 | c.evictLocked(ctx, e) |
| 270 | } |
| 271 | c.mu.Unlock() |
| 272 | } |
| 273 | |
| 274 | // close drops every handle and keeps no more (drain, shutdown). nil-safe. |
| 275 | func (c *warmCache) close(ctx context.Context) { |
| 276 | if c == nil { |
| 277 | return |
| 278 | } |
| 279 | c.mu.Lock() |
| 280 | c.closed = true |
| 281 | for _, e := range c.entries { |
| 282 | c.evictLocked(ctx, e) |
| 283 | } |
| 284 | c.mu.Unlock() |
| 285 | } |
| 286 | |
| 287 | // stats reports how many handles are kept and their bytes (tests, probes). |
| 288 | func (c *warmCache) stats() (handles int, bytes uint64) { |
| 289 | if c == nil { |
| 290 | return 0, 0 |
| 291 | } |
| 292 | c.mu.Lock() |
| 293 | defer c.mu.Unlock() |
| 294 | for _, e := range c.entries { |
| 295 | if e.kept { |
| 296 | handles++ |
| 297 | bytes += e.bytes |
| 298 | } |
| 299 | } |
| 300 | return handles, bytes |
| 301 | } |
| 302 | |
| 303 | // applyWarm is ApplyUpdate with a warm handle (rules 1–4). The caller has |
| 304 | // checked write permission. |
| 305 | func (s *Store) applyWarm(ctx context.Context, doc *Document, actor Actor, update []byte) (int64, error) { |
| 306 | e := s.warm.acquire(ctx, doc.ID) |
| 307 | if e == nil { |
| 308 | return s.applyCold(ctx, doc, actor, update) |
| 309 | } |
| 310 | defer s.warm.release(ctx, e) |
| 311 | |
| 312 | if e.h == nil { |
| 313 | h, replayedSeq, lastSnapshotSeq, err := s.replay(ctx, doc) |
| 314 | if err != nil { |
| 315 | return 0, err |
| 316 | } |
| 317 | e.h, e.seq, e.snap = h, replayedSeq, lastSnapshotSeq |
| 318 | s.warm.counts.replays.Add(1) |
| 319 | } else { |
| 320 | s.warm.counts.hits.Add(1) |
| 321 | } |
| 322 | |
| 323 | // Rule 4, with D3's placement: the snapshot is the state before this |
| 324 | // update, at the handle's seq. |
| 325 | reseed := false |
| 326 | if e.seq-e.snap >= snapshotCadence { |
| 327 | if err := s.writeSnapshot(ctx, doc, e.h, e.seq); err != nil { |
| 328 | if s.team != nil { |
| 329 | // As the cold path: in team mode the POST fails. The |
| 330 | // handle is unchanged (a snapshot only reads it). |
| 331 | if errors.Is(err, ErrNotWritable) { |
| 332 | return 0, err |
| 333 | } |
| 334 | return 0, errTeamUnavailable |
| 335 | } |
| 336 | s.logger.Error("docs: write snapshot", "doc_id", doc.ID, "seq", e.seq, "err", err) |
| 337 | } else { |
| 338 | e.snap = e.seq |
| 339 | reseed = true |
| 340 | s.warm.counts.reseeds.Add(1) |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | e.pending = true |
| 345 | if err := s.warmApply(ctx, e.h, update); err != nil { |
| 346 | // Rule 2: ANY error from Apply drops the handle. A rejection is not |
| 347 | // clean: yrs integrates an update's structs one at a time, and a |
| 348 | // later struct refused (InvalidParent, ERR_APPLY) leaves the earlier |
| 349 | // ones in the store, which the core's transaction then commits |
| 350 | // (review finding 1). The cold path threw that handle away; so does |
| 351 | // this one. A rejection costs one replay on the next POST. |
| 352 | e.close(ctx) |
| 353 | var rejected *core.RejectedError |
| 354 | if errors.As(err, &rejected) { |
| 355 | return 0, fmt.Errorf("docs: apply update to document %d: %w", doc.ID, &updateRejection{err}) |
| 356 | } |
| 357 | if ctx.Err() != nil { |
| 358 | // The client went away mid-Apply: not a sick handle, and a cold |
| 359 | // retry would fail on the same context (finding 7). |
| 360 | return 0, fmt.Errorf("docs: apply update to document %d: %w", doc.ID, ctx.Err()) |
| 361 | } |
| 362 | // A full log, a trap or a recovered instance: redo it cold. |
| 363 | s.logger.Warn("docs: warm handle dropped, replaying", "doc_id", doc.ID, "err", err) |
| 364 | return s.applyCold(ctx, doc, actor, update) |
| 365 | } |
| 366 | |
| 367 | seq, before, err := s.commitUpdate(ctx, doc, actor, update) |
| 368 | if err != nil { |
| 369 | e.close(ctx) // rule 3: applied, not committed |
| 370 | return 0, err |
| 371 | } |
| 372 | e.pending = false |
| 373 | if before != e.seq { |
| 374 | s.warm.counts.stale.Add(1) |
| 375 | } |
| 376 | if before != e.seq || reseed { |
| 377 | e.close(ctx) // rule 3 (stale) or rule 4 (re-seed) |
| 378 | } else { |
| 379 | e.seq = seq |
| 380 | } |
| 381 | return seq, nil |
| 382 | } |
| 383 | |
| 384 | // warmApply is Handle.Apply, behind a seam the tests use to inject the |
| 385 | // failures rule 2 is about. |
| 386 | func (s *Store) warmApply(ctx context.Context, h *core.Handle, update []byte) error { |
| 387 | if s.warmApplyHook != nil { |
| 388 | if err := s.warmApplyHook(h); err != nil { |
| 389 | return err |
| 390 | } |
| 391 | } |
| 392 | return h.Apply(ctx, update) |
| 393 | } |
| 394 | |
| 395 | // boundTo returns a copy of s whose queries run in tx, without warm |
| 396 | // handles (see this file's header): the agent paths' ApplyUpdate commits a |
| 397 | // savepoint the caller can still roll back. |
| 398 | func (s *Store) boundTo(tx *gorm.DB) *Store { |
| 399 | c := *s |
| 400 | c.db = tx |
| 401 | c.warm = nil |
| 402 | return &c |
| 403 | } |
| 404 | |
| 405 | // ParseWarmHandle reads $DOCS_WARM_HANDLE: on/off (also 1/0, true/false); |
| 406 | // unset is off. Anything else is a startup refusal rather than a guess. |
| 407 | func ParseWarmHandle(v string) (bool, error) { return parseOnOff("DOCS_WARM_HANDLE", v) } |
| 408 | |
| 409 | func parseOnOff(name, v string) (bool, error) { |
| 410 | switch v { |
| 411 | case "", "off", "0", "false": |
| 412 | return false, nil |
| 413 | case "on", "1", "true": |
| 414 | return true, nil |
| 415 | } |
| 416 | return false, fmt.Errorf("docs: %s must be on or off, not %q", name, v) |
| 417 | } |
| 418 | |