carlos / platform Public

carlos db pull: the forwarded pull, spooled, checked, restored locally (DBF-17, DBF-18, DBF-24, pending)

When the console's forward marker offers pull, dbPull holds one request
to the reads route, spools the sealed chunks to a private 0700 directory
(each checked against the chunk bound first), checks the file list whole,
opens the chunks into a litestream file replica, checks the count and the
SHA-256, restores with dbdoor.RestoreLocal, and hands the copy to today's
copyOut and lines. Each spooled chunk is removed once its bytes are in the
files, so the spool and the files are never both whole on the disk. A
console that forwards queries only still gets DBF-8.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev a5164cd962fc6644c333bbd5386486c6f5e97efd parent a32088c
4 files changed, +617 −33
  • approved_db_forward_copy_test.go +1 −0
  • db.go +7 −2
  • dbforward.go +285 −26
  • dbforward_test.go +324 −5
diff --git a/approved_db_forward_copy_test.go b/approved_db_forward_copy_test.go
index 33fcd17bc..0ff969936 100644
--- a/approved_db_forward_copy_test.go
+++ b/approved_db_forward_copy_test.go
@@ -62,6 +62,7 @@ var dbForwardCopyBuilt = []string{
// branch must not land before they are reviewed.
var dbForwardCopyWired = []string{
"DBF-19", "DBF-20", // the console's pull audit details
+ "DBF-17", "DBF-18", "DBF-24", // the CLI's pull sentences
}
func mustParseDBForwardRecord(t *testing.T) []copyRow {
diff --git a/db.go b/db.go
index 0757bdde4..bf697ae3d 100644
--- a/db.go
+++ b/db.go
@@ -284,8 +284,13 @@ func dbPull(ctx context.Context, t dbTarget, out string) error {
r, err := dbRestore(ctx, t)
var fwd *errDBForward
if errors.As(err, &fwd) {
- // Phase 1 forwards queries only (db region forward spec §6): DBF-8.
- return fmt.Errorf(dbfNoPull, t.host, fwd.door.Forward.Region)
+ // The copy's files come from the region that holds them (db region
+ // forward spec §6), when the console forwards pulls there.
+ if !slices.Contains(fwd.door.Forward.Ops, dbreads.OpPull) {
+ // A console that forwards queries and not pulls (plan 2's): DBF-8.
+ return fmt.Errorf(dbfNoPull, t.host, fwd.door.Forward.Region)
+ }
+ r, err = dbPullForward(ctx, t, *fwd.door.Forward)
}
if err != nil {
return err
diff --git a/dbforward.go b/dbforward.go
index 491df7887..61b4a6bdf 100644
--- a/dbforward.go
+++ b/dbforward.go
@@ -1,9 +1,11 @@
-// dbforward.go is the CLI's half of a forwarded `carlos db query` (spec
-// docs/superpowers/specs/2026-10-22-db-region-forward-design.md §5.5): when
-// the db door answers with the forward marker, the CLI makes an ephemeral
-// key, holds one request to the console's reads route open, buffers every
-// sealed chunk, and prints nothing until a done result's summary checks out
-// against the bytes (codex 6).
+// dbforward.go is the CLI's half of a forwarded `carlos db query` and
+// `carlos db pull` (spec
+// docs/superpowers/specs/2026-10-22-db-region-forward-design.md §5.5, §6):
+// when the db door answers with the forward marker, the CLI makes an
+// ephemeral key, holds one request to the console's reads route open, keeps
+// every sealed chunk (in memory for a query, spooled to a private directory
+// for a pull), and prints or saves nothing until a done result's summary
+// checks out against the bytes (codex 6).
package main
import (
@@ -20,10 +22,16 @@ import (
"net/http"
"net/url"
"os"
+ "path/filepath"
+ "strconv"
"strings"
"time"
"unicode/utf8"
+ "github.com/benbjohnson/litestream"
+ lsfile "github.com/benbjohnson/litestream/file"
+ "github.com/superfly/ltx"
+
"github.com/carlosframework/platform/internal/dbdoor"
"github.com/carlosframework/platform/internal/dbreads"
)
@@ -45,6 +53,14 @@ const (
dbfNotUTF8 = "this query cannot be sent to region %s, because it contains invalid UTF-8 or the replacement character U+FFFD. fix the query and run it again." // DBF-32
)
+// The forwarded pull's CLI sentences (copy record DBF-17, DBF-18, DBF-24),
+// pending a copy review: wired through dbForwardCopyWired.
+const (
+ dbfPullTooLarge = "the database for %s takes %s to fetch. carlos db pull can fetch at most %s from region %s." // DBF-17
+ dbfFetching = "fetching a copy of %s's database from region %s." // DBF-18
+ dbfPullNoRoom = "the server in region %s does not have room to prepare a copy of %s's database right now. try again later." // DBF-24
+)
+
// errDBForward is the db door's forward marker, handed back by dbRestore so
// a verb can switch to the forwarded read.
type errDBForward struct {
@@ -98,7 +114,12 @@ func dbQueryForward(ctx context.Context, t dbTarget, sqlText string, fwd dbdoor.
raw, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10))
return apiErrorFromBody(res.StatusCode, raw)
}
- ans, err := readDBForward(ctx, res.Body, key, t.host, fwd.Region, os.Stderr)
+ sink := &memSink{}
+ id, result, err := readDBForward(ctx, res.Body, key, t.host, fwd.Region, dbfReading, os.Stderr, sink, newDBFChunkBound(dbreads.MaxOutputBytes, dbreads.ChunkBytes))
+ if err != nil {
+ return err
+ }
+ ans, err := openDBForward(id, key, sink, *result, t.host, fwd.Region)
if err != nil {
return err
}
@@ -141,55 +162,98 @@ func (b *dbfChunkBound) admit(sealed []byte) bool {
return true
}
+// dbChunkSink holds a read's sealed chunks until its result arrives: in
+// memory for a query (at most 64 MiB), in the pull's private directory for a
+// pull (up to its cap).
+type dbChunkSink interface {
+ add(sealed []byte) error
+ count() int
+ chunk(i int) ([]byte, error) // 0-based
+}
+
+type memSink struct{ chunks [][]byte }
+
+func (m *memSink) add(b []byte) error { m.chunks = append(m.chunks, b); return nil }
+func (m *memSink) count() int { return len(m.chunks) }
+func (m *memSink) chunk(i int) ([]byte, error) { return m.chunks[i], nil }
+
+// fileSink spools sealed chunks to dir, one file each, 0600 in a 0700
+// directory the caller removes.
+type fileSink struct {
+ dir string
+ n int
+}
+
+func (f *fileSink) add(b []byte) error {
+ if f.n == 0 {
+ if err := os.MkdirAll(f.dir, 0o700); err != nil {
+ return err
+ }
+ }
+ f.n++
+ return dbPullSpoolWrite(filepath.Join(f.dir, strconv.Itoa(f.n)), b, 0o600)
+}
+
+func (f *fileSink) count() int { return f.n }
+
+func (f *fileSink) chunk(i int) ([]byte, error) {
+ return os.ReadFile(filepath.Join(f.dir, strconv.Itoa(i+1)))
+}
+
+// drop removes chunk i once its bytes are in the files, so the spool and
+// the files are never both whole on the member's disk.
+func (f *fileSink) drop(i int) { os.Remove(filepath.Join(f.dir, strconv.Itoa(i+1))) }
+
// readDBForward reads the reads route's lines (spec §5.5 steps 6 to 8). It
-// says DBF-11 once admitted, buffers every chunk in sequence, and opens and
-// checks the answer only when the result arrives.
-func readDBForward(ctx context.Context, body io.Reader, key *ecdh.PrivateKey, host, region string, status io.Writer) (dbForwardAnswer, error) {
+// says the reading sentence once admitted, keeps every chunk in sequence in
+// sink (each one checked against bound before the sink keeps anything, plan
+// review finding 37), and returns the read's id and its result unopened.
+func readDBForward(ctx context.Context, body io.Reader, key *ecdh.PrivateKey, host, region, reading string, status io.Writer, sink dbChunkSink, bound *dbfChunkBound) (string, *dbreads.Result, error) {
unchecked := fmt.Errorf(dbfUnchecked, region)
sc := bufio.NewScanner(body)
sc.Buffer(make([]byte, 64<<10), dbreads.MaxLineBytes)
var id, ended string
- var sealed [][]byte
- bound := newDBFChunkBound(dbreads.MaxOutputBytes, dbreads.ChunkBytes)
for sc.Scan() {
var l dbreads.Line
if err := json.Unmarshal(sc.Bytes(), &l); err != nil {
- return dbForwardAnswer{}, unchecked
+ return "", nil, unchecked
}
switch {
case l.Admitted != "":
if id != "" || !dbreads.ValidID(l.Admitted) {
- return dbForwardAnswer{}, unchecked
+ return "", nil, unchecked
}
id = l.Admitted
- fmt.Fprintln(status, fmt.Sprintf(dbfReading, host, region))
+ fmt.Fprintln(status, fmt.Sprintf(reading, host, region))
case l.Chunk != 0:
- if id == "" || l.Chunk != int64(len(sealed))+1 || !bound.admit(l.Data) {
- return dbForwardAnswer{}, unchecked
+ if id == "" || l.Chunk != int64(sink.count())+1 || !bound.admit(l.Data) {
+ return "", nil, unchecked
+ }
+ if err := sink.add(l.Data); err != nil {
+ return "", nil, err
}
- sealed = append(sealed, l.Data)
case l.Result != nil:
if id == "" {
- return dbForwardAnswer{}, unchecked
+ return "", nil, unchecked
}
- return openDBForward(id, key, sealed, *l.Result, host, region)
+ return id, l.Result, nil
case l.Ended != "":
ended = l.Ended
}
}
if errors.Is(ctx.Err(), context.Canceled) {
- return dbForwardAnswer{}, errors.New("stopped")
+ return "", nil, errors.New("stopped")
}
if ended == dbreads.EndedNotPicked {
- return dbForwardAnswer{}, fmt.Errorf(dbfNotPicked, region)
+ return "", nil, fmt.Errorf(dbfNotPicked, region)
}
- return dbForwardAnswer{}, fmt.Errorf(dbfUnfinished, host, region)
+ return "", nil, fmt.Errorf(dbfUnfinished, host, region)
}
// openDBForward opens a result: a done one's every chunk and its summary,
// checked against each other before anything is returned; any other state
// mapped to its sentence (spec §5.6, §10).
-func openDBForward(id string, key *ecdh.PrivateKey, sealed [][]byte, res dbreads.Result, host, region string) (dbForwardAnswer, error) {
+func openDBForward(id string, key *ecdh.PrivateKey, sink dbChunkSink, res dbreads.Result, host, region string) (dbForwardAnswer, error) {
unchecked := fmt.Errorf(dbfUnchecked, region)
if res.Valid() != nil {
return dbForwardAnswer{}, unchecked
@@ -200,11 +264,15 @@ func openDBForward(id string, key *ecdh.PrivateKey, sealed [][]byte, res dbreads
}
switch res.State {
case dbreads.StateDone:
- if res.LastSeq != int64(len(sealed)) {
+ if res.LastSeq != int64(sink.count()) {
return dbForwardAnswer{}, unchecked
}
var rows bytes.Buffer
- for i, c := range sealed {
+ for i := 0; i < sink.count(); i++ {
+ c, err := sink.chunk(i)
+ if err != nil {
+ return dbForwardAnswer{}, unchecked
+ }
seq := int64(i + 1)
plain, err := dbreads.OpenChunk(key, id, seq, dbreads.StreamRows, seq == res.LastSeq, c)
if err != nil {
@@ -246,3 +314,194 @@ func openDBForward(id string, key *ecdh.PrivateKey, sealed [][]byte, res dbreads
}
return dbForwardAnswer{}, fmt.Errorf(dbfUnfinished, host, region)
}
+
+// openDBPull opens a pull's result (spec §6, phase 2): a done one's chunks,
+// opened in order, are the planned files concatenated; they are checked
+// against the summary's count and hash and split by its file list into a
+// litestream file replica under dir, which today's restore and check turn
+// into the copy. Any other state maps to its sentence.
+func openDBPull(ctx context.Context, id string, key *ecdh.PrivateKey, sink dbChunkSink, res dbreads.Result, host, region, dir string) (*dbdoor.Restored, error) {
+ unchecked := fmt.Errorf(dbfUnchecked, region)
+ if res.Valid() != nil {
+ return nil, unchecked
+ }
+ s, err := dbreads.OpenSummary(key, id, res.Sealed)
+ if err != nil {
+ return nil, unchecked
+ }
+ if res.State != dbreads.StateDone {
+ switch res.Code {
+ case dbreads.CodeTooLarge:
+ return nil, fmt.Errorf(dbfPullTooLarge, host, humanBytes(&s.Restored), humanBytes(&s.Cap), region)
+ case dbreads.CodeNoRoom:
+ return nil, fmt.Errorf(dbfPullNoRoom, region, host)
+ }
+ _, err := openDBForward(id, key, sink, res, host, region)
+ return nil, err
+ }
+ // A done pull is the whole answer: no output cap applies to one.
+ if res.Code != "" || res.LastSeq != int64(sink.count()) || checkPullManifest(s) != nil {
+ return nil, unchecked
+ }
+ root := filepath.Join(dir, "replica")
+ h := sha256.New()
+ fi, written := 0, int64(0)
+ var out *os.File
+ defer func() {
+ if out != nil {
+ out.Close()
+ }
+ }()
+ drop, _ := sink.(interface{ drop(int) })
+ for i := 0; i < sink.count(); i++ {
+ sealed, err := sink.chunk(i)
+ if err != nil {
+ return nil, unchecked
+ }
+ seq := int64(i + 1)
+ plain, err := dbreads.OpenChunk(key, id, seq, dbreads.StreamLTX, seq == res.LastSeq, sealed)
+ if err != nil {
+ return nil, unchecked
+ }
+ h.Write(plain)
+ for len(plain) > 0 {
+ if fi >= len(s.Files) {
+ return nil, unchecked
+ }
+ f := s.Files[fi]
+ if out == nil {
+ p := litestream.LTXFilePath(root, f.Level, ltx.TXID(f.MinTXID), ltx.TXID(f.MaxTXID))
+ if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
+ return nil, err
+ }
+ if out, err = os.OpenFile(p, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600); err != nil {
+ return nil, err
+ }
+ }
+ n := min(int64(len(plain)), f.Size-written)
+ if _, err := out.Write(plain[:n]); err != nil {
+ return nil, err
+ }
+ plain, written = plain[n:], written+n
+ if written == f.Size {
+ if err := out.Close(); err != nil {
+ out = nil
+ return nil, err
+ }
+ out, fi, written = nil, fi+1, 0
+ }
+ }
+ if drop != nil {
+ drop.drop(i)
+ }
+ }
+ if fi != len(s.Files) || hex.EncodeToString(h.Sum(nil)) != s.SHA256 {
+ return nil, unchecked
+ }
+ db := filepath.Join(dir, "replica.db")
+ if err := dbdoor.RestoreLocal(ctx, lsfile.NewReplicaClient(root), db, s.TXID); err != nil {
+ return nil, dbRestoreError(host, err)
+ }
+ os.RemoveAll(root)
+ return &dbdoor.Restored{Path: db, Dir: dir, TXID: s.TXID, At: s.At}, nil
+}
+
+// checkPullManifest is the summary's file list checked whole before any
+// file is created (plan review finding 22): every size a possible LTX file
+// and within the cap, every level one litestream writes, every range a
+// range, no file twice, sizes that sum without overflow to the summary's
+// byte count, and a last file that ends at its transaction.
+func checkPullManifest(s dbreads.Summary) error {
+ bad := errors.New("the file list does not add up")
+ if len(s.Files) == 0 || s.Bytes <= 0 || s.Bytes > dbreads.MaxPullBytes {
+ return bad
+ }
+ type coord struct {
+ level int
+ min, max uint64
+ }
+ seen := make(map[coord]bool, len(s.Files))
+ var sum int64
+ for _, f := range s.Files {
+ c := coord{f.Level, f.MinTXID, f.MaxTXID}
+ switch {
+ case f.Size < ltx.HeaderSize+ltx.TrailerSize, f.Size > dbreads.MaxPullBytes,
+ f.Level < 0, f.Level > litestream.SnapshotLevel,
+ f.MinTXID < 1, f.MaxTXID < f.MinTXID, seen[c],
+ sum > dbreads.MaxPullBytes-f.Size: // sum + f.Size would pass the cap
+ return bad
+ }
+ seen[c] = true
+ sum += f.Size
+ }
+ if sum != s.Bytes || s.Files[len(s.Files)-1].MaxTXID != s.TXID {
+ return bad
+ }
+ return nil
+}
+
+// dbPullSpoolWrite writes one spooled chunk: os.WriteFile, a seam so a test
+// can fail the spool part way (plan review finding 23).
+var dbPullSpoolWrite = os.WriteFile
+
+// dbPullForward is a pull through the forwarded read (spec §6). The spool,
+// the files and the copy live in one private 0700 directory under the system
+// temp dir, removed on every path but success, where the caller removes it
+// after copyOut, as it does today's restore directory.
+func dbPullForward(ctx context.Context, t dbTarget, fwd dbdoor.Forward) (*dbdoor.Restored, error) {
+ ctx, cancel := context.WithTimeout(ctx, dbreads.CLIBound)
+ defer cancel()
+ key, err := dbreads.NewReplyKey()
+ if err != nil {
+ return nil, err
+ }
+ at := ""
+ if !t.at.IsZero() {
+ at = t.at.UTC().Format(time.RFC3339Nano)
+ }
+ body, err := json.Marshal(dbreads.ReadBody{Op: dbreads.OpPull, At: at, ReplyKey: dbreads.EncodeReplyKey(key.PublicKey())})
+ if err != nil {
+ return nil, err
+ }
+ res, err := t.sess.c.doStream(ctx, http.MethodPost, apiPath(t.acct, t.app, "/db/"+url.PathEscape(t.host)+"/reads"),
+ bytes.NewReader(body), int64(len(body)), http.Header{"Content-Type": {"application/json"}})
+ if err != nil {
+ if errors.Is(ctx.Err(), context.Canceled) {
+ return nil, errors.New("stopped")
+ }
+ return nil, fmt.Errorf(dbfUnfinished, t.host, fwd.Region)
+ }
+ defer res.Body.Close()
+ if res.StatusCode != http.StatusOK {
+ raw, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10))
+ return nil, apiErrorFromBody(res.StatusCode, raw)
+ }
+ dir, err := os.MkdirTemp("", "carlos-db-")
+ if err != nil {
+ return nil, err
+ }
+ // MkdirTemp already creates 0700; say it anyway, as the in-region
+ // restore does, because the copy's privacy rests on it.
+ if err := os.Chmod(dir, 0o700); err != nil {
+ os.RemoveAll(dir)
+ return nil, err
+ }
+ done := false
+ defer func() {
+ if !done {
+ os.RemoveAll(dir)
+ }
+ }()
+ sink := &fileSink{dir: filepath.Join(dir, "sealed")}
+ id, result, err := readDBForward(ctx, res.Body, key, t.host, fwd.Region, dbfFetching, os.Stderr, sink, newDBFChunkBound(dbreads.MaxPullBytes, dbreads.PullChunkBytes))
+ if err != nil {
+ return nil, err
+ }
+ r, err := openDBPull(ctx, id, key, sink, *result, t.host, fwd.Region, dir)
+ if err != nil {
+ return nil, err
+ }
+ os.RemoveAll(sink.dir)
+ done = true
+ return r, nil
+}
diff --git a/dbforward_test.go b/dbforward_test.go
index e6710057c..279c42100 100644
--- a/dbforward_test.go
+++ b/dbforward_test.go
@@ -5,18 +5,26 @@ import (
"context"
"crypto/ecdh"
"crypto/sha256"
+ "database/sql"
"encoding/hex"
"encoding/json"
+ "errors"
"fmt"
+ "io"
"net/http"
"net/http/httptest"
"os"
+ "path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
+ lsfile "github.com/benbjohnson/litestream/file"
+ "github.com/superfly/ltx"
+
"github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/dbdoor/dbdoortest"
"github.com/carlosframework/platform/internal/dbreads"
)
@@ -65,7 +73,12 @@ func summaryOf(rows string) dbreads.Summary {
func readFwd(t *testing.T, s *stream, key *ecdh.PrivateKey) (dbForwardAnswer, string, error) {
t.Helper()
var status bytes.Buffer
- ans, err := readDBForward(context.Background(), &s.buf, key, "shop.example.com", "uk", &status)
+ sink := &memSink{}
+ id, res, err := readDBForward(context.Background(), &s.buf, key, "shop.example.com", "uk", dbfReading, &status, sink, newDBFChunkBound(dbreads.MaxOutputBytes, dbreads.ChunkBytes))
+ if err != nil {
+ return dbForwardAnswer{}, status.String(), err
+ }
+ ans, err := openDBForward(id, key, sink, *res, "shop.example.com", "uk")
return ans, status.String(), err
}
@@ -206,9 +219,9 @@ func TestForwardedQueryCtrlCPrintsNothing(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
var status bytes.Buffer
- ans, err := readDBForward(ctx, &cutReader{r: &s.buf}, key, "shop.example.com", "uk", &status)
- if err == nil || err.Error() != "stopped" || ans.rows != nil {
- t.Fatalf("%q %v", ans.rows, err)
+ _, _, err := readDBForward(ctx, &cutReader{r: &s.buf}, key, "shop.example.com", "uk", dbfReading, &status, &memSink{}, newDBFChunkBound(dbreads.MaxOutputBytes, dbreads.ChunkBytes))
+ if err == nil || err.Error() != "stopped" {
+ t.Fatalf("%v", err)
}
}
@@ -243,7 +256,12 @@ func TestForwardedQueryBoundsChunkCountAndSize(t *testing.T) {
s := newStream(t, key)
write(s)
var status bytes.Buffer
- if _, err := readDBForward(context.Background(), &s.buf, key, "shop.example.com", "uk", &status); err == nil || err.Error() != unchecked {
+ sink := &memSink{}
+ id, res, err := readDBForward(context.Background(), &s.buf, key, "shop.example.com", "uk", dbfReading, &status, sink, newDBFChunkBound(dbreads.MaxOutputBytes, dbreads.ChunkBytes))
+ if err == nil {
+ _, err = openDBForward(id, key, sink, *res, "shop.example.com", "uk")
+ }
+ if err == nil || err.Error() != unchecked {
t.Errorf("%s: %v", name, err)
}
}
@@ -286,3 +304,304 @@ func (c *cutReader) Read(p []byte) (int, error) {
func dbdoorErrNothing() error { return dbdoor.ErrNothingReplicated }
func errVanished() error { return os.ErrNotExist }
+
+// pullStream is a pull's body for the files of dir's replica, in one chunk.
+func pullStream(t *testing.T, key *ecdh.PrivateKey, dir string, mutate func(s *dbreads.Summary, files [][]byte)) *stream {
+ t.Helper()
+ return pullStreamN(t, key, dir, 1, mutate)
+}
+
+// pullStreamN is pullStream with the files' bytes split across n chunks.
+func pullStreamN(t *testing.T, key *ecdh.PrivateKey, dir string, n int, mutate func(s *dbreads.Summary, files [][]byte)) *stream {
+ t.Helper()
+ rd := lsfile.NewReplicaClient(dir)
+ plan, err := dbdoor.PlanFrom(context.Background(), rd, time.Time{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ var files [][]byte
+ var all bytes.Buffer
+ for _, f := range plan.Planned {
+ rc, err := rd.OpenLTXFile(context.Background(), f.Level, ltx.TXID(f.MinTXID), ltx.TXID(f.MaxTXID), 0, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, _ := io.ReadAll(rc)
+ rc.Close()
+ files = append(files, b)
+ all.Write(b)
+ }
+ sum := sha256.Sum256(all.Bytes())
+ s := dbreads.Summary{TXID: plan.TXID, At: plan.At, Files: plan.Planned, Bytes: int64(all.Len()), SHA256: hex.EncodeToString(sum[:])}
+ if mutate != nil {
+ mutate(&s, files)
+ }
+ st := newStream(t, key)
+ b := all.Bytes()
+ per := (len(b) + n - 1) / n
+ for seq := 1; seq <= n; seq++ {
+ part := b[min((seq-1)*per, len(b)):min(seq*per, len(b))]
+ sealed, err := dbreads.SealChunk(key.PublicKey(), fwdID, int64(seq), dbreads.StreamLTX, seq == n, part)
+ if err != nil {
+ t.Fatal(err)
+ }
+ st.line(dbreads.Line{Chunk: int64(seq), Data: sealed})
+ }
+ st.result(dbreads.StateDone, "", int64(n), s)
+ return st
+}
+
+func readPull(t *testing.T, st *stream, key *ecdh.PrivateKey) (*dbdoor.Restored, error) {
+ t.Helper()
+ return readPullIn(t, st, key, t.TempDir())
+}
+
+func readPullIn(t *testing.T, st *stream, key *ecdh.PrivateKey, dir string) (*dbdoor.Restored, error) {
+ t.Helper()
+ sink := &fileSink{dir: filepath.Join(dir, "sealed")}
+ id, res, err := readDBForward(context.Background(), &st.buf, key, "shop.example.com", "uk", dbfFetching, io.Discard, sink, newDBFChunkBound(dbreads.MaxPullBytes, dbreads.PullChunkBytes))
+ if err != nil {
+ return nil, err
+ }
+ return openDBPull(context.Background(), id, key, sink, *res, "shop.example.com", "uk", dir)
+}
+
+func TestForwardedPullRestoresTheFiles(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, 3)
+ for _, n := range []int{1, 4} {
+ key, _ := dbreads.NewReplyKey()
+ out := t.TempDir()
+ r, err := readPullIn(t, pullStreamN(t, key, dir, n, nil), key, out)
+ if err != nil {
+ t.Fatalf("%d chunks: %v", n, err)
+ }
+ db, _ := sql.Open("sqlite", "file:"+r.Path+"?mode=ro")
+ var rows int
+ err = db.QueryRow("SELECT count(*) FROM t").Scan(&rows)
+ db.Close()
+ if err != nil || rows != 30 {
+ t.Fatalf("%d chunks: %d rows, %v", n, rows, err)
+ }
+ // Only the copy is left: each spooled chunk went once its bytes were
+ // in the files (so the two are never both whole on the disk), and
+ // the files went once the copy was restored. dbPullForward removes
+ // the empty spool directory.
+ if left, _ := os.ReadDir(filepath.Join(out, "sealed")); len(left) != 0 {
+ t.Errorf("%d chunks: %d spooled chunks are still there", n, len(left))
+ }
+ if _, err := os.Stat(filepath.Join(out, "replica")); !os.IsNotExist(err) {
+ t.Errorf("%d chunks: the files are still there (%v)", n, err)
+ }
+ }
+}
+
+// Review Focus 3 and plan review findings 22 and 24: a file list that does
+// not add up is DBF-13, never a panic, and no file is created before the
+// list is checked whole. Mutations: drop checkPullManifest's per-file size
+// bounds (red: "sizes -1 and N+1" panics or creates files); drop its sum
+// (red: "sizes that do not sum" creates the first file before failing);
+// drop the duplicate check (red: "a file twice" creates a file); drop the
+// level bound (red: "level 12").
+func TestForwardedPullRefusesFilesThatDoNotAddUp(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, 3)
+ for name, mutate := range map[string]func(s *dbreads.Summary, files [][]byte){
+ "sizes that do not sum": func(s *dbreads.Summary, _ [][]byte) { s.Files[0].Size++ },
+ "a list that ends elsewhere": func(s *dbreads.Summary, _ [][]byte) { s.TXID++ },
+ "no files": func(s *dbreads.Summary, _ [][]byte) { s.Files = nil },
+ "sizes -1 and N+1": func(s *dbreads.Summary, _ [][]byte) {
+ s.Files[1].Size += s.Files[0].Size + 1
+ s.Files[0].Size = -1
+ },
+ "a file twice": func(s *dbreads.Summary, _ [][]byte) {
+ s.Files[1] = s.Files[0]
+ s.Bytes = 0
+ for _, f := range s.Files {
+ s.Bytes += f.Size
+ }
+ },
+ "level 12": func(s *dbreads.Summary, _ [][]byte) { s.Files[0].Level = 12 },
+ "a range that runs back": func(s *dbreads.Summary, _ [][]byte) { s.Files[0].MinTXID = s.Files[0].MaxTXID + 1 },
+ "a size past the pull's cap": func(s *dbreads.Summary, _ [][]byte) { s.Files[0].Size = dbreads.MaxPullBytes + 1 },
+ } {
+ key, _ := dbreads.NewReplyKey()
+ out := t.TempDir()
+ func() {
+ defer func() {
+ if p := recover(); p != nil {
+ t.Errorf("%s: panic %v", name, p)
+ }
+ }()
+ if _, err := readPullIn(t, pullStream(t, key, dir, mutate), key, out); err == nil || err.Error() != fmt.Sprintf(dbfUnchecked, "uk") {
+ t.Errorf("%s: %v", name, err)
+ }
+ }()
+ if _, err := os.Stat(filepath.Join(out, "replica")); !os.IsNotExist(err) {
+ t.Errorf("%s: a file was created before the list was checked (%v)", name, err)
+ }
+ }
+}
+
+// The other endings of a pull: too-large is DBF-17 with the planned bytes
+// and the cap, no-room DBF-24, and the rest the query's mapping.
+func TestForwardedPullEndings(t *testing.T) {
+ t.Parallel()
+ for name, c := range map[string]struct {
+ code string
+ sum dbreads.Summary
+ want string
+ }{
+ "too large": {dbreads.CodeTooLarge, dbreads.Summary{Restored: 3 << 30, Cap: 2 << 30},
+ fmt.Sprintf(dbfPullTooLarge, "shop.example.com", humanBytes(ptr(int64(3<<30))), humanBytes(ptr(int64(2<<30))), "uk")},
+ "no room": {dbreads.CodeNoRoom, dbreads.Summary{}, fmt.Sprintf(dbfPullNoRoom, "uk", "shop.example.com")},
+ "nothing replicated": {dbreads.CodeNothingReplicated, dbreads.Summary{}, dbRestoreError("shop.example.com", dbdoor.ErrNothingReplicated).Error()},
+ } {
+ key, _ := dbreads.NewReplyKey()
+ st := newStream(t, key)
+ st.result(dbreads.StateFailed, c.code, 0, c.sum)
+ if _, err := readPull(t, st, key); err == nil || err.Error() != c.want {
+ t.Errorf("%s: %v, want %q", name, err, c.want)
+ }
+ }
+}
+
+func ptr[T any](v T) *T { return &v }
+
+// Plan review finding 37, at the spool: a chunk shorter than a sealed
+// empty one creates no spool file, and a stream of tiny chunks stops at the
+// bound's count, so the spool never holds more files than a read can make.
+// (TestForwardedQueryBoundsChunkCountAndSize pins the count's derivation; a
+// bound of 10 keeps this test small.) Mutation: add to the sink before
+// admit (red: a file for the short chunk, eleven files for the tiny ones).
+func TestForwardedPullSpoolsNoMalformedOrExcessChunk(t *testing.T) {
+ t.Parallel()
+ key, _ := dbreads.NewReplyKey()
+ for name, write := range map[string]func(s *stream) int{
+ "a chunk shorter than its seal": func(s *stream) int {
+ s.line(dbreads.Line{Chunk: 1, Data: []byte("short")})
+ return 0
+ },
+ "tiny chunks past the count": func(s *stream) int {
+ for seq := int64(1); seq <= 11; seq++ {
+ sealed, _ := dbreads.SealChunk(key.PublicKey(), fwdID, seq, dbreads.StreamLTX, false, []byte("x"))
+ s.line(dbreads.Line{Chunk: seq, Data: sealed})
+ }
+ return 10
+ },
+ } {
+ s := newStream(t, key)
+ want := write(s)
+ dir := filepath.Join(t.TempDir(), "sealed")
+ sink := &fileSink{dir: dir}
+ _, _, err := readDBForward(context.Background(), &s.buf, key, "shop.example.com", "uk", dbfFetching, io.Discard, sink,
+ &dbfChunkBound{maxBytes: dbreads.MaxPullBytes, maxChunks: 10})
+ files, _ := os.ReadDir(dir)
+ if err == nil || err.Error() != fmt.Sprintf(dbfUnchecked, "uk") || len(files) != want {
+ t.Errorf("%s: %v, %d spool files, want %d", name, err, len(files), want)
+ }
+ }
+}
+
+// standInConsole answers the list door with the forward marker offering a
+// pull, and the reads route with body (then holds the request open until
+// the client goes when hold is set). It is a stand-in for the console, so
+// that these tests run dbPull itself.
+func standInConsole(t *testing.T, body []byte, hold bool) dbTarget {
+ t.Helper()
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !strings.HasSuffix(r.URL.Path, "/reads") {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusConflict)
+ json.NewEncoder(w).Encode(dbdoor.ForwardBody{Error: "shop.example.com keeps its data in region uk.",
+ Forward: 1, Region: "uk", ForwardOps: []string{dbreads.OpQuery, dbreads.OpPull}})
+ return
+ }
+ io.Copy(io.Discard, r.Body)
+ w.Header().Set("Content-Type", "application/x-ndjson")
+ w.WriteHeader(http.StatusOK)
+ w.Write(body)
+ w.(http.Flusher).Flush()
+ if hold {
+ <-r.Context().Done()
+ }
+ }))
+ t.Cleanup(ts.Close)
+ return dbTarget{sess: &apiSession{c: newConsoleClient(ts.URL, "tok"), console: ts.URL}, acct: apiAcct{Seg: "acme"},
+ app: "shop", host: "shop.example.com"}
+}
+
+// leftBehind is what a pull left in its temp dir and at --out.
+func leftBehind(t *testing.T, tmp, out string) {
+ t.Helper()
+ if _, err := os.Stat(out); !os.IsNotExist(err) {
+ t.Errorf("something is at --out: %v", err)
+ }
+ if left, _ := filepath.Glob(filepath.Join(tmp, "carlos-db-*")); len(left) != 0 {
+ t.Errorf("the pull's directory is still there: %v", left)
+ }
+}
+
+// Review Focus 1 and plan review finding 23: a spool that fails part way,
+// through dbPull itself, leaves nothing at --out and removes its directory.
+// Not parallel: it sets TMPDIR and dbPullSpoolWrite. Mutation: drop
+// dbPullForward's deferred RemoveAll (red: carlos-db-* is left).
+func TestForwardedPullLeavesNothingWhenTheSpoolFails(t *testing.T) {
+ tmp := t.TempDir()
+ t.Setenv("TMPDIR", tmp)
+ writes := 0
+ dbPullSpoolWrite = func(name string, b []byte, mode os.FileMode) error {
+ if writes++; writes == 3 {
+ return errors.New("no space left on device")
+ }
+ return os.WriteFile(name, b, mode)
+ }
+ t.Cleanup(func() { dbPullSpoolWrite = os.WriteFile })
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, 3)
+ // The stand-in's chunks are sealed to a key the CLI does not hold; the
+ // pull fails at the spool, before anything is opened.
+ key, _ := dbreads.NewReplyKey()
+ st := pullStreamN(t, key, dir, 4, nil)
+ out := filepath.Join(t.TempDir(), "copy.db")
+ if err := dbPull(context.Background(), standInConsole(t, st.buf.Bytes(), false), out); err == nil {
+ t.Fatal("a spool that failed was accepted")
+ }
+ if writes != 3 {
+ t.Fatalf("%d spool writes: the failure was not part way", writes)
+ }
+ leftBehind(t, tmp, out)
+}
+
+// Review Focus 4 and plan review finding 23: Ctrl-C while chunks are
+// spooling, through dbPull itself, is "stopped", with nothing at --out and
+// the directory removed. Not parallel: it sets TMPDIR and dbPullSpoolWrite.
+// Mutation: drop dbPullForward's deferred RemoveAll (red). The binary's
+// SIGINT is Task 9's TestDBForwardPullInterruptedLeavesNothing.
+func TestForwardedPullCtrlCLeavesNothing(t *testing.T) {
+ tmp := t.TempDir()
+ t.Setenv("TMPDIR", tmp)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ dbPullSpoolWrite = func(name string, b []byte, mode os.FileMode) error {
+ err := os.WriteFile(name, b, mode)
+ cancel() // Ctrl-C once the first chunk is on disk
+ return err
+ }
+ t.Cleanup(func() { dbPullSpoolWrite = os.WriteFile })
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, 3)
+ key, _ := dbreads.NewReplyKey()
+ st := pullStreamN(t, key, dir, 4, nil)
+ // Admitted, picked and the first chunk only (newStream writes admitted
+ // and picked first), then the stand-in holds the request.
+ lines := bytes.SplitAfter(st.buf.Bytes(), []byte("\n"))
+ out := filepath.Join(t.TempDir(), "copy.db")
+ err := dbPull(ctx, standInConsole(t, bytes.Join(lines[:3], nil), true), out)
+ if err == nil || err.Error() != "stopped" {
+ t.Fatalf("%v", err)
+ }
+ leftBehind(t, tmp, out)
+}