carlos / platform Public

console: the reads route streams the read: result before listing, flushed lines, cancel on every end (plan 2, Task 7)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev f4271e7c92f99a70d81a957fc712b8d4c58ac8cc parent 67e39c0
2 files changed, +1,112 −3
  • internal/console/apidbforward.go +248 −3
  • internal/console/apidbforward_test.go +864 −0
diff --git a/internal/console/apidbforward.go b/internal/console/apidbforward.go
index cd8d834f1..7b5b74e2d 100644
--- a/internal/console/apidbforward.go
+++ b/internal/console/apidbforward.go
@@ -430,9 +430,254 @@ func (s *Server) admitDBRead(w http.ResponseWriter, r *http.Request) (dbReadAdmi
return dbReadAdmitted{id: id, region: rec.Region, issued: issued}, actor, true
}
-// streamDBRead is Task 7's.
-func (s *Server) streamDBRead(w http.ResponseWriter, _ *http.Request, _ *http.ResponseController, a dbReadAdmitted) {
+// errDBClientGone is a line the client did not take within s.dbf.stall.
+var errDBClientGone = errors.New("the client went or stalled")
+
+// dbfEndSlack is how far past the request's bound the last line may still be
+// written: room for the ended line, and no more.
+const dbfEndSlack = 10 * time.Second
+
+// dbLineWriter writes one line at a time, each under a fresh write deadline
+// and flushed under the same deadline (spec §5.5 step 6, codex 19). The
+// deadline never passes until, the request's bound plus dbfEndSlack (plan
+// review finding 12). A write or flush error ends the request as a stalled
+// client.
+type dbLineWriter struct {
+ w http.ResponseWriter
+ rc *http.ResponseController
+ stall time.Duration
+ until time.Time
+ last time.Time
+}
+
+func (l *dbLineWriter) write(line dbreads.Line) error {
+ b, err := json.Marshal(line)
+ if err != nil {
+ return err
+ }
+ dl := time.Now().Add(l.stall)
+ if dl.After(l.until) {
+ dl = l.until
+ }
+ if err := l.rc.SetWriteDeadline(dl); err != nil && !errors.Is(err, http.ErrNotSupported) {
+ return err
+ }
+ if _, err := l.w.Write(append(b, '\n')); err != nil {
+ return err
+ }
+ if err := l.rc.Flush(); err != nil {
+ return err
+ }
+ l.last = time.Now()
+ return nil
+}
+
+// tick waits one poll and writes a wait line when nothing has been written
+// for every. It answers ctx's error when ctx ends first, and errDBClientGone
+// when the line cannot be written.
+func (l *dbLineWriter) tick(ctx context.Context, phase string, poll, every time.Duration) error {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-time.After(poll):
+ }
+ if time.Since(l.last) >= every && l.write(dbreads.Line{Wait: phase}) != nil {
+ return errDBClientGone
+ }
+ return nil
+}
+
+// dbReadRelay is one admitted read's relay, with what its last log line
+// counts. (dbStream is apidb.go's streaming function: plan review finding 25.)
+type dbReadRelay struct {
+ s *Server
+ lw *dbLineWriter
+ chunks int
+ bytes int
+}
+
+// dbfCall runs one store call under s.dbf.call and the phase's context, and
+// keeps writing wait lines while it blocks, so a stalled store neither holds
+// the request past its phase nor silences the stream (plan review finding
+// 12). A store that ignores its context is left behind: its goroutine ends
+// when the call does, into a buffered channel nobody reads.
+func dbfCall[T any](st *dbReadRelay, ctx context.Context, phase string, op func(context.Context) (T, error)) (T, error) {
+ var zero T
+ cctx, cancel := context.WithTimeout(ctx, st.s.dbf.call)
+ defer cancel()
+ type outcome struct {
+ v T
+ err error
+ }
+ done := make(chan outcome, 1)
+ go func() {
+ v, err := op(cctx)
+ done <- outcome{v, err}
+ }()
+ t := time.NewTicker(st.s.dbf.poll)
+ defer t.Stop()
+ for {
+ select {
+ case o := <-done:
+ return o.v, o.err
+ case <-cctx.Done():
+ return zero, cctx.Err()
+ case <-t.C:
+ if time.Since(st.lw.last) >= st.s.dbf.wait && st.lw.write(dbreads.Line{Wait: phase}) != nil {
+ return zero, errDBClientGone
+ }
+ }
+ }
+}
+
+// readDBResult is result.json, or nil while there is none, and nil for one
+// that is not a result in the vocabulary (Review Focus 4).
+func (s *Server) readDBResult(ctx context.Context, id string) *dbreads.Result {
+ raw, _, err := s.cfg.Releases.Get(ctx, dbreads.ResultKey(id))
+ if err != nil {
+ return nil
+ }
+ var res dbreads.Result
+ if json.Unmarshal(raw, &res) != nil || res.Valid() != nil {
+ return nil
+ }
+ return &res
+}
+
+// streamDBRead is spec §5.5 steps 6 and 7 inside the admitted request:
+// admitted at once, picked once, then about once a second result.json first
+// and the chunk listing second (codex 20; the run follow door's order), each
+// chunk in sequence with no gaps, a wait line whenever s.dbf.wait passes
+// with nothing else, and the result last, only once every chunk through its
+// last_seq has been written. Each phase runs on its own deadline context:
+// pickup on issued_at plus s.dbf.pickup, the owner's on its deadline plus
+// s.dbf.grace, never later than s.dbf.bound after issued_at. It ends without
+// a result, and writes cancel, when either deadline passes, a result
+// included, or when the client goes or stalls. Its last log line is the
+// relay's own measure (plan review finding 21).
+func (s *Server) streamDBRead(w http.ResponseWriter, r *http.Request, rc *http.ResponseController, a dbReadAdmitted) {
+ ctx := r.Context()
+ bound := a.issued.Add(s.dbf.bound)
w.Header().Set("Content-Type", "application/x-ndjson")
+ w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(http.StatusOK)
- json.NewEncoder(w).Encode(dbreads.Line{Admitted: a.id})
+ st := &dbReadRelay{s: s, lw: &dbLineWriter{w: w, rc: rc, stall: s.dbf.stall, until: bound.Add(dbfEndSlack)}}
+ start, why := time.Now(), "client gone"
+ defer func() {
+ log.Printf("console: db read %s: relayed %d chunks (%d bytes) in %s, ended %s",
+ a.id, st.chunks, st.bytes, time.Since(start).Round(time.Millisecond), why)
+ }()
+ end := func(ended string) {
+ if ended != "" {
+ why = ended
+ st.lw.write(dbreads.Line{Ended: ended})
+ }
+ s.cancelDBRead(a.id)
+ }
+ // stop ends a phase: a client that went or stalled gets no line, a phase
+ // whose deadline passed gets its ended word.
+ stop := func(err error, ended string) {
+ if errors.Is(err, errDBClientGone) || ctx.Err() != nil {
+ end("")
+ return
+ }
+ end(ended)
+ }
+ if st.lw.write(dbreads.Line{Admitted: a.id}) != nil {
+ end("")
+ return
+ }
+ store := s.cfg.Releases
+
+ pickCtx, cancelPick := context.WithDeadline(ctx, a.issued.Add(s.dbf.pickup))
+ defer cancelPick()
+ var picked dbreads.Picked
+ for {
+ raw, err := dbfCall(st, pickCtx, dbreads.WaitPickup, func(c context.Context) ([]byte, error) {
+ b, _, err := store.Get(c, dbreads.PickedKey(a.id))
+ return b, err
+ })
+ if err == nil && json.Unmarshal(raw, &picked) == nil {
+ break
+ }
+ if pickCtx.Err() != nil || errors.Is(err, errDBClientGone) {
+ stop(err, dbreads.EndedNotPicked)
+ return
+ }
+ if err := st.lw.tick(pickCtx, dbreads.WaitPickup, s.dbf.poll, s.dbf.wait); err != nil {
+ stop(err, dbreads.EndedNotPicked)
+ return
+ }
+ }
+ if st.lw.write(dbreads.Line{Picked: picked.Box}) != nil {
+ end("")
+ return
+ }
+ deadline := picked.Deadline.Add(s.dbf.grace)
+ if deadline.After(bound) {
+ deadline = bound
+ }
+ ownCtx, cancelOwn := context.WithDeadline(ctx, deadline)
+ defer cancelOwn()
+ next := int64(1)
+ for {
+ res, err := dbfCall(st, ownCtx, dbreads.WaitReading, func(c context.Context) (*dbreads.Result, error) {
+ return s.readDBResult(c, a.id), nil
+ }) // first
+ if ownCtx.Err() != nil || errors.Is(err, errDBClientGone) {
+ stop(err, dbreads.EndedNoResult)
+ return
+ }
+ keys, err := dbfCall(st, ownCtx, dbreads.WaitReading, func(c context.Context) ([]string, error) {
+ return store.List(c, dbreads.OutPrefix(a.id))
+ })
+ if ownCtx.Err() != nil || errors.Is(err, errDBClientGone) {
+ stop(err, dbreads.EndedNoResult)
+ return
+ }
+ if err == nil {
+ listed := map[int64]bool{}
+ for _, k := range keys {
+ if seq, ok := dbreads.ParseChunkKey(k, dbreads.OutPrefix(a.id)); ok {
+ listed[seq] = true
+ }
+ }
+ for listed[next] {
+ seq := next
+ sealed, err := dbfCall(st, ownCtx, dbreads.WaitReading, func(c context.Context) ([]byte, error) {
+ b, _, err := store.Get(c, dbreads.ChunkKey(a.id, seq))
+ return b, err
+ })
+ if ownCtx.Err() != nil || errors.Is(err, errDBClientGone) {
+ stop(err, dbreads.EndedNoResult)
+ return
+ }
+ if err != nil {
+ break
+ }
+ if st.lw.write(dbreads.Line{Chunk: seq, Data: sealed}) != nil {
+ end("")
+ return
+ }
+ st.chunks++
+ st.bytes += len(sealed)
+ next++
+ }
+ }
+ if res != nil && next > res.LastSeq {
+ // The bound holds for a result too: one that is complete only
+ // after the deadline is not relayed (plan review finding 12).
+ if ownCtx.Err() != nil {
+ stop(nil, dbreads.EndedNoResult)
+ return
+ }
+ why = res.State
+ st.lw.write(dbreads.Line{Result: res})
+ return
+ }
+ if err := st.lw.tick(ownCtx, dbreads.WaitReading, s.dbf.poll, s.dbf.wait); err != nil {
+ stop(err, dbreads.EndedNoResult)
+ return
+ }
+ }
}
diff --git a/internal/console/apidbforward_test.go b/internal/console/apidbforward_test.go
index bcc159a76..96048bf23 100644
--- a/internal/console/apidbforward_test.go
+++ b/internal/console/apidbforward_test.go
@@ -7,6 +7,9 @@ import (
"crypto/ecdh"
"crypto/ed25519"
"crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
"encoding/json"
"fmt"
"io"
@@ -19,9 +22,13 @@ import (
"testing"
"time"
+ lsfile "github.com/benbjohnson/litestream/file"
+
"github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/dbdoor/dbdoortest"
"github.com/carlosframework/platform/internal/dbquery"
"github.com/carlosframework/platform/internal/dbreads"
+ "github.com/carlosframework/platform/internal/dbreads/dbreadstest"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
)
@@ -585,3 +592,860 @@ func TestDBReadStalledBodyIsCutAtThePreHeaderBound(t *testing.T) {
t.Fatalf("a stalled body wrote %v", keys)
}
}
+
+// startBox runs plan 1's real agent and worker code in process for uk,
+// passing every 20 ms: a stand-in for the box's serial poll, not acceptance.
+func (fx *dbfFixture) startBox(t *testing.T, replicaDir string) *dbreadstest.Box {
+ t.Helper()
+ box := dbreadstest.Start(t, dbreadstest.Options{Store: fx.rel, Region: "uk", Box: "uk-1", Pub: fx.pub, HibernatePrefix: "instances",
+ OpenReplica: func(context.Context, string) (dbdoor.ReplicaReader, error) {
+ return lsfile.NewReplicaClient(replicaDir), nil
+ }})
+ runBox(t, box)
+ return box
+}
+
+func runBox(t *testing.T, box *dbreadstest.Box) {
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ for ctx.Err() == nil {
+ box.Agent.Pass(ctx)
+ time.Sleep(20 * time.Millisecond)
+ }
+ }()
+ t.Cleanup(func() { cancel(); <-done; box.Agent.Wait() })
+}
+
+// openAnswer opens a done result's chunks and summary with the CLI's key.
+func openAnswer(t *testing.T, key *ecdh.PrivateKey, lines []dbreads.Line) ([]byte, dbreads.Summary) {
+ t.Helper()
+ id := lines[0].Admitted
+ res := lines[len(lines)-1].Result
+ if res == nil || res.State != dbreads.StateDone {
+ t.Fatalf("no done result: %+v", lines[len(lines)-1])
+ }
+ var rows bytes.Buffer
+ for _, l := range lines {
+ if l.Chunk == 0 {
+ continue
+ }
+ plain, err := dbreads.OpenChunk(key, id, l.Chunk, dbreads.StreamRows, l.Chunk == res.LastSeq, l.Data)
+ if err != nil {
+ t.Fatalf("chunk %d: %v", l.Chunk, err)
+ }
+ rows.Write(plain)
+ }
+ s, err := dbreads.OpenSummary(key, id, res.Sealed)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return rows.Bytes(), s
+}
+
+func TestDBReadStreamsAQueryEndToEnd(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, 3)
+ fx.startBox(t, dir)
+ body, key := queryBody(t, "SELECT count(*) AS n FROM t")
+ res := fx.openRead(t, dbfHost, fx.member, body)
+ defer res.Body.Close()
+ if res.StatusCode != http.StatusOK || res.Header.Get("Content-Type") != "application/x-ndjson" ||
+ res.Header.Get("Cache-Control") != "no-store" || res.ContentLength != -1 {
+ t.Fatalf("%d %v", res.StatusCode, res.Header)
+ }
+ lines := readLines(t, res.Body)
+ if len(lines) < 2 || lines[0].Admitted == "" || lines[1].Picked != "uk-1" {
+ t.Fatalf("lines %+v", lines)
+ }
+ rows, _ := openAnswer(t, key, lines)
+ if string(rows) != "n\n30\n" {
+ t.Fatalf("rows %q", rows)
+ }
+}
+
+// No box: wait lines while the console waits, then ended not-picked after
+// the pickup window, a cancel, and the slot free again.
+func TestDBReadEndsNotPickedAndCancels(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ // issued_at is truncated to the second (production's semantics), so the
+ // pickup window seen from admission is pickup minus up to a second: 1.4 s
+ // leaves at least 400 ms, eight wait periods (plan review finding 30).
+ fx.srv.dbf.poll, fx.srv.dbf.wait, fx.srv.dbf.pickup = 10*time.Millisecond, 50*time.Millisecond, 1400*time.Millisecond
+ body, _ := queryBody(t, "SELECT 1")
+ res := fx.openRead(t, dbfHost, fx.member, body)
+ lines := readLines(t, res.Body)
+ res.Body.Close()
+ waits := 0
+ for _, l := range lines {
+ if l.Wait == dbreads.WaitPickup {
+ waits++
+ }
+ }
+ last := lines[len(lines)-1]
+ if waits < 3 || last.Ended != dbreads.EndedNotPicked || last.Result != nil {
+ t.Fatalf("lines %+v", lines)
+ }
+ if _, _, err := fx.rel.Get(context.Background(), dbreads.CancelKey(lines[0].Admitted)); err != nil {
+ t.Fatalf("no cancel: %v", err)
+ }
+}
+
+// T7, the console's half: admitted leaves with the headers, and every line
+// is flushed as it is written.
+func TestDBReadLinesAreFlushedAsWritten(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ // At least a second of pickup is left after issued_at's truncation: room
+ // for the five lines below at 100 ms each (plan review finding 30).
+ fx.srv.dbf.poll, fx.srv.dbf.wait, fx.srv.dbf.pickup = 10*time.Millisecond, 100*time.Millisecond, 2*time.Second
+ body, _ := queryBody(t, "SELECT 1")
+ start := time.Now()
+ res := fx.openRead(t, dbfHost, fx.member, body)
+ defer res.Body.Close()
+ br := bufio.NewReader(res.Body)
+ prev := start
+ for i := 0; i < 5; i++ {
+ if _, err := br.ReadBytes('\n'); err != nil {
+ t.Fatal(err)
+ }
+ if gap := time.Since(prev); gap > 400*time.Millisecond {
+ t.Fatalf("line %d arrived %s after the last: not flushed", i, gap)
+ }
+ prev = time.Now()
+ }
+}
+
+// dbfOpen is one open read: its response, a reader over its lines, and its
+// id ("" when it was refused).
+type dbfOpen struct {
+ res *http.Response
+ br *bufio.Reader
+ id string
+}
+
+func (fx *dbfFixture) openHeld(t *testing.T, base, bearer string) dbfOpen {
+ t.Helper()
+ body, _ := queryBody(t, "SELECT 1")
+ raw, _ := json.Marshal(body)
+ req, _ := http.NewRequest(http.MethodPost, base+"/api/cli/apps/"+release.OpsAccount+"/shop/db/"+dbfHost+"/reads", bytes.NewReader(raw))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+bearer)
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ o := dbfOpen{res: res, br: bufio.NewReader(res.Body)}
+ if res.StatusCode == http.StatusOK {
+ line, _ := o.br.ReadBytes('\n')
+ var l dbreads.Line
+ json.Unmarshal(line, &l)
+ o.id = l.Admitted
+ }
+ return o
+}
+
+// untilPicked reads lines until the console has written picked, so the
+// handler is in the owner's phase.
+func (o dbfOpen) untilPicked(t *testing.T) {
+ t.Helper()
+ for {
+ line, err := o.br.ReadBytes('\n')
+ if err != nil {
+ t.Fatalf("%s ended before picked: %v", o.id, err)
+ }
+ var l dbreads.Line
+ json.Unmarshal(line, &l)
+ if l.Picked != "" {
+ return
+ }
+ }
+}
+
+func refusedTooMany(t *testing.T, o dbfOpen, what string) {
+ t.Helper()
+ status, body := refusal(t, o.res)
+ if status != http.StatusTooManyRequests || o.res.Header.Get("Retry-After") == "" || !strings.Contains(body, dbfTooMany) {
+ t.Fatalf("%s: %d %s", what, status, body)
+ }
+}
+
+// admitWithin retries until a read is admitted: a handler frees its slot when
+// it notices its client went, which takes up to a poll.
+func (fx *dbfFixture) admitWithin(t *testing.T, base, bearer string) dbfOpen {
+ t.Helper()
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ o := fx.openHeld(t, base, bearer)
+ if o.id != "" {
+ return o
+ }
+ o.res.Body.Close()
+ if time.Now().After(deadline) {
+ t.Fatal("a disconnected read still holds its slot")
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
+
+// DBF-9 and T15 (J5; plan review findings 7 and 18): two open reads per
+// person and sixteen per console, held by the open requests. Both of a
+// person's slots come back when both CLIs leave before pickup, and again
+// when both leave after it; the seventeenth read across nine people is
+// refused; each disconnected read writes cancel; and a console restarted
+// under open reads recovers nothing and starts with empty counts.
+// Mutations: drop handleAPIDBRead's defer release (red: the second pair is
+// never admitted); release at the end of admitDBRead (red: the third read of
+// a pair is admitted); skip cancelDBRead on a client that went (red: no
+// cancel); a startup pass that writes under db-reads/ (red: the listing
+// changes across NewServer).
+func TestDBReadAdmissionBounds(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ fx.srv.dbf.poll, fx.srv.dbf.wait, fx.srv.dbf.pickup = 10*time.Millisecond, 50*time.Millisecond, time.Minute
+ base := fx.ts.URL
+ var left []string
+
+ // Before pickup.
+ a, b := fx.openHeld(t, base, fx.member), fx.openHeld(t, base, fx.member)
+ if a.id == "" || b.id == "" {
+ t.Fatal("the first two reads were refused")
+ }
+ refusedTooMany(t, fx.openHeld(t, base, fx.member), "a third read")
+ a.res.Body.Close()
+ b.res.Body.Close()
+ left = append(left, a.id, b.id)
+
+ // Both slots come back; the pair is picked, then both CLIs leave.
+ c, d := fx.admitWithin(t, base, fx.member), fx.admitWithin(t, base, fx.member)
+ refusedTooMany(t, fx.openHeld(t, base, fx.member), "a third read after the first pair left")
+ for _, o := range []dbfOpen{c, d} {
+ scriptFor(t, fx.rel, o.id).picked(time.Now().Add(time.Minute))
+ o.untilPicked(t)
+ o.res.Body.Close()
+ left = append(left, o.id)
+ }
+ e, f := fx.admitWithin(t, base, fx.member), fx.admitWithin(t, base, fx.member)
+ refusedTooMany(t, fx.openHeld(t, base, fx.member), "a third read after the picked pair left")
+ e.res.Body.Close()
+ f.res.Body.Close()
+ left = append(left, e.id, f.id)
+ for _, id := range left {
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ if _, _, err := fx.rel.Get(context.Background(), dbreads.CancelKey(id)); err == nil {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("%s: no cancel after its CLI left", id)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ }
+
+ // Sixteen per console, across people.
+ var held []dbfOpen
+ people := dbreads.OpenPerConsole/dbreads.OpenPerPerson + 1
+ for i := 0; i < people; i++ {
+ tok := fx.member
+ if i > 0 {
+ addr := fmt.Sprintf("member%d@example.com", i)
+ if err := fx.st.AddMember(OpsAccountID, addr, RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ tok = cliToken(t, fx.consoleFixture, addr, fmt.Sprintf("code-dbf-%d", i))
+ }
+ for j := 0; j < dbreads.OpenPerPerson; j++ {
+ if len(held) == dbreads.OpenPerConsole {
+ refusedTooMany(t, fx.openHeld(t, base, tok), "the seventeenth read on the console")
+ continue
+ }
+ o := fx.admitWithin(t, base, tok)
+ held = append(held, o)
+ }
+ }
+ if len(held) != dbreads.OpenPerConsole {
+ t.Fatalf("held %d reads", len(held))
+ }
+
+ // A restart under open reads: nothing to recover, nothing written, and
+ // the new console's counts start empty.
+ before, _ := fx.rel.List(context.Background(), dbreads.Prefix)
+ srv2, err := NewServer(fx.srv.cfg, fx.st)
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv2.dbf = fx.srv.dbf
+ ts2 := httptest.NewServer(srv2)
+ defer ts2.Close()
+ after, _ := fx.rel.List(context.Background(), dbreads.Prefix)
+ if !slices.Equal(before, after) {
+ t.Fatalf("starting a console wrote under db-reads/: %v", after)
+ }
+ g := fx.openHeld(t, ts2.URL, fx.member)
+ if g.id == "" {
+ status, body := refusal(t, g.res)
+ t.Fatalf("the restarted console refused a read: %d %s", status, body)
+ }
+ g.res.Body.Close()
+ for _, o := range held {
+ o.res.Body.Close()
+ }
+}
+
+// slowStore holds every call whose key contains match until free closes,
+// ignoring its context: the worst store, for plan review finding 12.
+type slowStore struct {
+ release.Store
+ match string
+ delay time.Duration // 0: until free closes
+ free chan struct{}
+}
+
+func (s *slowStore) hold(key string) {
+ if !strings.Contains(key, s.match) {
+ return
+ }
+ if s.delay > 0 {
+ time.Sleep(s.delay)
+ return
+ }
+ <-s.free
+}
+
+func (s *slowStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ s.hold(key)
+ return s.Store.Get(ctx, key)
+}
+
+func (s *slowStore) List(ctx context.Context, prefix string) ([]string, error) {
+ s.hold(prefix)
+ return s.Store.List(ctx, prefix)
+}
+
+// Plan review finding 12: a store that stops answering, in either phase,
+// neither silences the stream nor holds it past the phase's deadline.
+// Mutations: call the store on r.Context() without dbfCall (red: no wait
+// line and no end until free closes); drop the pickup deadline context (red:
+// same); drop the owner's deadline context (red: same in the owner case).
+func TestDBReadStalledStoreKeepsTheStreamAndItsBound(t *testing.T) {
+ for _, phase := range []string{"pickup", "owner"} {
+ t.Run(phase, func(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ fx.srv.dbf.poll, fx.srv.dbf.wait, fx.srv.dbf.call = 10*time.Millisecond, 100*time.Millisecond, time.Minute
+ fx.srv.dbf.pickup, fx.srv.dbf.grace = 1500*time.Millisecond, 0
+ ss := &slowStore{Store: fx.rel, match: "/picked", free: make(chan struct{})}
+ want := dbreads.EndedNotPicked
+ if phase == "owner" {
+ ss.match, want = "/result.json", dbreads.EndedNoResult
+ }
+ defer close(ss.free)
+ fx.srv.cfg.Releases = ss
+ o := fx.openHeld(t, fx.ts.URL, fx.member)
+ defer o.res.Body.Close()
+ if phase == "owner" {
+ scriptFor(t, fx.rel, o.id).picked(time.Now().Add(time.Second))
+ }
+ start, prev := time.Now(), time.Now()
+ var last dbreads.Line
+ for {
+ line, err := o.br.ReadBytes('\n')
+ if err != nil {
+ break
+ }
+ if gap := time.Since(prev); gap > 500*time.Millisecond {
+ t.Fatalf("a %s gap with the store stalled", gap)
+ }
+ prev = time.Now()
+ json.Unmarshal(line, &last)
+ if time.Since(start) > 5*time.Second {
+ t.Fatal("the stalled store held the request past its deadline")
+ }
+ }
+ if last.Ended != want {
+ t.Fatalf("last line %+v, want %s", last, want)
+ }
+ })
+ }
+}
+
+// Plan review finding 12: a relay slower than the time left ends at the
+// request's bound, without the rest of the chunks and without the result,
+// though both are in the bucket. issued_at is truncated to the second, so
+// the bound is 2 to 3 s after the request; relaying all forty chunks takes 6.
+// Mutation: relay without the owner's deadline, the chunk Gets on
+// r.Context() and no ownCtx check after them (red: all forty are relayed
+// and the request lasts 6 s).
+// Not witnessed alone: the ownCtx check before the result line; dbfCall
+// already cuts every call after the deadline, so that check guards only a
+// line write that outlasts it, which TestDBReadResultAfterTheDeadlineIsNotRelayed
+// forces with a held writer.
+func TestDBReadSlowRelayEndsAtTheBound(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ fx.srv.dbf.poll, fx.srv.dbf.bound, fx.srv.dbf.grace = 10*time.Millisecond, 3*time.Second, 0
+ fx.srv.cfg.Releases = &slowStore{Store: fx.rel, match: "/out/", delay: 150 * time.Millisecond}
+ start := time.Now()
+ o := fx.openHeld(t, fx.ts.URL, fx.member)
+ defer o.res.Body.Close()
+ box := scriptFor(t, fx.rel, o.id)
+ const n = 40
+ for seq := int64(1); seq <= n; seq++ {
+ box.chunk(seq, seq == n, "row\n")
+ }
+ box.result(n, strings.Repeat("row\n", n))
+ box.picked(time.Now().Add(time.Minute))
+ lines := readLines(t, o.br)
+ chunks := 0
+ for _, l := range lines {
+ if l.Result != nil {
+ t.Fatalf("a result relayed past the bound: %+v", l.Result)
+ }
+ if l.Chunk != 0 {
+ chunks++
+ }
+ }
+ if took := time.Since(start); took > 4500*time.Millisecond || chunks >= n {
+ t.Fatalf("relayed %d chunks in %s", chunks, took)
+ }
+ if last := lines[len(lines)-1]; last.Ended != dbreads.EndedNoResult {
+ t.Fatalf("last line %+v", last)
+ }
+}
+
+// scriptedBox writes a read's objects itself: a stand-in for a box, for the
+// orderings T18 needs. It seals real chunks to the request's reply key.
+type scriptedBox struct {
+ t *testing.T
+ s release.Store
+ pub *ecdh.PublicKey
+ id string
+}
+
+func scriptFor(t *testing.T, s release.Store, id string) *scriptedBox {
+ t.Helper()
+ raw, _, err := s.Get(context.Background(), dbreads.RequestKey(id))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var w struct{ Payload string }
+ json.Unmarshal(raw, &w)
+ payload, _ := base64.StdEncoding.DecodeString(w.Payload)
+ var req dbreads.Request
+ json.Unmarshal(payload, &req)
+ pub, err := dbreads.ParseReplyKey(req.ReplyKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return &scriptedBox{t: t, s: s, pub: pub, id: id}
+}
+
+func (b *scriptedBox) picked(deadline time.Time) {
+ p, _ := json.Marshal(dbreads.Picked{Box: "uk-1", Nonce: "n", Deadline: deadline})
+ b.s.Put(context.Background(), dbreads.PickedKey(b.id), p, "")
+}
+
+func (b *scriptedBox) chunk(seq int64, last bool, plain string) {
+ sealed, _ := dbreads.SealChunk(b.pub, b.id, seq, dbreads.StreamRows, last, []byte(plain))
+ b.s.Put(context.Background(), dbreads.ChunkKey(b.id, seq), sealed, "")
+}
+
+func (b *scriptedBox) result(last int64, rows string) {
+ sum := sha256.Sum256([]byte(rows))
+ sealed, _ := dbreads.SealSummary(b.pub, b.id, dbreads.Summary{TXID: 9, Bytes: int64(len(rows)), SHA256: hex.EncodeToString(sum[:])})
+ r, _ := json.Marshal(dbreads.Result{State: dbreads.StateDone, LastSeq: last, Box: "uk-1", Sealed: sealed})
+ b.s.Put(context.Background(), dbreads.ResultKey(b.id), r, "")
+}
+
+// dbReadHookStore runs once on the console's first listing of a read's
+// chunks, after the listing is taken: a box committing between the console's
+// listing and its next result read. It also records, in order, each result
+// read and each chunk listing. (hookStore is temphook_test.go's: plan review
+// finding 2.)
+type dbReadHookStore struct {
+ release.Store
+ once sync.Once
+ hook func()
+ mu sync.Mutex
+ ops []string
+}
+
+func (h *dbReadHookStore) record(op string) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ h.ops = append(h.ops, op)
+}
+
+func (h *dbReadHookStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if strings.HasSuffix(key, "/result.json") {
+ h.record("result")
+ }
+ return h.Store.Get(ctx, key)
+}
+
+func (h *dbReadHookStore) List(ctx context.Context, prefix string) ([]string, error) {
+ keys, err := h.Store.List(ctx, prefix)
+ if strings.HasSuffix(prefix, "/out/") {
+ h.record("list")
+ h.once.Do(h.hook)
+ }
+ return keys, err
+}
+
+// T18 (codex 20): the box commits its last chunk and result.json between the
+// console's listing and its result read, in both orders. The result line
+// never comes before every chunk through last_seq, the read succeeds, and in
+// every round the console reads result.json before it lists the chunks.
+// Mutations, each red on its own (plan review finding 20): list out/ before
+// reading result.json (the operation-order check), or write the result line
+// without waiting for next > last_seq (the chunk-count check).
+func TestDBReadResultWaitsForItsLastChunk(t *testing.T) {
+ for _, resultFirst := range []bool{false, true} {
+ fx := newDBFFixture(t, true)
+ fx.srv.dbf.poll = 10 * time.Millisecond
+ hs := &dbReadHookStore{Store: fx.rel}
+ fx.srv.cfg.Releases = hs
+ body, key := queryBody(t, "SELECT 1")
+ res := fx.openRead(t, dbfHost, fx.member, body)
+ br := bufio.NewReader(res.Body)
+ first, _ := br.ReadBytes('\n')
+ var adm dbreads.Line
+ json.Unmarshal(first, &adm)
+ box := scriptFor(t, fx.rel, adm.Admitted)
+ hs.hook = func() {
+ if resultFirst {
+ box.result(2, "a\nb\n")
+ box.chunk(2, true, "b\n")
+ } else {
+ box.chunk(2, true, "b\n")
+ box.result(2, "a\nb\n")
+ }
+ }
+ box.chunk(1, false, "a\n")
+ box.picked(time.Now().Add(time.Minute))
+ lines := append([]dbreads.Line{adm}, readLines(t, br)...)
+ res.Body.Close()
+ chunks := 0
+ for _, l := range lines {
+ if l.Chunk != 0 {
+ chunks++
+ }
+ if l.Result != nil && chunks != 2 {
+ t.Fatalf("result-first %v: the result line came after %d chunks", resultFirst, chunks)
+ }
+ }
+ if rows, _ := openAnswer(t, key, lines); string(rows) != "a\nb\n" {
+ t.Fatalf("rows %q", rows)
+ }
+ hs.mu.Lock()
+ ops := append([]string(nil), hs.ops...)
+ hs.mu.Unlock()
+ for i, op := range ops {
+ if op == "list" && (i == 0 || ops[i-1] != "result") {
+ t.Fatalf("result-first %v: a chunk listing not preceded by its round's result read: %v", resultFirst, ops)
+ }
+ }
+ }
+}
+
+// dbfHideStore leaves chunk seq out of the first hide listings of a read's
+// chunks: a listing that lags the box's writes.
+type dbfHideStore struct {
+ release.Store
+ seq int64
+ mu sync.Mutex
+ hide int
+}
+
+func (h *dbfHideStore) List(ctx context.Context, prefix string) ([]string, error) {
+ keys, err := h.Store.List(ctx, prefix)
+ if !strings.HasSuffix(prefix, "/out/") {
+ return keys, err
+ }
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ if h.hide == 0 {
+ return keys, err
+ }
+ h.hide--
+ var out []string
+ for _, k := range keys {
+ if seq, ok := dbreads.ParseChunkKey(k, prefix); !ok || seq != h.seq {
+ out = append(out, k)
+ }
+ }
+ return out, err
+}
+
+// T18's completeness guard on its own (plan review finding 31): result.json
+// says last_seq 2 from the first round, and the first three listings miss
+// chunk 2. The result line waits until chunk 2 is relayed. Mutation: write
+// the result line without waiting for next > res.LastSeq (red: the result
+// comes after one chunk).
+func TestDBReadResultWaitsForAChunkTheListingMissed(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ fx.srv.dbf.poll = 10 * time.Millisecond
+ fx.srv.cfg.Releases = &dbfHideStore{Store: fx.rel, seq: 2, hide: 3}
+ body, key := queryBody(t, "SELECT 1")
+ res := fx.openRead(t, dbfHost, fx.member, body)
+ defer res.Body.Close()
+ br := bufio.NewReader(res.Body)
+ first, _ := br.ReadBytes('\n')
+ var adm dbreads.Line
+ json.Unmarshal(first, &adm)
+ box := scriptFor(t, fx.rel, adm.Admitted)
+ box.chunk(1, false, "a\n")
+ box.chunk(2, true, "b\n")
+ box.result(2, "a\nb\n")
+ box.picked(time.Now().Add(time.Minute))
+ lines := append([]dbreads.Line{adm}, readLines(t, br)...)
+ chunks := 0
+ for _, l := range lines {
+ if l.Chunk != 0 {
+ chunks++
+ }
+ if l.Result != nil && chunks != 2 {
+ t.Fatalf("the result line came after %d chunks", chunks)
+ }
+ }
+ if rows, _ := openAnswer(t, key, lines); string(rows) != "a\nb\n" {
+ t.Fatalf("rows %q", rows)
+ }
+}
+
+// dbfHeldWriter is a ResponseWriter that holds the write of a line
+// containing holdOn until until: a client that takes one line slowly. A
+// stand-in for a network client, in a unit test.
+type dbfHeldWriter struct {
+ header http.Header
+ holdOn string
+ until time.Time
+ mu sync.Mutex
+ buf bytes.Buffer
+}
+
+func (w *dbfHeldWriter) Header() http.Header { return w.header }
+func (w *dbfHeldWriter) WriteHeader(int) {}
+func (w *dbfHeldWriter) Flush() {}
+
+func (w *dbfHeldWriter) Write(p []byte) (int, error) {
+ if bytes.Contains(p, []byte(w.holdOn)) {
+ time.Sleep(time.Until(w.until))
+ }
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ return w.buf.Write(p)
+}
+
+// Plan review finding 35: the owner's deadline holds for the result line
+// too. Every chunk and result.json are in the bucket, but the client takes
+// the last chunk's line until past the deadline: the read ends no-result,
+// and the result is not relayed. Mutation: drop the ownCtx check before the
+// result line (red: the result is relayed).
+func TestDBReadResultAfterTheDeadlineIsNotRelayed(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ fx.srv.dbf.poll, fx.srv.dbf.grace = 10*time.Millisecond, 0
+ key, err := dbreads.NewReplyKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ id, err := dbreads.MintID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ box := &scriptedBox{t: t, s: fx.rel, pub: key.PublicKey(), id: id}
+ deadline := time.Now().Add(800 * time.Millisecond)
+ box.chunk(1, true, "a\n")
+ box.result(1, "a\n")
+ box.picked(deadline)
+ w := &dbfHeldWriter{header: http.Header{}, holdOn: `"chunk":1,`, until: deadline.Add(200 * time.Millisecond)}
+ r := httptest.NewRequest(http.MethodPost, "/", nil)
+ fx.srv.streamDBRead(w, r, http.NewResponseController(w), dbReadAdmitted{id: id, region: "uk", issued: time.Now().UTC().Truncate(time.Second)})
+ w.mu.Lock()
+ lines := readLines(t, bytes.NewReader(w.buf.Bytes()))
+ w.mu.Unlock()
+ chunks := 0
+ for _, l := range lines {
+ if l.Result != nil {
+ t.Fatalf("a result relayed past the owner's deadline: %+v", l.Result)
+ }
+ if l.Chunk != 0 {
+ chunks++
+ }
+ }
+ if last := lines[len(lines)-1]; chunks != 1 || last.Ended != dbreads.EndedNoResult {
+ t.Fatalf("%d chunks, last line %+v", chunks, last)
+ }
+}
+
+// dbfDeadlineListener records, for every read deadline the server sets on
+// its connections, how far ahead it was set.
+type dbfDeadlineListener struct {
+ net.Listener
+ mu sync.Mutex
+ ahead []time.Duration
+}
+
+type dbfDeadlineConn struct {
+ net.Conn
+ l *dbfDeadlineListener
+}
+
+func (l *dbfDeadlineListener) Accept() (net.Conn, error) {
+ c, err := l.Listener.Accept()
+ if err != nil {
+ return nil, err
+ }
+ return dbfDeadlineConn{Conn: c, l: l}, nil
+}
+
+func (c dbfDeadlineConn) SetReadDeadline(t time.Time) error {
+ if !t.IsZero() {
+ c.l.mu.Lock()
+ c.l.ahead = append(c.l.ahead, time.Until(t))
+ c.l.mu.Unlock()
+ }
+ return c.Conn.SetReadDeadline(t)
+}
+
+// Plan review findings 13 and 38: admission reads under s.dbf.preHeader,
+// and once admitted the read deadline moves out to the read's bound plus a
+// minute. Observed on the connection itself: once a body has been read to
+// its end, net/http's background read clears the read deadline on its own,
+// so a stream that outlives ReadTimeout does not show the extension.
+// Mutations: drop the extension (red: no deadline past 22 minutes); drop the
+// preHeader deadline (red: none between 15 and 20 s; the server's own are
+// 10 s and 5 minutes).
+func TestDBReadSetsBothReadDeadlines(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ fx.srv.dbf.poll, fx.srv.dbf.pickup = 10*time.Millisecond, 1500*time.Millisecond
+ raw, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ ln := &dbfDeadlineListener{Listener: raw}
+ hs := NewHTTPServer(fx.srv)
+ go hs.Serve(ln)
+ t.Cleanup(func() { hs.Close() })
+ body, _ := queryBody(t, "SELECT 1")
+ rawBody, _ := json.Marshal(body)
+ req, _ := http.NewRequest(http.MethodPost, "http://"+raw.Addr().String()+strings.TrimPrefix(fx.readURL(dbfHost), fx.ts.URL), bytes.NewReader(rawBody))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+fx.member)
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ io.Copy(io.Discard, res.Body)
+ res.Body.Close()
+ ln.mu.Lock()
+ defer ln.mu.Unlock()
+ var pre, extended bool
+ for _, d := range ln.ahead {
+ pre = pre || (d > 15*time.Second && d <= 20*time.Second)
+ extended = extended || d > 22*time.Minute
+ }
+ if !pre || !extended {
+ t.Fatalf("read deadlines set this far ahead: %v", ln.ahead)
+ }
+}
+
+// Review Focus 3: a picked deadline far in the future does not hold the
+// request past its own bound.
+func TestDBReadRequestBoundClampsAForgedDeadline(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ fx.srv.dbf.poll, fx.srv.dbf.bound = 10*time.Millisecond, 1500*time.Millisecond
+ body, _ := queryBody(t, "SELECT 1")
+ res := fx.openRead(t, dbfHost, fx.member, body)
+ br := bufio.NewReader(res.Body)
+ first, _ := br.ReadBytes('\n')
+ var adm dbreads.Line
+ json.Unmarshal(first, &adm)
+ scriptFor(t, fx.rel, adm.Admitted).picked(time.Date(2100, 1, 1, 0, 0, 0, 0, time.UTC))
+ done := make(chan []dbreads.Line)
+ go func() { done <- readLines(t, br) }()
+ select {
+ case lines := <-done:
+ if last := lines[len(lines)-1]; last.Ended != dbreads.EndedNoResult {
+ t.Fatalf("last line %+v", last)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("the request outlived its bound")
+ }
+ res.Body.Close()
+}
+
+// Review Focus 4: a result.json that is not a result is never relayed.
+func TestDBReadIgnoresAMalformedResult(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ fx.srv.dbf.poll, fx.srv.dbf.grace = 10*time.Millisecond, 0
+ body, _ := queryBody(t, "SELECT 1")
+ res := fx.openRead(t, dbfHost, fx.member, body)
+ br := bufio.NewReader(res.Body)
+ first, _ := br.ReadBytes('\n')
+ var adm dbreads.Line
+ json.Unmarshal(first, &adm)
+ box := scriptFor(t, fx.rel, adm.Admitted)
+ box.picked(time.Now().Add(500 * time.Millisecond))
+ fx.rel.Put(context.Background(), dbreads.ResultKey(adm.Admitted), []byte(`{"state":"maybe","last_seq":-1}`), "")
+ lines := readLines(t, br)
+ res.Body.Close()
+ for _, l := range lines {
+ if l.Result != nil {
+ t.Fatalf("a malformed result was relayed: %+v", l.Result)
+ }
+ }
+ if last := lines[len(lines)-1]; last.Ended != dbreads.EndedNoResult {
+ t.Fatalf("last line %+v", last)
+ }
+}
+
+// strictStore fails the test on any delete or replacing write under
+// db-reads/ (T16, the console's half).
+type strictStore struct {
+ release.Store
+ t *testing.T
+}
+
+func (s strictStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if strings.HasPrefix(key, dbreads.Prefix) && ifMatch != "" {
+ s.t.Errorf("a replacing write of %s", key)
+ }
+ return s.Store.Put(ctx, key, body, ifMatch)
+}
+
+func (s strictStore) Delete(ctx context.Context, key string) error {
+ if strings.HasPrefix(key, dbreads.Prefix) {
+ s.t.Errorf("a delete of %s", key)
+ }
+ return s.Store.Delete(ctx, key)
+}
+
+// T16 (codex 4, 13, 14): a box that writes after the request ended changes
+// nothing any reader sees, and the console never deletes or replaces.
+func TestDBReadLateWritesChangeNothing(t *testing.T) {
+ fx := newDBFFixture(t, true)
+ fx.srv.cfg.Releases = strictStore{Store: fx.rel, t: t}
+ fx.srv.dbf.poll, fx.srv.dbf.grace = 10*time.Millisecond, 0
+ body, _ := queryBody(t, "SELECT 1")
+ res := fx.openRead(t, dbfHost, fx.member, body)
+ br := bufio.NewReader(res.Body)
+ first, _ := br.ReadBytes('\n')
+ var adm dbreads.Line
+ json.Unmarshal(first, &adm)
+ box := scriptFor(t, fx.rel, adm.Admitted)
+ box.picked(time.Now().Add(200 * time.Millisecond))
+ lines := readLines(t, br) // ends no-result at the deadline
+ res.Body.Close()
+ box.chunk(1, true, "late\n")
+ box.result(1, "late\n")
+ if last := lines[len(lines)-1]; last.Ended != dbreads.EndedNoResult {
+ t.Fatalf("last line %+v", last)
+ }
+ keys, _ := fx.rel.List(context.Background(), dbreads.Prefix+adm.Admitted+"/")
+ for _, k := range keys {
+ if strings.HasSuffix(k, "/cancel") {
+ return
+ }
+ }
+ t.Fatalf("no cancel among %v", keys)
+}