oficina / docs Public

Live push 1b: far behind is decided from lengths, before any bytes (#175 finding 2)

rowsAfter read, opened and cached up to 257 rows (each up to 1 MiB)
before pushFrames measured them and sent one update. It now takes the
far-behind exit from the row count and the rows' stored lengths (SELECT
seq, LENGTH(update_bin)), before reading any row's bytes; a row too large
to push is never loaded, and the frame cache never keeps a row over
32 KiB. The first row a stream cannot push ends its flush with one update
for the current seq (the client's fetch from its cursor brings it and the
rest), instead of an update per row.

TestPushFarBehindReadsNoBytes: 20 rows of 33 KiB, then a stream from 0,
gets one update with no row read or opened and nothing oversized cached;
300 rows behind reads nothing either. Before the fix: 20 rows read.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 3feb582ff94c0f6cb9841d77a93dc876ca559df3 parent 946c4ae
3 files changed, +135 −43
  • internal/docs/push.go +88 −41
  • internal/docs/push_test.go +45 −0
  • internal/docs/stream.go +2 −2
diff --git a/internal/docs/push.go b/internal/docs/push.go
index 52b031a..9344581 100644
--- a/internal/docs/push.go
+++ b/internal/docs/push.go
@@ -220,64 +220,111 @@ func (c *frameCache) put(seq int64, b []byte) {
}
}
-// pushRow is one row read for a stream: its bytes, or why it has none.
+// pushRow is one row for a stream: its bytes, or why it has none.
type pushRow struct {
seq int64
bytes []byte
unusable bool // could not be opened
+ tooLarge bool // over pushMaxRowBytes: goes as update, never loaded
}
-// rowsAfter reads doc's rows after sent, in seq order, at most
-// pushMaxBehindRow+1 of them, through cache when it has them all. The
-// query and the opening are updatesGet's (§3.1: one code path for bytes).
-func (h *handlers) rowsAfter(ctx context.Context, doc *Document, sent int64, cache *frameCache) ([]pushRow, int64, error) {
- var current int64
- if err := h.store.db.WithContext(ctx).Model(&DocUpdate{}).Where("doc_id = ?", doc.ID).Select("COALESCE(MAX(seq), 0)").Scan(&current).Error; err != nil {
- return nil, 0, err
+// pushSealSlack is how much longer a stored (sealed) row may be than its
+// update: the length check before loading is on the stored bytes.
+const pushSealSlack = 256
+
+// rowsAfter returns doc's rows after sent, in seq order, and the log's
+// current seq. far reports a stream more than pushMaxBehindRow rows or
+// pushMaxBehind bytes behind: no rows are returned and none was read. The
+// decision is made from the rows' count and stored lengths before any
+// row's bytes are read or opened, and a row too large to push is never
+// loaded (#175 finding 2). The rest come through cache when it holds them
+// all, otherwise with updatesGet's query and opening (§3.1).
+func (h *handlers) rowsAfter(ctx context.Context, doc *Document, sent int64, cache *frameCache) (rows []pushRow, current int64, far bool, err error) {
+ db := h.store.db.WithContext(ctx)
+ if err = db.Model(&DocUpdate{}).Where("doc_id = ?", doc.ID).Select("COALESCE(MAX(seq), 0)").Scan(&current).Error; err != nil {
+ return nil, 0, false, err
}
if current <= sent {
- return nil, current, nil
+ return nil, current, false, nil
+ }
+ if current-sent > pushMaxBehindRow {
+ return nil, current, true, nil
}
- if cache != nil && current-sent <= pushMaxBehindRow {
- rows := make([]pushRow, 0, current-sent)
+ if cache != nil {
+ rows = make([]pushRow, 0, current-sent)
+ total := 0
for seq := sent + 1; seq <= current; seq++ {
b, ok := cache.get(seq)
if !ok {
rows = nil
break
}
+ total += len(b)
rows = append(rows, pushRow{seq: seq, bytes: b})
}
if rows != nil {
- if h.pushStats != nil {
- h.pushStats.cacheHits.Add(int64(len(rows)))
+ if total > pushMaxBehind {
+ return nil, current, true, nil
}
- return rows, current, nil
+ h.pushStats.cacheHits.Add(int64(len(rows)))
+ return rows, current, false, nil
}
}
- var updates []DocUpdate
- if err := h.store.db.WithContext(ctx).
+ var lengths []struct {
+ Seq int64
+ N int64
+ }
+ if err = db.Model(&DocUpdate{}).Select("seq, LENGTH(update_bin) AS n").
Where("doc_id = ? AND seq > ? AND seq <= ?", doc.ID, sent, current).
- Order("seq ASC").Limit(pushMaxBehindRow + 1).
- Find(&updates).Error; err != nil {
- return nil, 0, err
+ Order("seq ASC").Scan(&lengths).Error; err != nil {
+ return nil, 0, false, err
}
- if h.pushStats != nil {
- h.pushStats.rowReads.Add(int64(len(updates)))
+ var total int64
+ var small []int64
+ for _, l := range lengths {
+ if l.N <= pushMaxRowBytes+pushSealSlack {
+ total += l.N
+ small = append(small, l.Seq)
+ }
}
- rows := make([]pushRow, 0, len(updates))
- for i := range updates {
- u := &updates[i]
- if err := h.store.openContentUpdate(doc.GUID, u); err != nil {
- rows = append(rows, pushRow{seq: u.Seq, unusable: true})
- continue
+ if total > pushMaxBehind+int64(len(small))*pushSealSlack {
+ return nil, current, true, nil
+ }
+ loaded := map[int64][]byte{}
+ unusable := map[int64]bool{}
+ if len(small) > 0 {
+ var updates []DocUpdate
+ if err = db.Where("doc_id = ? AND seq IN ?", doc.ID, small).Find(&updates).Error; err != nil {
+ return nil, 0, false, err
+ }
+ h.pushStats.rowReads.Add(int64(len(updates)))
+ for i := range updates {
+ u := &updates[i]
+ if err := h.store.openContentUpdate(doc.GUID, u); err != nil {
+ unusable[u.Seq] = true
+ continue
+ }
+ loaded[u.Seq] = u.UpdateBin
+ if cache != nil && len(u.UpdateBin) <= pushMaxRowBytes {
+ cache.put(u.Seq, u.UpdateBin)
+ }
}
- if cache != nil {
- cache.put(u.Seq, u.UpdateBin)
+ }
+ rows = make([]pushRow, 0, len(lengths))
+ for _, l := range lengths {
+ b, ok := loaded[l.Seq]
+ switch {
+ case ok && len(b) <= pushMaxRowBytes:
+ rows = append(rows, pushRow{seq: l.Seq, bytes: b})
+ case ok:
+ rows = append(rows, pushRow{seq: l.Seq, tooLarge: true})
+ case unusable[l.Seq]:
+ rows = append(rows, pushRow{seq: l.Seq, unusable: true})
+ default:
+ rows = append(rows, pushRow{seq: l.Seq, tooLarge: true})
}
- rows = append(rows, pushRow{seq: u.Seq, bytes: u.UpdateBin})
}
- return rows, current, nil
+ return rows, current, false, nil
}
// pushFrames renders rows as frames for stream id (§3.1): own for an update
@@ -286,24 +333,24 @@ func (h *handlers) rowsAfter(ctx context.Context, doc *Document, sent int64, cac
// than pushMaxBehindRow rows or pushMaxBehind bytes) is one update for the
// log's current seq. It returns the text to write in one flush and the new
// cursor.
-func (h *handlers) pushFrames(docID int64, id string, rows []pushRow, current, sent int64) (string, int64) {
+func (h *handlers) pushFrames(docID int64, id string, rows []pushRow, current, sent int64, far bool) (string, int64) {
+ if far {
+ return "event: update\ndata: " + strconv.FormatInt(current, 10) + "\n\n", current
+ }
if len(rows) == 0 {
return "", sent
}
- total := 0
- for _, r := range rows {
- total += len(r.bytes)
- }
last := rows[len(rows)-1].seq
- if len(rows) > pushMaxBehindRow || total > pushMaxBehind {
- return "event: update\ndata: " + strconv.FormatInt(current, 10) + "\n\n", current
- }
var b strings.Builder
for _, r := range rows {
seq := strconv.FormatInt(r.seq, 10)
switch o, ok := h.pushRegistry.lookup(docID, r.seq); {
- case r.unusable || len(r.bytes) > pushMaxRowBytes:
- b.WriteString("event: update\ndata: " + seq + "\n\n")
+ case r.unusable || r.tooLarge || len(r.bytes) > pushMaxRowBytes:
+ // The client fetches from its cursor, which brings this row and
+ // everything after it: one update for the current seq ends the
+ // flush, rather than an update per remaining row.
+ b.WriteString("event: update\ndata: " + strconv.FormatInt(current, 10) + "\n\n")
+ return b.String(), current
case ok && o.stream == id && o.hash == sha256.Sum256(r.bytes):
b.WriteString("id: " + seq + "\nevent: own\ndata: " + seq + " " + o.counter + "\n\n")
default:
diff --git a/internal/docs/push_test.go b/internal/docs/push_test.go
index 211296a..040c7cc 100644
--- a/internal/docs/push_test.go
+++ b/internal/docs/push_test.go
@@ -1037,3 +1037,48 @@ func TestLateAnswersIgnoreAppendedCookies(t *testing.T) {
}
}
}
+
+// #175 finding 2: a stream that will get a single update (too far behind,
+// or rows too large to push) learns so from the rows' lengths, before any
+// row's bytes are read or opened, and the frame cache never keeps a row it
+// could not push.
+func TestPushFarBehindReadsNoBytes(t *testing.T) {
+ f := newPushFixture(t, pushOn())
+ for k := 1; k <= 20; k++ {
+ f.post(f.cookies, f.update(k, strings.Repeat(fmt.Sprint(k%10), pushMaxRowBytes+1024)), "")
+ }
+ reads := f.app.handlers.pushStats.rowReads.Load()
+ s := f.open(f.cookies, "?push=1&since=0", nil)
+ s.hello(t)
+ if fr := s.next(t); fr.event != "update" || fr.data != "20" {
+ t.Fatalf("%+v, want update 20", fr)
+ }
+ if n := f.app.handlers.pushStats.rowReads.Load() - reads; n != 0 {
+ t.Fatalf("%d rows read and opened for a stream that got one update", n)
+ }
+ f.app.handlers.pushRegistry.mu.Lock()
+ for _, c := range f.app.handlers.pushRegistry.frames {
+ c.mu.Lock()
+ for seq, b := range c.rows {
+ if len(b) > pushMaxRowBytes {
+ t.Errorf("the frame cache holds row %d (%d bytes)", seq, len(b))
+ }
+ }
+ c.mu.Unlock()
+ }
+ f.app.handlers.pushRegistry.mu.Unlock()
+
+ g := newPushFixture(t, pushOn())
+ for k := 1; k <= pushMaxBehindRow+44; k++ {
+ g.post(g.cookies, g.update(k, fmt.Sprint("r", k)), "")
+ }
+ reads = g.app.handlers.pushStats.rowReads.Load()
+ behind := g.open(g.cookies, "?push=1&since=0", nil)
+ behind.hello(t)
+ if fr := behind.next(t); fr.event != "update" {
+ t.Fatalf("%+v, want update", fr)
+ }
+ if n := g.app.handlers.pushStats.rowReads.Load() - reads; n != 0 {
+ t.Fatalf("%d rows read for a stream %d rows behind", n, pushMaxBehindRow+44)
+ }
+}
diff --git a/internal/docs/stream.go b/internal/docs/stream.go
index 9bb64af..b416b2b 100644
--- a/internal/docs/stream.go
+++ b/internal/docs/stream.go
@@ -220,12 +220,12 @@ func (h *handlers) stream(w http.ResponseWriter, r *http.Request) {
defer h.pushRegistry.releaseCache(doc.ID)
}
flushFrames = func() bool {
- rows, current, err := h.rowsAfter(r.Context(), doc, sent, cache)
+ rows, current, far, err := h.rowsAfter(r.Context(), doc, sent, cache)
if err != nil {
h.logger.Error("docs: stream: read rows", "sqid", doc.Sqid, "err", err)
return false
}
- text, next := h.pushFrames(doc.ID, streamID, rows, current, sent)
+ text, next := h.pushFrames(doc.ID, streamID, rows, current, sent, far)
if text == "" {
return true
}