carlos / platform Public

dbreads: the agent's pull: its cap, its reservation, the ltx stream and the file list

A pull's cap is on its planned LTX bytes (MaxPull: MaxPullBytes, lowered
by CARLOS_DB_PULL_MAX_BYTES, and never above what the worker holds), its
reservation is the LTX bytes alone, and its output is the held files as
the ltx stream in 1 MiB chunks with the plan in the summary. Its too-large
and no-room endings wait for check B like every replica-derived ending
(Astra round 1, finding 2), where the plan wrote fail. Plan 1's two timing
lines stay, the first saying held through for a pull.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 608c4dabf696a41d67b0882151d26ee120795dd2 parent cd59925
7 files changed, +334 −16
  • internal/dbreads/agent.go +15 −3
  • internal/dbreads/fixture_test.go +26 −2
  • internal/dbreads/pull_test.go +164 −0
  • internal/dbreads/read.go +36 −8
  • internal/host/dbreads.go +15 −3
  • internal/host/dbreads_rootrunner_linux_test.go +48 −0
  • internal/host/dbreads_test.go +30 −0
diff --git a/internal/dbreads/agent.go b/internal/dbreads/agent.go
index 41e6ddb79..78ac62fee 100644
--- a/internal/dbreads/agent.go
+++ b/internal/dbreads/agent.go
@@ -43,9 +43,13 @@ type AgentConfig struct {
// 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)
+ // MaxPull is a pull's cap on its planned LTX files: MaxPullBytes when
+ // zero or larger, so no box ships more than a CLI accepts, and never
+ // more than the worker holds (PlanBytesFactor times MaxRestored).
+ MaxPull int64
+ 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.
@@ -80,6 +84,14 @@ func NewAgent(cfg AgentConfig) *Agent {
if cfg.MaxRestored <= 0 {
cfg.MaxRestored = DefaultMaxRestored
}
+ if cfg.MaxPull <= 0 || cfg.MaxPull > MaxPullBytes {
+ cfg.MaxPull = MaxPullBytes
+ }
+ // The worker refuses a plan whose files total more than this (its
+ // planWithinBounds), so a pull over it ends too-large here instead.
+ if held := PlanBytesFactor * cfg.MaxRestored; cfg.MaxPull > held {
+ cfg.MaxPull = held
+ }
if cfg.Now == nil {
cfg.Now = time.Now
}
diff --git a/internal/dbreads/fixture_test.go b/internal/dbreads/fixture_test.go
index bcf0e7582..c4a481a30 100644
--- a/internal/dbreads/fixture_test.go
+++ b/internal/dbreads/fixture_test.go
@@ -46,6 +46,30 @@ type inProcWorkers struct {
// 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
+ // sent is the type of every frame the agent wrote, in order.
+ sent []byte
+}
+
+// frameTap records the first byte of each Write the agent makes: one frame
+// type per frame (writeFrame writes a frame in one Write).
+type frameTap struct {
+ net.Conn
+ w *inProcWorkers
+}
+
+func (f frameTap) Write(p []byte) (int, error) {
+ if len(p) > 0 {
+ f.w.mu.Lock()
+ f.w.sent = append(f.w.sent, p[0])
+ f.w.mu.Unlock()
+ }
+ return f.Conn.Write(p)
+}
+
+func (w *inProcWorkers) sentFrames() []byte {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ return append([]byte(nil), w.sent...)
}
func (w *inProcWorkers) dial(context.Context) (net.Conn, error) {
@@ -64,7 +88,7 @@ func (w *inProcWorkers) dial(context.Context) (net.Conn, error) {
time.Sleep(w.linger)
w.live.Add(-1)
}()
- return agentEnd, nil
+ return frameTap{Conn: agentEnd, w: w}, nil
}
opt := w.opt
if opt.Scratch == "" {
@@ -82,7 +106,7 @@ func (w *inProcWorkers) dial(context.Context) (net.Conn, error) {
time.Sleep(w.linger)
w.live.Add(-1)
}()
- return agentEnd, nil
+ return frameTap{Conn: agentEnd, w: w}, nil
}
func (w *inProcWorkers) units(context.Context) (int, error) { return int(w.live.Load()), nil }
diff --git a/internal/dbreads/pull_test.go b/internal/dbreads/pull_test.go
index d0cd95476..ac0886a3b 100644
--- a/internal/dbreads/pull_test.go
+++ b/internal/dbreads/pull_test.go
@@ -4,7 +4,10 @@ import (
"bytes"
"context"
"encoding/json"
+ "fmt"
"io"
+ "strings"
+ "sync"
"testing"
"time"
@@ -116,3 +119,164 @@ func TestWorkerHoldStopsWithoutSending(t *testing.T) {
t.Fatal(err)
}
}
+
+func (fx *fixture) pullRequest(at string) Request {
+ req := fx.request("", at)
+ req.Op = OpPull
+ return req
+}
+
+// answerPull opens a pull's chunks as the CLI does: the ltx stream.
+func (fx *fixture) answerPull(id string) ([]byte, Summary, Result) {
+ fx.t.Helper()
+ raw, _, err := fx.store.Get(context.Background(), ResultKey(id))
+ if err != nil {
+ fx.t.Fatal(err)
+ }
+ var r Result
+ if err := json.Unmarshal(raw, &r); err != nil {
+ fx.t.Fatal(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, _, _ := fx.store.Get(context.Background(), ChunkKey(id, seq))
+ plain, err := OpenChunk(fx.reply, id, seq, StreamLTX, seq == r.LastSeq, sealed)
+ if err != nil {
+ fx.t.Fatalf("chunk %d: %v", seq, err)
+ }
+ out.Write(plain)
+ }
+ return out.Bytes(), s, r
+}
+
+// plannedBytes is dir's planned files, concatenated in plan order.
+func plannedBytes(t *testing.T, dir string) (dbdoor.RestorePlan, []byte) {
+ t.Helper()
+ rd := lsfile.NewReplicaClient(dir)
+ plan, err := dbdoor.PlanFrom(context.Background(), rd, time.Time{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ var want 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)
+ }
+ io.Copy(&want, rc)
+ rc.Close()
+ }
+ return plan, want.Bytes()
+}
+
+// The agent's pull ships the planned files whole, in plan order, as the
+// ltx stream in chunks of at most PullChunkBytes, with the file list in the
+// summary, and logs plan 1's two timing lines (plan review finding 26).
+// Mutation: drop the timing lines (red).
+func TestPullShipsThePlannedFiles(t *testing.T) {
+ t.Parallel()
+ fx := newFixture(t, 4)
+ var logMu sync.Mutex
+ var logs []string
+ a, _ := fx.agent("uk-1", func(c *AgentConfig, _ *inProcWorkers) {
+ c.Logf = func(format string, args ...any) {
+ logMu.Lock()
+ defer logMu.Unlock()
+ logs = append(logs, fmt.Sprintf(format, args...))
+ }
+ })
+ req := fx.pullRequest("")
+ fx.submit(req)
+ a.Pass(context.Background())
+ a.Wait()
+ got, s, r := fx.answerPull(req.ID)
+ plan, want := plannedBytes(t, fx.replica)
+ if r.State != StateDone || !bytes.Equal(got, want) || s.TXID != plan.TXID || len(s.Files) != len(plan.Planned) || s.Bytes != plan.LTXBytes {
+ t.Fatalf("result %+v summary %+v: %d bytes, want %d", r, s, len(got), len(want))
+ }
+ for i, f := range s.Files {
+ if f.Level != plan.Planned[i].Level || f.MinTXID != plan.Planned[i].MinTXID || f.MaxTXID != plan.Planned[i].MaxTXID || f.Size != plan.Planned[i].Size {
+ t.Fatalf("file %d is %+v, planned %+v", i, f, plan.Planned[i])
+ }
+ }
+ for seq := int64(1); seq < r.LastSeq; seq++ {
+ sealed, _, _ := fx.store.Get(context.Background(), ChunkKey(req.ID, seq))
+ if len(sealed)-SealOverhead > PullChunkBytes {
+ t.Fatalf("chunk %d is %d bytes", seq, len(sealed))
+ }
+ }
+ // Task 1's measurement reads these two lines (plan review finding 26).
+ logMu.Lock()
+ all := strings.Join(logs, "\n")
+ logMu.Unlock()
+ if !strings.Contains(all, "and held through") || !strings.Contains(all, "confirmed chunks in") {
+ t.Fatalf("the pull's timing lines are missing:\n%s", all)
+ }
+}
+
+// A pull over the agent's cap ends too-large with the planned bytes and the
+// cap, and a record change after the last byte left the bucket (T9 for a
+// pull) writes no chunk and never sends the worker run. Mutation: the
+// agent's pull sends run before check B (red: the recorded frames hold a
+// run).
+func TestPullTooLargeAndNoChunkBeforeCheckB(t *testing.T) {
+ t.Parallel()
+ fx := newFixture(t, 2)
+ a, _ := fx.agent("uk-1", func(c *AgentConfig, _ *inProcWorkers) { c.MaxPull = 100 })
+ req := fx.pullRequest("")
+ fx.submit(req)
+ a.Pass(context.Background())
+ a.Wait()
+ _, s, r := fx.answerPull(req.ID)
+ if r.Code != CodeTooLarge || s.Cap != 100 || s.Restored <= 100 {
+ t.Fatalf("%+v %+v", r, s)
+ }
+ fx2 := newFixture(t, 2)
+ plan, _ := plannedBytes(t, fx2.replica)
+ last := plan.Planned[len(plan.Planned)-1]
+ hook := &stageHook{ReplicaReader: lsfile.NewReplicaClient(fx2.replica), stage: "after the last byte",
+ lastSpan: dbdoor.Span(last.MinTXID, last.MaxTXID), change: func() { r := fx2.record(); r.Region = "ie"; fx2.putRecord(r) }}
+ b, w := fx2.agent("uk-1", func(c *AgentConfig, _ *inProcWorkers) {
+ c.OpenReplica = func(context.Context, string) (dbdoor.ReplicaReader, error) { return hook, nil }
+ })
+ req2 := fx2.pullRequest("")
+ fx2.submit(req2)
+ b.Pass(context.Background())
+ b.Wait()
+ if _, _, r := fx2.answerPull(req2.ID); r.Code != CodeRecordChanged || len(fx2.chunkKeys(req2.ID)) != 0 {
+ t.Fatalf("%+v, chunks %v", r, fx2.chunkKeys(req2.ID))
+ }
+ // The worker never heard run: check B failed, so the agent said stop
+ // (plan review finding 24). Without this, an agent that sent run first
+ // and refused the files afterwards would pass the two checks above.
+ sent := w.sentFrames()
+ if !bytes.Contains(sent, []byte{frameStop}) {
+ t.Fatalf("the agent never said stop: %q", sent)
+ }
+ if bytes.Contains(sent, []byte{frameRun}) {
+ t.Fatalf("the agent sent run before check B passed: %q", sent)
+ }
+}
+
+// Plan review finding 24: NewAgent itself clamps the pull's cap, whatever a
+// box's settings hand it. Mutation: NewAgent keeps a MaxPull above
+// MaxPullBytes (red).
+func TestNewAgentClampsMaxPull(t *testing.T) {
+ t.Parallel()
+ fx := newFixture(t, 1)
+ for give, want := range map[int64]int64{0: MaxPullBytes, -1: MaxPullBytes, 1 << 20: 1 << 20, MaxPullBytes + 1: MaxPullBytes} {
+ a, _ := fx.agent("uk-1", func(c *AgentConfig, _ *inProcWorkers) { c.MaxPull = give })
+ if a.cfg.MaxPull != want {
+ t.Errorf("MaxPull %d became %d, want %d", give, a.cfg.MaxPull, want)
+ }
+ }
+ // Never more than the worker holds: PlanBytesFactor times MaxRestored.
+ a, _ := fx.agent("uk-1", func(c *AgentConfig, _ *inProcWorkers) { c.MaxRestored = 256 << 20 })
+ if a.cfg.MaxPull != PlanBytesFactor*(256<<20) {
+ t.Errorf("MaxPull %d with a 256 MiB restored cap", a.cfg.MaxPull)
+ }
+}
diff --git a/internal/dbreads/read.go b/internal/dbreads/read.go
index c3443a52f..b3aafa8ce 100644
--- a/internal/dbreads/read.go
+++ b/internal/dbreads/read.go
@@ -183,10 +183,21 @@ func (a *Agent) attempt(ctx context.Context, req Request, pub *ecdh.PublicKey, a
a.logf("dbreads: %s: plan: %v", req.ID, err)
return fail(CodeInterrupted, Summary{})
}
- if plan.RestoredBytes > a.cfg.MaxRestored {
+ // A pull's cap is on the files it ships, a query's on the copy it
+ // restores (spec §5.7). Both endings are the replica's word, so both wait
+ // for check B (Astra round 1, finding 2).
+ pull := req.Op == OpPull
+ switch {
+ case pull && plan.LTXBytes > a.cfg.MaxPull:
+ return failB(CodeTooLarge, Summary{Restored: plan.LTXBytes, Cap: a.cfg.MaxPull})
+ case !pull && plan.RestoredBytes > a.cfg.MaxRestored:
return failB(CodeTooLarge, Summary{Restored: plan.RestoredBytes, Cap: a.cfg.MaxRestored})
}
- if err := a.adm.grow(req.ID, plan.LTXBytes+plan.RestoredBytes); err != nil {
+ need := plan.LTXBytes + plan.RestoredBytes
+ if pull {
+ need = plan.LTXBytes // the worker holds the files and restores nothing
+ }
+ if err := a.adm.grow(req.ID, need); err != nil {
return failB(CodeNoRoom, Summary{})
}
conn, err := a.dial(pctx)
@@ -242,20 +253,37 @@ func (a *Agent) attempt(ctx context.Context, req Request, pub *ecdh.PublicKey, a
}
return refuse(code)
}
- stopPlanBound() // the query is bounded by the worker and the owner's deadline
- // Phase timings, for operators and for plan 3's throughput measurement:
- // planning and the worker's restore, then the output's sealing and
- // confirmed creates.
- a.logf("dbreads: %s: planned %d files (%d bytes) and restored to %d in %s", req.ID, plan.Files, plan.LTXBytes, plan.TXID, time.Since(attemptStart).Round(time.Millisecond))
+ stopPlanBound() // the run is bounded by the worker and the owner's deadline
+ stream, size, max := StreamRows, ChunkBytes, a.cfg.MaxOutput
+ if pull {
+ stream, size, max = StreamLTX, PullChunkBytes, plan.LTXBytes
+ }
+ // Phase timings, for operators and for plan 3's throughput measurement
+ // (plan review finding 26): a query's first phase plans and restores, a
+ // pull's plans and has the worker verify and hold the files; then the
+ // output's sealing and confirmed creates.
+ held := "restored to"
+ if pull {
+ held = "held through"
+ }
+ a.logf("dbreads: %s: planned %d files (%d bytes) and %s %d in %s", req.ID, plan.Files, plan.LTXBytes, held, plan.TXID, time.Since(attemptStart).Round(time.Millisecond))
runStart := time.Now()
if err := writeJSONFrame(conn, frameRun, runMsg{SQL: req.SQL}); err != nil {
return fail(CodeInterrupted, Summary{})
}
- cw := newChunkWriter(ctx, a.cfg.Store, req.ID, pub, StreamRows, a.cfg.ChunkEvery, a.cfg.MaxOutput, ChunkBytes)
+ cw := newChunkWriter(ctx, a.cfg.Store, req.ID, pub, stream, a.cfg.ChunkEvery, max, size)
endCode, sqlErr, rerr := relay(conn, cw)
last, n, sum, werr := cw.close()
a.logf("dbreads: %s: output %d bytes in %d confirmed chunks in %s", req.ID, n, last, time.Since(runStart).Round(time.Millisecond))
s := Summary{TXID: plan.TXID, At: plan.At, Bytes: n, SHA256: sum, Error: sqlErr}
+ if pull {
+ s.Files = plan.Planned
+ // A worker that sends more or less than it held is a check
+ // failure, never an output cap.
+ if werr == nil && rerr == nil && endCode == "" && (cw.capped() || n != plan.LTXBytes) {
+ return a.ended(pub, req.ID, StateFailed, CodeCheckFailed, Summary{}, last), false
+ }
+ }
switch {
case werr != nil:
a.logf("dbreads: %s: write output: %v", req.ID, werr)
diff --git a/internal/host/dbreads.go b/internal/host/dbreads.go
index a836646ff..777dc8a60 100644
--- a/internal/host/dbreads.go
+++ b/internal/host/dbreads.go
@@ -26,6 +26,8 @@ const (
// (carlos-dbread.socket says why).
dbReadSocketPath = "/run/carlos/dbread/worker.sock"
dbReadMaxBytesEnv = "CARLOS_DB_READ_MAX_BYTES"
+ // dbPullMaxBytesEnv can only lower a pull's cap (spec §5.7, rev 7).
+ dbPullMaxBytesEnv = "CARLOS_DB_PULL_MAX_BYTES"
dbReadsSwitchEnv = "CARLOS_DB_READS"
)
@@ -33,6 +35,7 @@ type dbReadsEnv struct {
region string
pub ed25519.PublicKey
maxRestored int64
+ maxPull int64
}
// dbReadsSettings is the environment half of spec §7.1's conditions:
@@ -57,7 +60,7 @@ func dbReadsSettings(getenv func(string) string) (dbReadsEnv, string) {
if err != nil {
return dbReadsEnv{}, err.Error()
}
- env := dbReadsEnv{region: region, pub: pub, maxRestored: dbreads.DefaultMaxRestored}
+ env := dbReadsEnv{region: region, pub: pub, maxRestored: dbreads.DefaultMaxRestored, maxPull: dbreads.MaxPullBytes}
if raw := strings.TrimSpace(getenv(dbReadMaxBytesEnv)); raw != "" {
n, err := strconv.ParseInt(raw, 10, 64)
if err != nil || n <= 0 {
@@ -65,6 +68,15 @@ func dbReadsSettings(getenv func(string) string) (dbReadsEnv, string) {
}
env.maxRestored = n
}
+ if raw := strings.TrimSpace(getenv(dbPullMaxBytesEnv)); raw != "" {
+ n, err := strconv.ParseInt(raw, 10, 64)
+ if err != nil || n <= 0 {
+ return dbReadsEnv{}, dbPullMaxBytesEnv + " is not a whole number of bytes"
+ }
+ // Lowering only: no box ships more than a CLI accepts (Review
+ // Focus 5). NewAgent clamps again.
+ env.maxPull = min(n, dbreads.MaxPullBytes)
+ }
return env, ""
}
@@ -143,7 +155,7 @@ func armDBReads(hib activator.Config) {
return lease.ReadReplicaClient(ctx, hib.Bucket, prefix, hib.Region)
},
DialWorker: dialDBReadWorker, Units: dbReadUnits, Free: varTmpFree,
- MaxRestored: env.maxRestored, Logf: log.Printf, Draining: dbReadsDraining.Load,
+ MaxRestored: env.maxRestored, MaxPull: env.maxPull, Logf: log.Printf, Draining: dbReadsDraining.Load,
})
armedDBReads.Store(a)
go a.Run(ctx, dbReadsNudge)
@@ -151,7 +163,7 @@ func armDBReads(hib activator.Config) {
}
// dbReadsHostEnvKeys are the host.env settings dbReadsSettings reads.
-var dbReadsHostEnvKeys = []string{"CARLOS_HIBERNATE_BUCKET", "CARLOS_REGION", "CARLOS_RELEASE_PUBKEY", dbReadsSwitchEnv, "CARLOS_HOST_CLAIM", dbReadMaxBytesEnv}
+var dbReadsHostEnvKeys = []string{"CARLOS_HIBERNATE_BUCKET", "CARLOS_REGION", "CARLOS_RELEASE_PUBKEY", dbReadsSwitchEnv, "CARLOS_HOST_CLAIM", dbReadMaxBytesEnv, dbPullMaxBytesEnv}
// dbReadsSocketWanted is root's half of the dark gate (Astra round 1,
// finding 1): the adopt pass arms carlos-dbread.socket only when the box's
diff --git a/internal/host/dbreads_rootrunner_linux_test.go b/internal/host/dbreads_rootrunner_linux_test.go
index 16d5b61d6..f6dd18cc5 100644
--- a/internal/host/dbreads_rootrunner_linux_test.go
+++ b/internal/host/dbreads_rootrunner_linux_test.go
@@ -9,8 +9,10 @@ import (
"crypto/ecdh"
"crypto/ed25519"
"crypto/rand"
+ "crypto/sha256"
"database/sql"
"encoding/base64"
+ "encoding/hex"
"encoding/json"
"fmt"
"io"
@@ -25,6 +27,7 @@ import (
"time"
lsfile "github.com/benbjohnson/litestream/file"
+ "github.com/superfly/ltx"
"github.com/carlosframework/platform/internal/dbdoor"
"github.com/carlosframework/platform/internal/dbdoor/dbdoortest"
@@ -342,6 +345,51 @@ func TestRootDBReadServesThroughTheInstalledUnits(t *testing.T) {
privateTmpGone(t, 10*time.Second)
}
+// A forwarded pull through the real socket and the real service (plan 3
+// Task 5): the installed worker verifies and holds the planned files and
+// sends them back after check B; the answer, opened as the ltx stream, is
+// the planned files byte for byte in plan order, and adds up to the sealed
+// summary. The worker's private tmp is gone afterwards.
+func TestRootDBReadPullThroughTheInstalledUnits(t *testing.T) {
+ r := newDBReadRunner(t, "40g")
+ id, reply := r.submit(dbreads.OpPull, "")
+ rep, _ := r.payload("serve", true, id)
+ if rep["capable"] != true {
+ t.Fatalf("the installed worker failed its probe: %v", rep)
+ }
+ got, res := r.answer(id, reply, dbreads.StreamLTX)
+ if res.State != dbreads.StateDone || res.Code != "" {
+ t.Fatalf("result %+v", res)
+ }
+ sum, err := dbreads.OpenSummary(reply, id, res.Sealed)
+ if err != nil {
+ t.Fatal(err)
+ }
+ h := sha256.Sum256(got)
+ if hex.EncodeToString(h[:]) != sum.SHA256 || int64(len(got)) != sum.Bytes {
+ t.Fatalf("%d bytes do not add up to the summary %+v", len(got), sum)
+ }
+ rd := lsfile.NewReplicaClient(filepath.Join(r.dir, "replica", "instances", dbreadRunnerHost))
+ plan, err := dbdoor.PlanFrom(context.Background(), rd, time.Time{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ var want 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)
+ }
+ io.Copy(&want, rc)
+ rc.Close()
+ }
+ if !bytes.Equal(got, want.Bytes()) || sum.TXID != plan.TXID || len(sum.Files) != len(plan.Planned) {
+ t.Fatalf("pulled %d bytes at %d in %d files; planned %d bytes at %d in %d files",
+ len(got), sum.TXID, len(sum.Files), want.Len(), plan.TXID, len(plan.Planned))
+ }
+ privateTmpGone(t, 10*time.Second)
+}
+
// T3: from inside the worker, nothing outside its scratch is reachable,
// including any network interface but loopback; the private tmp is gone
// after a normal end, a cancel and kill -9 of the agent. Mutation: remove
diff --git a/internal/host/dbreads_test.go b/internal/host/dbreads_test.go
index 620804c23..542464139 100644
--- a/internal/host/dbreads_test.go
+++ b/internal/host/dbreads_test.go
@@ -252,3 +252,33 @@ func TestEnsureSystemUnitsKeepsTheDBReadSocketDarkWithoutTheGate(t *testing.T) {
}
}
}
+
+// Review Focus 5: the pull's cap can only be lowered on a box. Mutation:
+// dbReadsSettings keeps a CARLOS_DB_PULL_MAX_BYTES above the cap (red).
+func TestPullCapOnlyLowers(t *testing.T) {
+ t.Parallel()
+ pub, _, _ := ed25519.GenerateKey(rand.Reader)
+ base := map[string]string{"CARLOS_HIBERNATE_BUCKET": "d", "CARLOS_REGION": "uk", "CARLOS_RELEASE_PUBKEY": base64.StdEncoding.EncodeToString(pub)}
+ get := func(v string) func(string) string {
+ return func(k string) string {
+ if k == "CARLOS_DB_PULL_MAX_BYTES" {
+ return v
+ }
+ return base[k]
+ }
+ }
+ if env, why := dbReadsSettings(get("")); why != "" || env.maxPull != dbreads.MaxPullBytes {
+ t.Fatalf("default %d %q", env.maxPull, why)
+ }
+ if env, why := dbReadsSettings(get("1048576")); why != "" || env.maxPull != 1<<20 {
+ t.Fatalf("lowered %d %q", env.maxPull, why)
+ }
+ if env, why := dbReadsSettings(get("99999999999999")); why != "" || env.maxPull != dbreads.MaxPullBytes {
+ t.Fatalf("raised past the built-in cap: %d %q", env.maxPull, why)
+ }
+ for _, bad := range []string{"0", "-5", "2GB"} {
+ if _, why := dbReadsSettings(get(bad)); why == "" {
+ t.Fatalf("CARLOS_DB_PULL_MAX_BYTES=%s armed the loop", bad)
+ }
+ }
+}