db forward task 14: dbreadstest, and T6's parity half against the in-region door
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+262
−0
internal/console/dbreads_parity_test.go+103 −0internal/dbreads/dbreadstest/dbreadstest.go+159 −0
diff --git a/internal/console/dbreads_parity_test.go b/internal/console/dbreads_parity_test.go| new file mode 100644 |
| index 000000000..cff2d5d15 |
| --- /dev/null |
| +++ b/internal/console/dbreads_parity_test.go |
| @@ -0,0 +1,103 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "database/sql" |
| + "encoding/json" |
| + "path/filepath" |
| + "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/hostclaim" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// The parity half of spec T6 that needs no console server (plan 1): the box |
| +// path (dbreads.Agent through the real worker code, joined in process: not |
| +// acceptance for the units) and the CLI's in-region path (dbdoor.RestoreAsOf |
| +// over this package's own door code, replicaDoer and listReplicaLevel, then |
| +// dbquery.RunContext) print the same bytes, as of the same transaction: the |
| +// newest copy, a time between writes, and a time in the same second as a |
| +// write. Plan 2's T6 runs the same comparison through the console server and |
| +// the CLI binary. |
| +func TestDBReadsParityWithTheInRegionDoor(t *testing.T) { |
| + const host = "shop.example.com" |
| + dir := t.TempDir() |
| + src := filepath.Join(t.TempDir(), "shop.db") |
| + db, err := sql.Open("sqlite", src) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer db.Close() |
| + exec := func(q string, args ...any) { |
| + t.Helper() |
| + if _, err := db.Exec(q, args...); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + nextSecond := func() time.Time { |
| + time.Sleep(time.Until(time.Now().Truncate(time.Second).Add(time.Second + 10*time.Millisecond))) |
| + return time.Now() |
| + } |
| + exec(`PRAGMA journal_mode=WAL; CREATE TABLE orders (id INTEGER PRIMARY KEY, note TEXT, data BLOB, at DATETIME)`) |
| + exec(`INSERT INTO orders (note, data, at) VALUES (?, ?, ?), (NULL, NULL, NULL), (?, ?, ?)`, |
| + "a\ttab", []byte{0, 0xff}, time.Date(2026, 10, 7, 14, 0, 0, 0, time.UTC), |
| + "two\nlines", []byte("x"), time.Date(2026, 10, 7, 14, 0, 1, 500, time.UTC)) |
| + dbdoortest.Sync(t, src, dir) |
| + between := nextSecond() |
| + nextSecond() |
| + exec(`INSERT INTO orders (note) VALUES ('later')`) |
| + dbdoortest.Sync(t, src, dir) |
| + sameSecond := time.Now() // in the second the last file was written |
| + nextSecond() |
| + |
| + store := release.NewDirStore(t.TempDir()) |
| + pub, priv, _ := ed25519.GenerateKey(rand.Reader) |
| + yes := true |
| + rec := provision.Record{Host: host, App: "shop", Account: "bab", Region: "uk", Hibernate: &yes, CreatedAt: time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC)} |
| + body, _ := json.Marshal(rec) |
| + if _, err := store.Put(context.Background(), provision.RecordKey("bab", "shop", host), body, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + inc, _ := hostclaim.Incarnation("bab", "shop", host, rec.CreatedAt) |
| + box := dbreadstest.Start(t, dbreadstest.Options{Store: store, Region: "uk", Box: "uk-1", Pub: pub, HibernatePrefix: "instances", |
| + OpenReplica: func(context.Context, string) (dbdoor.ReplicaReader, error) { return lsfile.NewReplicaClient(dir), nil }}) |
| + const query = "SELECT id, note, data, at FROM orders ORDER BY id" |
| + for name, at := range map[string]time.Time{"newest": {}, "between writes": between, "same second as a write": sameSecond} { |
| + got, err := dbdoor.RestoreAsOf(context.Background(), dbdoor.NewClient(replicaDoer(lsfile.NewReplicaClient(dir))), t.TempDir(), at) |
| + if err != nil { |
| + t.Fatalf("%s: in-region: %v", name, err) |
| + } |
| + var want bytes.Buffer |
| + if err := dbquery.RunContext(context.Background(), &want, got.Path, query, dbquery.Options{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + reply, _ := dbreads.NewReplyKey() |
| + id, _ := dbreads.MintID() |
| + atRaw := "" |
| + if !at.IsZero() { |
| + atRaw = at.UTC().Format(time.RFC3339Nano) |
| + } |
| + req := dbreads.Request{ID: id, Account: "bab", App: "shop", Host: host, Incarnation: inc, Region: "uk", |
| + Op: dbreads.OpQuery, SQL: query, At: atRaw, ReplyKey: dbreads.EncodeReplyKey(reply.PublicKey()), |
| + By: "member@example.com", IssuedAt: time.Now().UTC().Format(time.RFC3339)} |
| + dbreadstest.Submit(t, store, priv, req) |
| + box.Serve(t, store, id, 30*time.Second) |
| + rows, s, r := dbreadstest.Answer(t, store, id, reply, dbreads.StreamRows) |
| + if r.State != dbreads.StateDone || !bytes.Equal(rows, want.Bytes()) || s.TXID != got.TXID || !s.At.Equal(got.At) { |
| + t.Fatalf("%s: box %+v txid %d at %v rows %q; in-region txid %d at %v rows %q", |
| + name, r, s.TXID, s.At, rows, got.TXID, got.At, want.Bytes()) |
| + } |
| + } |
| +} |
diff --git a/internal/dbreads/dbreadstest/dbreadstest.go b/internal/dbreads/dbreadstest/dbreadstest.go| new file mode 100644 |
| index 000000000..874714933 |
| --- /dev/null |
| +++ b/internal/dbreads/dbreadstest/dbreadstest.go |
| @@ -0,0 +1,159 @@ |
| +// Package dbreadstest runs the box's half of a forwarded read inside a test |
| +// process: the real dbreads.Agent and the real dbreads.ServeWorker, joined by |
| +// net.Pipe instead of the installed socket. Test support only. It is not |
| +// acceptance for the units (internal/host's root-runner tests are), and |
| +// nothing outside a _test.go file may import it. |
| +package dbreadstest |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ecdh" |
| + "crypto/ed25519" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "net" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/dbdoor" |
| + "github.com/carlosframework/platform/internal/dbreads" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +type Options struct { |
| + Store release.Store |
| + Region string |
| + Box string |
| + Pub ed25519.PublicKey |
| + HibernatePrefix string |
| + OpenReplica func(ctx context.Context, prefix string) (dbdoor.ReplicaReader, error) |
| + MaxRestored int64 |
| + // Worker's Scratch, Exit and Self are filled in when empty. |
| + Worker dbreads.WorkerOptions |
| +} |
| + |
| +type Box struct { |
| + Agent *dbreads.Agent |
| + Dials atomic.Int64 |
| + live atomic.Int64 |
| + worker dbreads.WorkerOptions |
| +} |
| + |
| +// Start builds a capable in-process box: its probe passes against an |
| +// in-process worker reporting a sandboxed view. |
| +func Start(t testing.TB, o Options) *Box { |
| + t.Helper() |
| + b := &Box{worker: o.Worker} |
| + if b.worker.Scratch == "" { |
| + b.worker.Scratch = t.TempDir() |
| + } |
| + if b.worker.Exit == nil { |
| + b.worker.Exit = func(int) {} |
| + } |
| + if b.worker.Self == nil { |
| + b.worker.Self = func() dbreads.HelloReply { |
| + return dbreads.HelloReply{V: dbreads.ProtocolVersion, Interfaces: []string{"lo"}} |
| + } |
| + } |
| + b.Agent = dbreads.NewAgent(dbreads.AgentConfig{ |
| + Store: o.Store, Region: o.Region, Box: o.Box, Boot: "boot-" + o.Box, Pub: o.Pub, |
| + HibernatePrefix: o.HibernatePrefix, OpenReplica: o.OpenReplica, |
| + DialWorker: b.dial, Units: b.units, |
| + Free: func() (uint64, uint64, error) { return 100 << 30, 200 << 30, nil }, |
| + MaxRestored: o.MaxRestored, Jitter: func() time.Duration { return 0 }, Logf: t.Logf, |
| + }) |
| + b.Agent.Probe(context.Background()) |
| + if !b.Agent.Capable() { |
| + t.Fatal("dbreadstest: the in-process box failed its probe") |
| + } |
| + return b |
| +} |
| + |
| +func (b *Box) dial(context.Context) (net.Conn, error) { |
| + agentEnd, workerEnd := net.Pipe() |
| + b.Dials.Add(1) |
| + b.live.Add(1) |
| + go func() { |
| + defer b.live.Add(-1) |
| + dbreads.ServeWorker(workerEnd, b.worker) |
| + workerEnd.Close() |
| + }() |
| + return agentEnd, nil |
| +} |
| + |
| +func (b *Box) units(context.Context) (int, error) { return int(b.live.Load()), nil } |
| + |
| +// Serve passes until the read's result exists. |
| +func (b *Box) Serve(t testing.TB, store release.Store, id string, timeout time.Duration) { |
| + t.Helper() |
| + deadline := time.Now().Add(timeout) |
| + for time.Now().Before(deadline) { |
| + b.Agent.Pass(context.Background()) |
| + b.Agent.Wait() |
| + if _, _, err := store.Get(context.Background(), dbreads.ResultKey(id)); err == nil { |
| + return |
| + } |
| + time.Sleep(20 * time.Millisecond) |
| + } |
| + t.Fatalf("dbreadstest: no result for %s within %s", id, timeout) |
| +} |
| + |
| +// Submit is the console's two creates for req, signed with root: for tests |
| +// that have no console. |
| +func Submit(t testing.TB, store release.Store, root ed25519.PrivateKey, req dbreads.Request) { |
| + t.Helper() |
| + wire, err := dbreads.Sign(release.RootSigner(root), req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := store.Put(context.Background(), dbreads.RequestKey(req.ID), wire, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + issued, err := req.Issued() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := store.Put(context.Background(), dbreads.QueueKey(req.Region, issued, req.ID), nil, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// Answer reads a read's result and opens its chunks with the CLI's key, |
| +// checking the count and hash a done read's summary carries. |
| +func Answer(t testing.TB, store release.Store, id string, priv *ecdh.PrivateKey, stream string) ([]byte, dbreads.Summary, dbreads.Result) { |
| + t.Helper() |
| + raw, _, err := store.Get(context.Background(), dbreads.ResultKey(id)) |
| + if err != nil { |
| + t.Fatalf("dbreadstest: no result for %s: %v", id, err) |
| + } |
| + var r dbreads.Result |
| + if err := json.Unmarshal(raw, &r); err != nil || r.Valid() != nil { |
| + t.Fatalf("dbreadstest: result %s: %v", raw, err) |
| + } |
| + s, err := dbreads.OpenSummary(priv, id, r.Sealed) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var out bytes.Buffer |
| + for seq := int64(1); seq <= r.LastSeq; seq++ { |
| + sealed, _, err := store.Get(context.Background(), dbreads.ChunkKey(id, seq)) |
| + if err != nil { |
| + t.Fatalf("dbreadstest: chunk %d: %v", seq, err) |
| + } |
| + plain, err := dbreads.OpenChunk(priv, id, seq, stream, seq == r.LastSeq, sealed) |
| + if err != nil { |
| + t.Fatalf("dbreadstest: chunk %d: %v", seq, err) |
| + } |
| + out.Write(plain) |
| + } |
| + if r.State == dbreads.StateDone { |
| + sum := sha256.Sum256(out.Bytes()) |
| + if int64(out.Len()) != s.Bytes || hex.EncodeToString(sum[:]) != s.SHA256 { |
| + t.Fatalf("dbreadstest: the answer does not add up: %d bytes, summary %+v", out.Len(), s) |
| + } |
| + } |
| + return out.Bytes(), s, r |
| +} |