oficina / docs Public

Live push 1b: the server checks a resumed cursor against the row it names (#175 findings 3, 5)

The log epoch misses the likeliest restore: a Litestream point-in-time
restore is from after the last start, and a volume snapshot carries the
file beside the database, so the epoch is kept and a client whose cursor
the restored log has passed again silently skips the new rows. Push and
own frames now carry id <seq>.<tag> (tag: 16 hex digits of SHA-256 over
the seq and the row's bytes), fetches carry Docs-Seq-Tag, and a resume
that names its cursor's tag (Last-Event-ID <seq>.<tag>, or since=&tag=) is
checked against the row the log holds at that seq: another tag, a missing
row, or a cursor ahead of the log answers event: resync <current> and ends
the stream. A cursor without a tag is checked by seq and epoch only.
Spec §3.1 amended.

Tests: TestPushRestoredLogIsDetected (database and its file copied at seq 3,
rows 4-5 written and held by a client, the copy restored in place, two
different rows written so the log is back at 5: the client resuming at 5
is told to resync); TestPushFramesCarryTheRowsTag (frame tags, the fetch
header, resume by tag both ways, a wrong tag resyncs);
TestPushCursorAheadOfTheLogResyncs. All three failed before (no tag; the
restored and ahead cursors were accepted in silence).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev b597ebd7d6b47692f69f8e966e58d466570a6509 parent 3feb582
5 files changed, +219 −13
  • docs/superpowers/specs/2026-11-26-live-push-design.md +30 −5
  • internal/docs/handlers.go +10 −1
  • internal/docs/push.go +35 −2
  • internal/docs/push_test.go +116 −3
  • internal/docs/stream.go +28 −2
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 b871881..60574dc 100644
--- a/docs/superpowers/specs/2026-11-26-live-push-design.md
+++ b/docs/superpowers/specs/2026-11-26-live-push-design.md
@@ -247,27 +247,39 @@ A client that understands push asks for it:
event: hello
data: <stream id> <the log's current seq> <log epoch>
-id: 43
+id: 43.<tag>
event: push
data: 43 <base64 of row 43's bytes>
-id: 44
+id: 44.<tag>
event: own
data: 44 <the client's counter from Docs-Stream>
event: update
data: 45
+event: resync
+data: <the log's current seq>
+
event: bye
data: <reason: ttl | lease | drain>
```
+The `<tag>` is the row's digest (16 hex digits of SHA-256 over its seq and
+bytes; branch review #175, finding 3, below).
+
- `push` carries a row this client did not post. `own` marks one it did
(§3.4); no bytes. `update` is today's seq-only event. The server sends it
instead of `push` for a row over **32 KiB**, a row it cannot open, or a
client more than **256 rows / 512 KiB** behind. The client then fetches
`?since=` as today. `update` frames never carry `id:`, because their bytes
were not delivered.
+- **As built:**
+ - The far-behind case is decided from the rows' count and stored lengths
+ before any row is read, and a row too large to push is never loaded or
+ cached.
+ - The first row a flush cannot push ends it with one `update <current>`,
+ since the client's fetch brings that row and everything after it.
- **Reading.** The stream reads rows with the same query and
`openContentUpdate` as `updatesGet` (`seq > sent ORDER BY seq`, log rows
only, never a snapshot). Seq is `MAX+1` inside the single-writer
@@ -284,9 +296,22 @@ data: <reason: ttl | lease | drain>
failed to advance). `hello` always comes first.
- **A rewound log** (the database restored from a backup, a team
re-provisioned, a later version restore). The client resyncs from 0 (the
- web's resync controller; native's catch-up from the start) when either:
- - `hello`'s seq is below its cursor; or
- - `hello`'s **log epoch** differs from the one it holds.
+ web's resync controller; native's catch-up from the start) when any of
+ these holds:
+ - `hello`'s seq is below its cursor;
+ - `hello`'s **log epoch** differs from the one it holds;
+ - the stream sends **`resync`** (the server's own check, below).
+- **The server checks the cursor itself** (branch review #175, findings 3
+ and 5), because the epoch misses the likeliest restore. A Litestream
+ point-in-time restore is from after the last start, and a volume
+ snapshot carries the file beside the database. So:
+ - push and own frames carry `id: <seq>.<tag>`;
+ - fetch responses carry `Docs-Seq-Tag` for the row their `Docs-Seq` names;
+ - a resume names its cursor's tag (`Last-Event-ID: <seq>.<tag>`, which
+ `EventSource` sends by itself, or `since=<seq>&tag=<tag>`);
+ - the stream answers `resync` and ends when the row it holds at that seq
+ has another tag or is missing, and when the cursor is ahead of the log;
+ - a cursor without a tag is checked by seq and epoch only.
The seq alone misses a restore that new commits have already passed: a
log restored to 90, twenty new commits, and a client at 100 sees 110 and
diff --git a/internal/docs/handlers.go b/internal/docs/handlers.go
index c64cf10..cf2fcbe 100644
--- a/internal/docs/handlers.go
+++ b/internal/docs/handlers.go
@@ -948,8 +948,17 @@ func (h *handlers) updatesGet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Docs-Seq", strconv.FormatInt(highest, 10))
if h.livePush {
// A non-push client can check its cursor against the log's
- // identity on its next fetch (§3.1, a rewound log).
+ // identity on its next fetch (§3.1, a rewound log), and learns the
+ // tag of the row its new cursor names, for a push stream's resume.
w.Header().Set("Docs-Log-Epoch", h.store.logEpoch)
+ if n := len(updates); n > 0 && updates[n-1].Seq == highest {
+ w.Header().Set("Docs-Seq-Tag", pushTag(highest, updates[n-1].UpdateBin))
+ } else if highest > 0 {
+ var row []DocUpdate
+ if err := h.store.db.WithContext(r.Context()).Where("doc_id = ? AND seq = ?", doc.ID, highest).Limit(1).Find(&row).Error; err == nil && len(row) == 1 && h.store.openContentUpdate(doc.GUID, &row[0]) == nil {
+ w.Header().Set("Docs-Seq-Tag", pushTag(highest, row[0].UpdateBin))
+ }
+ }
}
parts := make([][]byte, 0, len(updates)+1)
if snapshot != nil {
diff --git a/internal/docs/push.go b/internal/docs/push.go
index 9344581..5654d77 100644
--- a/internal/docs/push.go
+++ b/internal/docs/push.go
@@ -352,9 +352,9 @@ func (h *handlers) pushFrames(docID int64, id string, rows []pushRow, current, s
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")
+ b.WriteString("id: " + seq + "." + pushTag(r.seq, r.bytes) + "\nevent: own\ndata: " + seq + " " + o.counter + "\n\n")
default:
- b.WriteString("id: " + seq + "\nevent: push\ndata: " + seq + " ")
+ b.WriteString("id: " + seq + "." + pushTag(r.seq, r.bytes) + "\nevent: push\ndata: " + seq + " ")
b.WriteString(base64.StdEncoding.EncodeToString(r.bytes))
b.WriteString("\n\n")
}
@@ -459,3 +459,36 @@ func (l *lateAnswers) admit(ctx context.Context, draining <-chan struct{}, sessi
type pushStats struct {
rowReads, cacheHits, frames atomic.Int64
}
+
+// pushTag is a row's short digest: 16 hex digits of SHA-256 over its seq
+// and its bytes. Push and own frames carry it in their id (<seq>.<tag>),
+// fetches in Docs-Seq-Tag, and a resume names the tag of its cursor's row,
+// so the server can tell a cursor into a log that has since been rewound
+// and rewritten (a restore that the epoch did not catch) from one into this
+// log (#175 finding 3).
+func pushTag(seq int64, b []byte) string {
+ h := sha256.New()
+ var n [8]byte
+ for i := 0; i < 8; i++ {
+ n[i] = byte(seq >> (56 - 8*i))
+ }
+ h.Write(n[:])
+ h.Write(b)
+ return hex.EncodeToString(h.Sum(nil))[:16]
+}
+
+// cursorMatches reports whether row seq of doc is the row tag was taken
+// from: the resume check (#175 finding 3). A missing row does not match.
+func (h *handlers) cursorMatches(ctx context.Context, doc *Document, seq int64, tag string) (bool, error) {
+ var rows []DocUpdate
+ if err := h.store.db.WithContext(ctx).Where("doc_id = ? AND seq = ?", doc.ID, seq).Limit(1).Find(&rows).Error; err != nil {
+ return false, err
+ }
+ if len(rows) == 0 {
+ return false, nil
+ }
+ if err := h.store.openContentUpdate(doc.GUID, &rows[0]); err != nil {
+ return false, err
+ }
+ return pushTag(seq, rows[0].UpdateBin) == tag, nil
+}
diff --git a/internal/docs/push_test.go b/internal/docs/push_test.go
index 040c7cc..f2530a2 100644
--- a/internal/docs/push_test.go
+++ b/internal/docs/push_test.go
@@ -96,7 +96,7 @@ func (f *pushFixture) post(cookies []*http.Cookie, update []byte, docsStream str
return res.StatusCode, seq
}
-type frame struct{ id, event, data string }
+type frame struct{ id, tag, event, data string }
// testStream is an open stream with a frame reader.
type testStream struct {
@@ -140,7 +140,7 @@ func (f *pushFixture) open(cookies []*http.Cookie, query string, header map[stri
switch {
case strings.HasPrefix(line, ":"):
case strings.HasPrefix(line, "id: "):
- fr.id = line[4:]
+ fr.id, fr.tag, _ = strings.Cut(line[4:], ".")
case strings.HasPrefix(line, "event: "):
fr.event = line[7:]
case strings.HasPrefix(line, "data: "):
@@ -806,7 +806,7 @@ func (f *pushFixture) openClient(client *http.Client, query string) *testStream
line = strings.TrimRight(line, "\r\n")
switch {
case strings.HasPrefix(line, "id: "):
- fr.id = line[4:]
+ fr.id, fr.tag, _ = strings.Cut(line[4:], ".")
case strings.HasPrefix(line, "event: "):
fr.event = line[7:]
case strings.HasPrefix(line, "data: "):
@@ -1082,3 +1082,116 @@ func TestPushFarBehindReadsNoBytes(t *testing.T) {
t.Fatalf("%d rows read for a stream %d rows behind", n, pushMaxBehindRow+44)
}
}
+
+// #175 finding 3: push and own frames carry id <seq>.<tag>, the tag a digest
+// of the row; fetches carry Docs-Seq-Tag. A resume names its cursor's tag,
+// and the server checks it against the row it holds.
+func TestPushFramesCarryTheRowsTag(t *testing.T) {
+ f := newPushFixture(t, pushOn())
+ s := f.open(f.cookies, "?push=1&since=0", nil)
+ s.hello(t)
+ u := f.update(1, "tagged")
+ f.post(f.cookies, u, "")
+ fr := s.next(t)
+ if fr.event != "push" || fr.id != "1" || fr.tag != pushTag(1, u) {
+ t.Fatalf("%+v, want push 1 with tag %s", fr, pushTag(1, u))
+ }
+ rec := httptest.NewRecorder()
+ f.app.Handler().ServeHTTP(rec, f.app.TestRequest(t, "owner@example.com", http.MethodGet, "/d/"+f.doc.Sqid+"/updates?since=0", nil))
+ if got := rec.Header().Get("Docs-Seq-Tag"); got != pushTag(1, u) {
+ t.Fatalf("Docs-Seq-Tag %q, want %q", got, pushTag(1, u))
+ }
+ f.post(f.cookies, f.update(2, "next"), "")
+ good := f.open(f.cookies, "?push=1&since=1&tag="+pushTag(1, u), nil)
+ good.hello(t)
+ if fr := good.next(t); fr.event != "push" || fr.id != "2" {
+ t.Fatalf("resume with the right tag: %+v", fr)
+ }
+ viaHeader := f.open(f.cookies, "?push=1", map[string]string{"Last-Event-ID": "1." + pushTag(1, u)})
+ viaHeader.hello(t)
+ if fr := viaHeader.next(t); fr.event != "push" || fr.id != "2" {
+ t.Fatalf("resume by Last-Event-ID seq.tag: %+v", fr)
+ }
+ bad := f.open(f.cookies, "?push=1&since=1&tag=0000000000000000", nil)
+ bad.hello(t)
+ if fr := bad.next(t); fr.event != "resync" {
+ t.Fatalf("resume with a wrong tag: %+v, want resync", fr)
+ }
+}
+
+// #175 finding 3, the restore it is for: the database and the file beside
+// it copied at seq 3, rows 4 and 5 written (a client holds 5), the copy
+// restored in place (so the epoch is kept), and two different rows written,
+// so the log is back at 5. A client resuming at 5 with row 5's tag must be
+// told to resync; its 4 and 5 are not the log's.
+func TestPushRestoredLogIsDetected(t *testing.T) {
+ dir := t.TempDir()
+ cfg := Config{DBPath: filepath.Join(dir, "docs.db"), Env: "development", LivePush: true}
+ open := func() *pushFixture {
+ app, err := New(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { app.Close() })
+ srv := httptest.NewServer(app.Handler())
+ t.Cleanup(srv.Close)
+ f := &pushFixture{t: t, app: app, srv: srv, ctx: context.Background()}
+ f.owner = app.TestPerson(t, "owner@example.com")
+ docs, err := app.Store().List(f.ctx, f.owner)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, d := range docs {
+ if d.Title == "Restored" {
+ f.doc = d
+ }
+ }
+ if f.doc == nil {
+ if f.doc, err = app.Store().Create(f.ctx, f.owner, "Restored"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ f.cookies = f.session("owner@example.com")
+ return f
+ }
+ f := open()
+ for k := 1; k <= 3; k++ {
+ f.post(f.cookies, f.update(k, fmt.Sprint("before", k)), "")
+ }
+ f.app.Close()
+ backup := copyDB(t, cfg.DBPath, filepath.Join(dir, "backup.db"))
+ sidecar, _ := os.ReadFile(cfg.DBPath + ".log-epoch")
+ f = open()
+ var held []byte
+ for k := 4; k <= 5; k++ {
+ held = f.update(k, fmt.Sprint("lost", k))
+ f.post(f.cookies, held, "")
+ }
+ tag := pushTag(5, held)
+ f.app.Close()
+ restoreDB(t, backup, cfg.DBPath)
+ os.WriteFile(cfg.DBPath+".log-epoch", sidecar, 0600) // a volume snapshot carries it along
+ f = open()
+ for k := 6; k <= 7; k++ {
+ f.post(f.cookies, f.update(k, fmt.Sprint("after", k)), "")
+ }
+ s := f.open(f.cookies, "?push=1&since=5&tag="+tag, nil)
+ _, seq, _ := s.hello(t)
+ if seq != 5 {
+ t.Fatalf("the restored log is at %d, want 5 (the case the seq check cannot see)", seq)
+ }
+ if fr := s.next(t); fr.event != "resync" {
+ t.Fatalf("%+v: a client whose 4 and 5 are not the log's was not told to resync", fr)
+ }
+}
+
+// #175 finding 5: a cursor ahead of the log is told to resync, not accepted.
+func TestPushCursorAheadOfTheLogResyncs(t *testing.T) {
+ f := newPushFixture(t, pushOn())
+ f.post(f.cookies, f.update(1, "one"), "")
+ s := f.open(f.cookies, "?push=1&since=99", nil)
+ s.hello(t)
+ if fr := s.next(t); fr.event != "resync" || fr.data != "1" {
+ t.Fatalf("%+v, want resync 1", fr)
+ }
+}
diff --git a/internal/docs/stream.go b/internal/docs/stream.go
index b416b2b..b8078e2 100644
--- a/internal/docs/stream.go
+++ b/internal/docs/stream.go
@@ -5,6 +5,7 @@ import (
"io"
"net/http"
"strconv"
+ "strings"
"time"
"amadan.net/rastrillo/rastrillo"
@@ -143,18 +144,25 @@ func (h *handlers) stream(w http.ResponseWriter, r *http.Request) {
// Where a push stream starts: Last-Event-ID (EventSource sends it on its
// own reconnects) wins over since; garbage in either is a 400, as
// parseSince answers. With neither, it starts at the current seq.
- start, resume := current, false
+ // A cursor may name its row's tag (<seq>.<tag> in Last-Event-ID, or
+ // since=<seq>&tag=<tag>), which the stream checks below.
+ start, resume, tag := current, false, ""
if push {
raw := r.Header.Get("Last-Event-ID")
if raw == "" {
raw = r.URL.Query().Get("since")
+ tag = r.URL.Query().Get("tag")
}
if raw != "" {
- n, err := strconv.ParseInt(raw, 10, 64)
+ seqText, rawTag, _ := strings.Cut(raw, ".")
+ n, err := strconv.ParseInt(seqText, 10, 64)
if err != nil || n < 0 {
http.Error(w, rastrillo.T(r, "docs.error.badsince"), http.StatusBadRequest)
return
}
+ if rawTag != "" {
+ tag = rawTag
+ }
start, resume = n, true
}
}
@@ -247,6 +255,14 @@ func (h *handlers) stream(w http.ResponseWriter, r *http.Request) {
}
if push && resume {
+ // A cursor this log cannot vouch for resyncs from the start rather
+ // than resume (#175 findings 3 and 5): one ahead of the log, or one
+ // whose row's tag does not match the row this log holds at that seq
+ // (a restore the epoch did not catch, then rewritten past it).
+ if start > current || (tag != "" && start > 0 && !h.cursorHeld(r, doc, start, tag)) {
+ write("event: resync\ndata: " + strconv.FormatInt(current, 10) + "\n\n")
+ return
+ }
// What the client missed since its cursor arrives as frames: the
// connect-time fetch goes away.
if !flushFrames() {
@@ -337,3 +353,13 @@ func (h *handlers) ttlInterval() time.Duration {
}
return defaultStreamTTL
}
+
+// cursorHeld is cursorMatches for a stream; a read error counts as not
+// held, which resyncs (the safe direction).
+func (h *handlers) cursorHeld(r *http.Request, doc *Document, seq int64, tag string) bool {
+ ok, err := h.cursorMatches(r.Context(), doc, seq, tag)
+ if err != nil {
+ h.logger.Error("docs: stream: check cursor", "sqid", doc.Sqid, "err", err)
+ }
+ return ok
+}