carlos / platform Public

db forward task 10: the identity check, the create-only election with read-back, ClassRefusal moved to dbreads

serve is a stub here; Task 11 replaces it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 51d0a35b2c3ab7cbcc0754af7983de7df8f68f76 parent 04be05a
5 files changed, +753 −13
  • internal/console/apidb.go +4 −13
  • internal/dbreads/agent.go +310 −0
  • internal/dbreads/agent_test.go +154 −0
  • internal/dbreads/class.go +25 −0
  • internal/dbreads/fixture_test.go +260 −0
diff --git a/internal/console/apidb.go b/internal/console/apidb.go
index fbb0e78b8..b4c7eef47 100644
--- a/internal/console/apidb.go
+++ b/internal/console/apidb.go
@@ -30,6 +30,7 @@ import (
"github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/dbreads"
"github.com/carlosframework/platform/internal/hostclaim"
"github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/provision"
@@ -234,19 +235,9 @@ func (s *Server) resolveDBSource(ctx context.Context, acct *Account, actor, app,
// dbClassRefusal is the class rail as a sentence, or "" for an
// activator-managed exec instance: the only class whose database the
// platform replicates (spec §1 scope). Same three facts the move doors
-// refuse on; the fleet and pool cases are resolveReplica's.
-func dbClassRefusal(rec provision.Record) string {
- if k := rec.Kind; k != "" && k != "instance" {
- return fmt.Sprintf("%s is a %s route. The platform keeps a database copy only for instances.", rec.Host, k)
- }
- if rec.Addr != "" || len(rec.Addrs) > 0 {
- return fmt.Sprintf("%s is served from its own address, so the platform does not manage its database.", rec.Host)
- }
- if !rec.HibernateOrDefault() {
- return fmt.Sprintf("%s does not sleep, so the platform does not keep a copy of its database.", rec.Host)
- }
- return ""
-}
+// refuse on; the fleet and pool cases are resolveReplica's. The rule lives
+// in dbreads.ClassRefusal (db region forward spec §8.2).
+func dbClassRefusal(rec provision.Record) string { return dbreads.ClassRefusal(rec) }
// dbResidencyRefusal names where the data is, in the vocabulary the
// regions door uses (the home region by its CONSOLE_HOME_REGION name).
diff --git a/internal/dbreads/agent.go b/internal/dbreads/agent.go
new file mode 100644
index 000000000..6ceb7a2cd
--- /dev/null
+++ b/internal/dbreads/agent.go
@@ -0,0 +1,310 @@
+package dbreads
+
+import (
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "net"
+ "os"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ mrand "math/rand/v2"
+
+ "github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/hostclaim"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// AgentConfig is what the box's db-reads loop needs (spec §7, §8).
+// internal/host fills it from the box's environment; tests fill it with
+// stand-ins.
+type AgentConfig struct {
+ Store release.Store // the deployment bucket
+ Region string // CARLOS_REGION
+ Box string // this box's label, as its edges file names it
+ Boot string // this agent process's id
+ Pub ed25519.PublicKey // CARLOS_RELEASE_PUBKEY
+ HibernatePrefix string // CARLOS_HIBERNATE_PREFIX
+ // OpenReplica opens the read side of this box's own region bucket at a
+ // prefix the agent derived (lease.ReadReplicaClient in production).
+ OpenReplica func(ctx context.Context, prefix string) (dbdoor.ReplicaReader, error)
+ // DialWorker connects to carlos-dbread.socket.
+ DialWorker func(ctx context.Context) (net.Conn, error)
+ // Units counts carlos-dbread@ units active, activating or deactivating.
+ Units func(ctx context.Context) (int, error)
+ // Free reads the filesystem holding /var/tmp.
+ Free func() (avail, total uint64, err error)
+ MaxRestored int64 // DefaultMaxRestored when zero
+ Now func() time.Time
+ Jitter func() time.Duration // 0 to MaxJitter
+ Logf func(format string, args ...any)
+ // Draining is this box's own published draining flag (its edges file's
+ // draining field); a draining box takes no new read. Never draining
+ // when nil.
+ Draining func() bool
+
+ // Test seams; zero is the spec's value.
+ OwnerDeadline time.Duration
+ PlanBudget time.Duration
+ CancelEvery time.Duration
+ ChunkEvery time.Duration
+ MaxOutput int64
+}
+
+// Agent is the box's half of forwarded reads (spec §8.1): it lists the
+// region's queue, verifies requests, elects an owner, runs the identity
+// bracket around planning and download, streams bytes to a worker, and
+// seals and writes output. It never opens SQLite, decodes pages, runs SQL or
+// writes a file.
+type Agent struct {
+ cfg AgentConfig
+ adm *admission
+
+ mu sync.Mutex
+ decided map[string]time.Time
+
+ probeOK atomic.Bool
+ probeAfter chan struct{}
+ reads sync.WaitGroup
+}
+
+func NewAgent(cfg AgentConfig) *Agent {
+ if cfg.MaxRestored <= 0 {
+ cfg.MaxRestored = DefaultMaxRestored
+ }
+ if cfg.Now == nil {
+ cfg.Now = time.Now
+ }
+ if cfg.Jitter == nil {
+ cfg.Jitter = func() time.Duration { return mrand.N(MaxJitter) }
+ }
+ if cfg.Logf == nil {
+ cfg.Logf = func(string, ...any) {}
+ }
+ if cfg.Draining == nil {
+ cfg.Draining = func() bool { return false }
+ }
+ if cfg.OwnerDeadline == 0 {
+ cfg.OwnerDeadline = OwnerDeadline
+ }
+ if cfg.PlanBudget == 0 {
+ cfg.PlanBudget = PlanBudget
+ }
+ if cfg.CancelEvery == 0 {
+ cfg.CancelEvery = CancelEvery
+ }
+ if cfg.ChunkEvery == 0 {
+ cfg.ChunkEvery = ChunkEvery
+ }
+ if cfg.MaxOutput == 0 {
+ cfg.MaxOutput = MaxOutputBytes
+ }
+ return &Agent{cfg: cfg, adm: newAdmission(cfg.Units, cfg.Free), decided: map[string]time.Time{},
+ probeAfter: make(chan struct{}, 1)}
+}
+
+// Capable is whether this box may publish db-read-1: its last readiness
+// probe passed (spec §7.1).
+func (a *Agent) Capable() bool { return a.probeOK.Load() }
+
+// Wait blocks until every read this agent owns has written its result.
+func (a *Agent) Wait() { a.reads.Wait() }
+
+func (a *Agent) now() time.Time { return a.cfg.Now().UTC() }
+
+func (a *Agent) logf(format string, args ...any) { a.cfg.Logf(format, args...) }
+
+func (a *Agent) decide(id string) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.decided[id] = a.now()
+}
+
+func (a *Agent) isDecided(id string) bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ _, ok := a.decided[id]
+ return ok
+}
+
+// prune forgets decisions older than any listing can show again.
+func (a *Agent) prune(now time.Time) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ for id, at := range a.decided {
+ if now.Sub(at) > 2*time.Hour {
+ delete(a.decided, id)
+ }
+ }
+}
+
+// askProbe asks the loop for a probe now: a read's worker failed to start
+// (spec §7.1).
+func (a *Agent) askProbe() {
+ select {
+ case a.probeAfter <- struct{}{}:
+ default:
+ }
+}
+
+// closeThenProbe gives the failed worker's connection slot back before
+// asking for a probe, so admission sees the worker's unit as the orphan it
+// now is and holds the probe until the unit has stopped (plan review
+// finding 29). The deferred Close that follows is a no-op (countedConn).
+func closeThenProbe(a *Agent, conn net.Conn) {
+ conn.Close()
+ a.askProbe()
+}
+
+// countedConn gives a worker connection's slot back exactly once.
+type countedConn struct {
+ net.Conn
+ once sync.Once
+ adm *admission
+}
+
+func (c *countedConn) Close() error {
+ err := c.Conn.Close()
+ c.once.Do(c.adm.closed)
+ return err
+}
+
+// dial opens a worker connection inside the three the socket allows.
+func (a *Agent) dial(ctx context.Context) (net.Conn, error) {
+ if !a.adm.opened() {
+ return nil, errBusy
+ }
+ c, err := a.cfg.DialWorker(ctx)
+ if err != nil {
+ a.adm.closed()
+ return nil, err
+ }
+ return &countedConn{Conn: c, adm: a.adm}, nil
+}
+
+// check is one half of the identity bracket (spec §8.2): the record read
+// fresh, and refused unless it is the instance the envelope named, still a
+// replicated instance, still in this box's region and not moving. A class,
+// pool or fleet change after the console admitted the read is a record
+// change.
+func (a *Agent) check(ctx context.Context, req Request) (provision.Record, string, error) {
+ rec, err := provision.GetRecord(ctx, a.cfg.Store, req.Account, req.App, req.Host)
+ if errors.Is(err, os.ErrNotExist) {
+ return provision.Record{}, CodeRecordChanged, nil
+ }
+ if err != nil {
+ return provision.Record{}, "", err
+ }
+ inc, ierr := hostclaim.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ _, fleet := registry.FleetPlacement(rec.Region)
+ switch {
+ case ierr != nil, inc != req.Incarnation, rec.Account != req.Account, rec.App != req.App,
+ rec.Host != req.Host, !provision.ValidHostShape(rec.Host), ClassRefusal(*rec) != "",
+ rec.Pool != "", fleet, rec.Region != a.cfg.Region:
+ return *rec, CodeRecordChanged, nil
+ case rec.Move != nil:
+ return *rec, CodeMoving, nil
+ }
+ return *rec, "", nil
+}
+
+func nonce() string {
+ var b [16]byte
+ rand.Read(b[:])
+ return hex.EncodeToString(b[:])
+}
+
+// elect is J3: the first create of picked owns the read. A create that
+// answers an error or a conflict is decided by reading picked back: this
+// agent's own nonce owns it, anything else, or a read that fails, does not.
+func (a *Agent) elect(ctx context.Context, id string) (Picked, bool) {
+ p := Picked{Box: a.cfg.Box, Boot: a.cfg.Boot, Nonce: nonce(), Deadline: a.now().Add(a.cfg.OwnerDeadline)}
+ body, err := json.Marshal(p)
+ if err != nil {
+ return Picked{}, false
+ }
+ if _, err := a.cfg.Store.Put(ctx, PickedKey(id), body, ""); err == nil {
+ return p, true
+ }
+ raw, _, err := a.cfg.Store.Get(ctx, PickedKey(id))
+ if err != nil {
+ return Picked{}, false
+ }
+ var got Picked
+ if json.Unmarshal(raw, &got) != nil || got.Nonce != p.Nonce {
+ return Picked{}, false
+ }
+ return got, true
+}
+
+// consider decides one in-window queue entry (spec §5.5 step 4): read and
+// verify the request against its entry, check admission, wait the jitter,
+// and enter the election. A refused or forged request is decided, and so
+// logged once. A read that fails admission is not decided: a later pass may
+// admit it while the window lasts.
+func (a *Agent) consider(ctx context.Context, e QueueEntry) {
+ raw, _, err := a.cfg.Store.Get(ctx, RequestKey(e.ID))
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ a.decide(e.ID)
+ a.logf("dbreads: %s: a queue entry with no request; ignored", e.ID)
+ }
+ return
+ }
+ req, err := Verify(a.cfg.Pub, raw, e.ID, a.cfg.Region, a.now())
+ if err == nil && !QueueMatches(e, req) {
+ err = ErrEnvelope
+ }
+ if err != nil {
+ a.decide(e.ID)
+ a.logf("dbreads: %s: refused the request: %v", e.ID, err)
+ return
+ }
+ // A request whose console has already given up (its request ended
+ // before it was announced) is never picked (spec §5.5 step 4).
+ if _, _, err := a.cfg.Store.Get(ctx, CancelKey(e.ID)); err == nil {
+ a.decide(e.ID)
+ return
+ }
+ // A draining box does not enter the election (spec §7.1, D2).
+ if a.cfg.Draining() {
+ return
+ }
+ if err := a.adm.admitRead(ctx, e.ID); err != nil {
+ return
+ }
+ if d := a.cfg.Jitter(); d > 0 {
+ select {
+ case <-ctx.Done():
+ a.adm.abandon(e.ID)
+ return
+ case <-time.After(d):
+ }
+ }
+ // It may have started draining during the jitter.
+ if a.cfg.Draining() {
+ a.adm.abandon(e.ID)
+ return
+ }
+ p, owned := a.elect(ctx, e.ID)
+ a.decide(e.ID)
+ if !owned {
+ a.adm.abandon(e.ID)
+ return
+ }
+ a.reads.Add(1)
+ go a.serve(ctx, req, p)
+}
+
+// serve is Task 11's.
+func (a *Agent) serve(_ context.Context, req Request, _ Picked) {
+ defer a.reads.Done()
+ defer a.adm.finish(req.ID)
+}
diff --git a/internal/dbreads/agent_test.go b/internal/dbreads/agent_test.go
new file mode 100644
index 000000000..572599600
--- /dev/null
+++ b/internal/dbreads/agent_test.go
@@ -0,0 +1,154 @@
+package dbreads
+
+import (
+ "context"
+ "errors"
+ "math/rand/v2"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The identity check (spec §8.2): the record as the envelope named it, or a
+// code. T9's stages are Task 11's; this is the check itself.
+func TestCheckIsTheRecordAsTheEnvelopeNamedIt(t *testing.T) {
+ t.Parallel()
+ no := false
+ for name, c := range map[string]struct {
+ change func(fx *fixture)
+ want string
+ }{
+ "unchanged": {func(*fixture) {}, ""},
+ "moved to another region": {func(fx *fixture) { r := fx.record(); r.Region = "ie"; fx.putRecord(r) }, CodeRecordChanged},
+ "moving": {func(fx *fixture) {
+ r := fx.record()
+ r.Move = &provision.MoveState{ID: "mv_x", To: "ie", State: "requested"}
+ fx.putRecord(r)
+ }, CodeMoving},
+ "recreated in the account": {func(fx *fixture) { r := fx.record(); r.CreatedAt = r.CreatedAt.Add(time.Hour); fx.putRecord(r) }, CodeRecordChanged},
+ "recreated in another account": {func(fx *fixture) {
+ created := fx.record().CreatedAt
+ fx.store.Delete(context.Background(), provision.RecordKey(fxAccount, fxApp, fxHost))
+ fx.putRecordUnder("bac", provision.Record{Region: "uk", CreatedAt: created})
+ }, CodeRecordChanged},
+ "no longer sleeps": {func(fx *fixture) { r := fx.record(); r.Hibernate = &no; fx.putRecord(r) }, CodeRecordChanged},
+ "pooled": {func(fx *fixture) { r := fx.record(); r.Pool = "shared"; fx.putRecord(r) }, CodeRecordChanged},
+ "placed on a fleet": {func(fx *fixture) { r := fx.record(); r.Region = "fleet/acme"; fx.putRecord(r) }, CodeRecordChanged},
+ } {
+ t.Run(name, func(t *testing.T) {
+ t.Parallel()
+ fx := newFixture(t, 0)
+ req := fx.request("SELECT 1", "")
+ c.change(fx)
+ a, _ := fx.agent("uk-1")
+ _, code, err := a.check(context.Background(), req)
+ if err != nil || code != c.want {
+ t.Fatalf("check = %q, %v; want %q", code, err, c.want)
+ }
+ })
+ }
+}
+
+// T5: two capable boxes in one region; exactly one owns each read, across
+// 1,000 reads with random jitter.
+func TestElectionOneOwnerAcrossTwoAgents(t *testing.T) {
+ t.Parallel()
+ fx := newFixture(t, 0)
+ a, _ := fx.agent("uk-1")
+ b, _ := fx.agent("uk-2")
+ var mu sync.Mutex
+ owners := map[string]int{}
+ var wg sync.WaitGroup
+ for i := 0; i < 1000; i++ {
+ id, err := MintID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, ag := range []*Agent{a, b} {
+ wg.Add(1)
+ go func(ag *Agent) {
+ defer wg.Done()
+ time.Sleep(rand.N(2 * time.Millisecond))
+ if _, ok := ag.elect(context.Background(), id); ok {
+ mu.Lock()
+ owners[id]++
+ mu.Unlock()
+ }
+ }(ag)
+ }
+ }
+ wg.Wait()
+ if len(owners) != 1000 {
+ t.Fatalf("%d reads have an owner, want 1000", len(owners))
+ }
+ for id, n := range owners {
+ if n != 1 {
+ t.Fatalf("%s has %d owners", id, n)
+ }
+ }
+}
+
+// lossyStore commits some Puts and then answers an error: a response lost
+// on the way back (T5, codex 16).
+type lossyStore struct {
+ release.Store
+ lose func(key string) bool
+ refuse func(key string) bool
+}
+
+func (s lossyStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if s.refuse != nil && s.refuse(key) {
+ return "", errors.New("connection reset before the write")
+ }
+ etag, err := s.Store.Put(ctx, key, body, ifMatch)
+ if err == nil && s.lose != nil && s.lose(key) {
+ return "", errors.New("connection reset after the write")
+ }
+ return etag, err
+}
+
+// A box whose picked create commits but answers an error reads it back and
+// owns the read.
+func TestElectionReadsBackALostAnswer(t *testing.T) {
+ t.Parallel()
+ fx := newFixture(t, 0)
+ a, _ := fx.agent("uk-1", func(c *AgentConfig, _ *inProcWorkers) {
+ c.Store = lossyStore{Store: fx.store, lose: func(string) bool { return true }}
+ })
+ if _, ok := a.elect(context.Background(), "dbr_aaaaaaaaaaaaaaaaaaaaaaaaaa"); !ok {
+ t.Fatal("a lost answer to a create that landed was not owned")
+ }
+}
+
+// A box whose create answers an error while another box owns the read steps
+// away; so does one whose read-back fails.
+func TestElectionStepsAwayFromAnotherOwner(t *testing.T) {
+ t.Parallel()
+ fx := newFixture(t, 0)
+ a, _ := fx.agent("uk-1")
+ id := "dbr_aaaaaaaaaaaaaaaaaaaaaaaaaa"
+ if _, ok := a.elect(context.Background(), id); !ok {
+ t.Fatal("the first create did not own")
+ }
+ b, _ := fx.agent("uk-2", func(c *AgentConfig, _ *inProcWorkers) {
+ c.Store = lossyStore{Store: fx.store, refuse: func(string) bool { return true }}
+ })
+ if _, ok := b.elect(context.Background(), id); ok {
+ t.Fatal("a box owned a read another box had picked")
+ }
+ c, _ := fx.agent("uk-3", func(cfg *AgentConfig, _ *inProcWorkers) {
+ cfg.Store = failingGets{lossyStore{Store: fx.store, refuse: func(string) bool { return true }}}
+ })
+ if _, ok := c.elect(context.Background(), "dbr_bbbbbbbbbbbbbbbbbbbbbbbbbb"); ok {
+ t.Fatal("a box owned a read it could not read back")
+ }
+}
+
+type failingGets struct{ release.Store }
+
+func (failingGets) Get(context.Context, string) ([]byte, string, error) {
+ return nil, "", errors.New("timeout")
+}
diff --git a/internal/dbreads/class.go b/internal/dbreads/class.go
new file mode 100644
index 000000000..65d7ecd17
--- /dev/null
+++ b/internal/dbreads/class.go
@@ -0,0 +1,25 @@
+package dbreads
+
+import (
+ "fmt"
+
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+// ClassRefusal is the class rail as a sentence, or "" for an
+// activator-managed exec instance: the only class whose database the
+// platform replicates. It moved here from the console's db door so the door
+// and the box's identity bracket refuse on one rule (spec §8.2); the
+// sentences are the door's, unchanged.
+func ClassRefusal(rec provision.Record) string {
+ if k := rec.Kind; k != "" && k != "instance" {
+ return fmt.Sprintf("%s is a %s route. The platform keeps a database copy only for instances.", rec.Host, k)
+ }
+ if rec.Addr != "" || len(rec.Addrs) > 0 {
+ return fmt.Sprintf("%s is served from its own address, so the platform does not manage its database.", rec.Host)
+ }
+ if !rec.HibernateOrDefault() {
+ return fmt.Sprintf("%s does not sleep, so the platform does not keep a copy of its database.", rec.Host)
+ }
+ return ""
+}
diff --git a/internal/dbreads/fixture_test.go b/internal/dbreads/fixture_test.go
new file mode 100644
index 000000000..bcf0e7582
--- /dev/null
+++ b/internal/dbreads/fixture_test.go
@@ -0,0 +1,260 @@
+package dbreads
+
+import (
+ "bytes"
+ "context"
+ "crypto/ecdh"
+ "crypto/ed25519"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "net"
+ "os"
+ "sort"
+ "sync"
+ "sync/atomic"
+ "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/hostclaim"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+const fxAccount, fxApp, fxHost = "bab", "shop", "shop.example.com"
+
+// inProcWorkers runs the real ServeWorker in process over net.Pipe: not
+// acceptance (Task 15 drives the installed units). units counts the live
+// workers, the way the box counts carlos-dbread@ units.
+type inProcWorkers struct {
+ t *testing.T
+ opt WorkerOptions
+ live atomic.Int64
+ dials atomic.Int64
+ // linger keeps a finished worker counted as a live unit for a while,
+ // as systemd's deactivation does; liveAtDial records the live count
+ // each dial saw.
+ linger time.Duration
+ mu sync.Mutex
+ liveAtDial []int64
+ // failStart makes the worker end at once without a word, as a unit
+ // whose service fails to start after the socket accepted does.
+ failStart atomic.Bool
+}
+
+func (w *inProcWorkers) dial(context.Context) (net.Conn, error) {
+ agentEnd, workerEnd := net.Pipe()
+ w.mu.Lock()
+ w.liveAtDial = append(w.liveAtDial, w.live.Load())
+ w.mu.Unlock()
+ w.dials.Add(1)
+ w.live.Add(1)
+ if w.failStart.Load() {
+ // The socket accepted and the service died: the plan's header is
+ // read by nobody useful, and the connection drops.
+ go func() {
+ readFrame(workerEnd)
+ workerEnd.Close()
+ time.Sleep(w.linger)
+ w.live.Add(-1)
+ }()
+ return agentEnd, nil
+ }
+ opt := w.opt
+ if opt.Scratch == "" {
+ opt.Scratch = w.t.TempDir()
+ }
+ if opt.Exit == nil {
+ opt.Exit = func(int) {}
+ }
+ if opt.Self == nil {
+ opt.Self = func() HelloReply { return HelloReply{V: ProtocolVersion, Interfaces: []string{"lo"}} }
+ }
+ go func() {
+ ServeWorker(workerEnd, opt)
+ workerEnd.Close()
+ time.Sleep(w.linger)
+ w.live.Add(-1)
+ }()
+ return agentEnd, nil
+}
+
+func (w *inProcWorkers) units(context.Context) (int, error) { return int(w.live.Load()), nil }
+
+func plentyFree() (uint64, uint64, error) { return 100 << 30, 200 << 30, nil }
+
+type fixture struct {
+ t *testing.T
+ store release.Store
+ rootPub ed25519.PublicKey
+ rootPriv ed25519.PrivateKey
+ reply *ecdh.PrivateKey
+ replica string
+ now time.Time
+}
+
+// newFixture is a deployment store holding shop.example.com's record in uk,
+// and a file replica of its database with batches*10 rows.
+func newFixture(t *testing.T, batches int) *fixture {
+ t.Helper()
+ pub, priv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ reply, err := NewReplyKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ fx := &fixture{t: t, store: release.NewDirStore(t.TempDir()), rootPub: pub, rootPriv: priv, reply: reply,
+ replica: t.TempDir(), now: time.Now().UTC().Truncate(time.Second)}
+ if batches > 0 {
+ dbdoortest.Replicate(t, fx.replica, batches)
+ }
+ fx.putRecord(provision.Record{Host: fxHost, Region: "uk", CreatedAt: time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC)})
+ return fx
+}
+
+func (fx *fixture) putRecordUnder(acct string, rec provision.Record) {
+ fx.t.Helper()
+ rec.Account, rec.App = acct, fxApp
+ if rec.Host == "" {
+ rec.Host = fxHost
+ }
+ if rec.Hibernate == nil {
+ yes := true
+ rec.Hibernate = &yes
+ }
+ body, err := json.Marshal(rec)
+ if err != nil {
+ fx.t.Fatal(err)
+ }
+ key := provision.RecordKey(acct, fxApp, rec.Host)
+ if err := fx.store.Delete(context.Background(), key); err != nil {
+ fx.t.Fatal(err)
+ }
+ if _, err := fx.store.Put(context.Background(), key, body, ""); err != nil {
+ fx.t.Fatal(err)
+ }
+}
+
+func (fx *fixture) putRecord(rec provision.Record) { fx.putRecordUnder(fxAccount, rec) }
+
+func (fx *fixture) record() provision.Record {
+ fx.t.Helper()
+ rec, err := provision.GetRecord(context.Background(), fx.store, fxAccount, fxApp, fxHost)
+ if err != nil {
+ fx.t.Fatal(err)
+ }
+ return *rec
+}
+
+// request is the envelope the console would sign for the current record.
+func (fx *fixture) request(sqlText, at string) Request {
+ fx.t.Helper()
+ rec := fx.record()
+ inc, err := hostclaim.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ if err != nil {
+ fx.t.Fatal(err)
+ }
+ id, err := MintID()
+ if err != nil {
+ fx.t.Fatal(err)
+ }
+ return Request{ID: id, Account: fxAccount, App: fxApp, Host: fxHost, Incarnation: inc, Region: "uk",
+ Op: OpQuery, SQL: sqlText, At: at, ReplyKey: EncodeReplyKey(fx.reply.PublicKey()),
+ By: "member@example.com", IssuedAt: fx.now.Format(time.RFC3339)}
+}
+
+// submit is the console's two creates: the signed request, then the queue
+// entry.
+func (fx *fixture) submit(req Request) QueueEntry {
+ fx.t.Helper()
+ wire, err := Sign(release.RootSigner(fx.rootPriv), req)
+ if err != nil {
+ fx.t.Fatal(err)
+ }
+ if _, err := fx.store.Put(context.Background(), RequestKey(req.ID), wire, ""); err != nil {
+ fx.t.Fatal(err)
+ }
+ issued, _ := req.Issued()
+ key := QueueKey(req.Region, issued, req.ID)
+ if _, err := fx.store.Put(context.Background(), key, nil, ""); err != nil {
+ fx.t.Fatal(err)
+ }
+ e, _ := ParseQueueKey(key)
+ return e
+}
+
+// agent is a capable agent in uk over the fixture's store and replica.
+// Its probe is Task 12's: it starts capable.
+func (fx *fixture) agent(box string, mut ...func(*AgentConfig, *inProcWorkers)) (*Agent, *inProcWorkers) {
+ w := &inProcWorkers{t: fx.t}
+ cfg := AgentConfig{
+ Store: fx.store, Region: "uk", Box: box, Boot: "boot-" + box, Pub: fx.rootPub, HibernatePrefix: "instances",
+ OpenReplica: func(_ context.Context, prefix string) (dbdoor.ReplicaReader, error) {
+ if prefix != "instances/"+fxHost {
+ fx.t.Errorf("the agent asked for prefix %q", prefix)
+ }
+ return lsfile.NewReplicaClient(fx.replica), nil
+ },
+ Units: w.units, Free: plentyFree, Logf: fx.t.Logf,
+ Jitter: func() time.Duration { return 0 },
+ }
+ for _, m := range mut {
+ m(&cfg, w)
+ }
+ cfg.DialWorker = w.dial
+ a := NewAgent(cfg)
+ a.probeOK.Store(true)
+ return a, w
+}
+
+// chunkKeys lists a read's chunk objects.
+func (fx *fixture) chunkKeys(id string) []string {
+ keys, err := fx.store.List(context.Background(), OutPrefix(id))
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ fx.t.Fatal(err)
+ }
+ sort.Strings(keys)
+ return keys
+}
+
+// answer reads a read's result and opens its chunks as the CLI would.
+func (fx *fixture) answer(id string) ([]byte, Summary, Result) {
+ fx.t.Helper()
+ raw, _, err := fx.store.Get(context.Background(), ResultKey(id))
+ if err != nil {
+ fx.t.Fatalf("no result for %s: %v", id, err)
+ }
+ var r Result
+ if err := json.Unmarshal(raw, &r); err != nil || r.Valid() != nil {
+ fx.t.Fatalf("result %s: %v", raw, err)
+ }
+ s, err := OpenSummary(fx.reply, id, r.Sealed)
+ if err != nil {
+ fx.t.Fatal(err)
+ }
+ var out bytes.Buffer
+ for seq := int64(1); seq <= r.LastSeq; seq++ {
+ sealed, _, err := fx.store.Get(context.Background(), ChunkKey(id, seq))
+ if err != nil {
+ fx.t.Fatalf("chunk %d: %v", seq, err)
+ }
+ plain, err := OpenChunk(fx.reply, id, seq, StreamRows, seq == r.LastSeq, sealed)
+ if err != nil {
+ fx.t.Fatalf("chunk %d: %v", seq, err)
+ }
+ out.Write(plain)
+ }
+ sum := sha256.Sum256(out.Bytes())
+ if r.State == StateDone && (int64(out.Len()) != s.Bytes || hex.EncodeToString(sum[:]) != s.SHA256) {
+ fx.t.Fatalf("the answer does not add up: %d bytes, summary %+v", out.Len(), s)
+ }
+ return out.Bytes(), s, r
+}