db forward task 11: the owned read, its identity bracket, sealed chunks confirmed before they are named, and the result
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+889
−6
internal/dbreads/agent.go+0 −6internal/dbreads/chunks.go+165 −0internal/dbreads/read.go+298 −0internal/dbreads/read_test.go+426 −0
diff --git a/internal/dbreads/agent.go b/internal/dbreads/agent.go| index 6ceb7a2cd..5217e8b15 100644 |
| --- a/internal/dbreads/agent.go |
| +++ b/internal/dbreads/agent.go |
| @@ -302,9 +302,3 @@ func (a *Agent) consider(ctx context.Context, e QueueEntry) { |
| 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/chunks.go b/internal/dbreads/chunks.go| new file mode 100644 |
| index 000000000..d160a1557 |
| --- /dev/null |
| +++ b/internal/dbreads/chunks.go |
| @@ -0,0 +1,165 @@ |
| +package dbreads |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ecdh" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "errors" |
| + "fmt" |
| + "hash" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +var errCapped = errors.New("dbreads: the output cap was reached") |
| + |
| +// putCreateOnly creates key with body, retrying until it lands or ctx ends. |
| +// An error or a conflict is resolved by reading the key back: the same |
| +// bytes mean an earlier attempt landed (spec §5.4). The caller keeps body |
| +// until this returns, so a retry is the same bytes. |
| +func putCreateOnly(ctx context.Context, s release.Store, key string, body []byte) error { |
| + wait := 250 * time.Millisecond |
| + for { |
| + _, err := s.Put(ctx, key, body, "") |
| + if err == nil { |
| + return nil |
| + } |
| + got, _, gerr := s.Get(ctx, key) |
| + switch { |
| + case gerr == nil && bytes.Equal(got, body): |
| + return nil |
| + case gerr == nil: |
| + return fmt.Errorf("dbreads: %s holds other bytes: %w", key, release.ErrCASConflict) |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + case <-time.After(wait): |
| + } |
| + wait = min(wait*2, 5*time.Second) |
| + } |
| +} |
| + |
| +// chunkWriter seals a read's output into out/<seq> objects: one every |
| +// ChunkBytes, and whatever is pending every `every`; close seals what is |
| +// left, possibly nothing, as the last chunk. Past max nothing more is kept |
| +// and Write answers errCapped. Each put is create-only and confirmed before |
| +// the next is sealed, under the lock, so seqs are in order (the run |
| +// chunker's discipline). |
| +type chunkWriter struct { |
| + ctx context.Context |
| + store release.Store |
| + id string |
| + pub *ecdh.PublicKey |
| + stream string |
| + max int64 |
| + |
| + mu sync.Mutex |
| + pending []byte |
| + seq int64 |
| + total int64 |
| + sum hash.Hash |
| + err error |
| + isCapped bool |
| + |
| + stop chan struct{} |
| + done chan struct{} |
| +} |
| + |
| +func newChunkWriter(ctx context.Context, s release.Store, id string, pub *ecdh.PublicKey, stream string, every time.Duration, max int64) *chunkWriter { |
| + c := &chunkWriter{ctx: ctx, store: s, id: id, pub: pub, stream: stream, max: max, sum: sha256.New(), |
| + stop: make(chan struct{}), done: make(chan struct{})} |
| + go c.tick(every) |
| + return c |
| +} |
| + |
| +func (c *chunkWriter) tick(every time.Duration) { |
| + defer close(c.done) |
| + t := time.NewTicker(every) |
| + defer t.Stop() |
| + for { |
| + select { |
| + case <-c.stop: |
| + return |
| + case <-t.C: |
| + c.mu.Lock() |
| + if len(c.pending) > 0 && c.err == nil { |
| + c.err = c.flushLocked(c.pending, false) |
| + c.pending = nil |
| + } |
| + c.mu.Unlock() |
| + } |
| + } |
| +} |
| + |
| +func (c *chunkWriter) Write(p []byte) (int, error) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if c.err != nil { |
| + return 0, c.err |
| + } |
| + if c.isCapped { |
| + return 0, errCapped |
| + } |
| + capped := false |
| + if room := c.max - c.total; int64(len(p)) > room { |
| + p, capped = p[:room], true |
| + } |
| + c.sum.Write(p) |
| + c.total += int64(len(p)) |
| + c.pending = append(c.pending, p...) |
| + for len(c.pending) >= ChunkBytes { |
| + if err := c.flushLocked(c.pending[:ChunkBytes], false); err != nil { |
| + c.err = err |
| + return 0, err |
| + } |
| + c.pending = append([]byte(nil), c.pending[ChunkBytes:]...) |
| + } |
| + if capped { |
| + c.isCapped = true |
| + return len(p), errCapped |
| + } |
| + return len(p), nil |
| +} |
| + |
| +// flushLocked seals and creates the next chunk. seq moves only once the |
| +// create is confirmed, so close never reports, and no result ever names, a |
| +// chunk that was not confirmed (spec §5.4; plan review finding 9). A chunk |
| +// whose create stayed ambiguous until the context ended may land later at |
| +// seq+1; no result names it, so no reader relays it. |
| +func (c *chunkWriter) flushLocked(b []byte, last bool) error { |
| + next := c.seq + 1 |
| + sealed, err := SealChunk(c.pub, c.id, next, c.stream, last, b) |
| + if err != nil { |
| + return err |
| + } |
| + if err := putCreateOnly(c.ctx, c.store, ChunkKey(c.id, next), sealed); err != nil { |
| + return err |
| + } |
| + c.seq = next |
| + return nil |
| +} |
| + |
| +func (c *chunkWriter) capped() bool { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.isCapped |
| +} |
| + |
| +// close seals the pending bytes as the last chunk and reports the last seq, |
| +// the plaintext byte count and its SHA-256. |
| +func (c *chunkWriter) close() (int64, int64, string, error) { |
| + close(c.stop) |
| + <-c.done |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if c.err == nil { |
| + c.err = c.flushLocked(c.pending, true) |
| + c.pending = nil |
| + } |
| + return c.seq, c.total, hex.EncodeToString(c.sum.Sum(nil)), c.err |
| +} |
diff --git a/internal/dbreads/read.go b/internal/dbreads/read.go| new file mode 100644 |
| index 000000000..c6b9d1c41 |
| --- /dev/null |
| +++ b/internal/dbreads/read.go |
| @@ -0,0 +1,298 @@ |
| +package dbreads |
| + |
| +import ( |
| + "context" |
| + "crypto/ecdh" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net" |
| + "os" |
| + "sync/atomic" |
| + "time" |
| + |
| + "github.com/superfly/ltx" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/dbdoor" |
| +) |
| + |
| +// serve runs one read this agent owns, inside the owner's deadline, and |
| +// writes its result (spec §5.5 step 5). The read slot is given back here; |
| +// the reservation stays until the worker unit is gone (J5). |
| +func (a *Agent) serve(parent context.Context, req Request, p Picked) { |
| + defer a.reads.Done() |
| + defer a.adm.finish(req.ID) |
| + ctx, cancel := context.WithTimeout(parent, a.cfg.OwnerDeadline) |
| + defer cancel() |
| + var cancelled atomic.Bool |
| + go a.watchCancel(ctx, req.ID, cancel, &cancelled) |
| + started := a.now() |
| + res := a.read(ctx, req) |
| + if cancelled.Load() { |
| + res.State, res.Code = StateCancelled, "" |
| + } |
| + res.Box, res.Started, res.Ended = a.cfg.Box, started, a.now() |
| + body, err := json.Marshal(res) |
| + if err == nil { |
| + wctx, wcancel := context.WithTimeout(context.WithoutCancel(parent), 30*time.Second) |
| + err = putCreateOnly(wctx, a.cfg.Store, ResultKey(req.ID), body) |
| + wcancel() |
| + } |
| + if err != nil { |
| + a.logf("dbreads: %s: write the result: %v", req.ID, err) |
| + } |
| +} |
| + |
| +// watchCancel reads cancel every CancelEvery and ends the read when it |
| +// appears: the console's best-effort word that nobody is waiting. |
| +func (a *Agent) watchCancel(ctx context.Context, id string, cancel context.CancelFunc, seen *atomic.Bool) { |
| + t := time.NewTicker(a.cfg.CancelEvery) |
| + defer t.Stop() |
| + for { |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-t.C: |
| + if _, _, err := a.cfg.Store.Get(ctx, CancelKey(id)); err == nil { |
| + seen.Store(true) |
| + cancel() |
| + return |
| + } |
| + } |
| + } |
| +} |
| + |
| +// ended seals the summary into a result. |
| +func (a *Agent) ended(pub *ecdh.PublicKey, id, state, code string, s Summary, last int64) Result { |
| + sealed, err := SealSummary(pub, id, s) |
| + if err != nil { |
| + a.logf("dbreads: %s: seal the summary: %v", id, err) |
| + } |
| + return Result{State: state, Code: code, LastSeq: last, Sealed: sealed} |
| +} |
| + |
| +// read is today's "changed while it was being read" retry, box side: one |
| +// fresh plan, with both checks again, then changed-twice. |
| +func (a *Agent) read(ctx context.Context, req Request) Result { |
| + pub, err := ParseReplyKey(req.ReplyKey) |
| + if err != nil { |
| + return Result{State: StateFailed, Code: CodeInterrupted} |
| + } |
| + at, _ := req.AtTime() |
| + for attempt := 0; attempt < 2; attempt++ { |
| + if attempt > 0 { |
| + // The first attempt's worker may still be stopping: keep its |
| + // reservation, and wait for its unit before the next one (J5). |
| + a.adm.retry(req.ID, attempt) |
| + if err := a.adm.settle(ctx, settlePoll); err != nil { |
| + return a.ended(pub, req.ID, StateFailed, CodeInterrupted, Summary{}, 0) |
| + } |
| + } |
| + if res, retry := a.attempt(ctx, req, pub, at); !retry { |
| + return res |
| + } |
| + } |
| + return a.ended(pub, req.ID, StateFailed, CodeChangedTwice, Summary{}, 0) |
| +} |
| + |
| +// settlePoll is how often a retry rereads the unit listing while it waits. |
| +var settlePoll = 200 * time.Millisecond |
| + |
| +// attempt is the identity bracket (spec §8.2): check A, plan, stream every |
| +// planned file into a worker that restores and checks it, check B after the |
| +// last byte has left the bucket, and only then run. No output exists before |
| +// check B passes. retry is true when a planned file vanished or changed. |
| +func (a *Agent) attempt(ctx context.Context, req Request, pub *ecdh.PublicKey, at time.Time) (Result, bool) { |
| + fail := func(code string, s Summary) (Result, bool) { |
| + return a.ended(pub, req.ID, StateFailed, code, s, 0), false |
| + } |
| + refuse := func(code string) (Result, bool) { |
| + return a.ended(pub, req.ID, StateRefused, code, Summary{}, 0), false |
| + } |
| + attemptStart := time.Now() |
| + pctx, pcancel := context.WithTimeout(ctx, a.cfg.PlanBudget) |
| + defer pcancel() |
| + |
| + rec, code, err := a.check(pctx, req) // check A |
| + if err != nil { |
| + a.logf("dbreads: %s: check A: %v", req.ID, err) |
| + return fail(CodeInterrupted, Summary{}) |
| + } |
| + if code != "" { |
| + return refuse(code) |
| + } |
| + rd, err := a.cfg.OpenReplica(pctx, activator.HibernatePrefix(a.cfg.HibernatePrefix, rec.Host)) |
| + if err != nil { |
| + a.logf("dbreads: %s: open the replica: %v", req.ID, err) |
| + return fail(CodeInterrupted, Summary{}) |
| + } |
| + plan, err := dbdoor.PlanFrom(pctx, rd, at) |
| + var before *dbdoor.BeforeHistoryError |
| + switch { |
| + case errors.Is(err, dbdoor.ErrNothingReplicated): |
| + return fail(CodeNothingReplicated, Summary{}) |
| + case errors.As(err, &before): |
| + return fail(CodeHistoryGone, Summary{Oldest: before.Oldest}) |
| + case errors.Is(err, dbdoor.ErrHistoryGone): |
| + return fail(CodeHistoryGone, Summary{}) |
| + case errors.Is(err, os.ErrNotExist): |
| + return Result{}, true |
| + case err != nil: |
| + a.logf("dbreads: %s: plan: %v", req.ID, err) |
| + return fail(CodeInterrupted, Summary{}) |
| + } |
| + if plan.RestoredBytes > a.cfg.MaxRestored { |
| + return fail(CodeTooLarge, Summary{Restored: plan.RestoredBytes, Cap: a.cfg.MaxRestored}) |
| + } |
| + if err := a.adm.grow(req.ID, plan.LTXBytes+plan.RestoredBytes); err != nil { |
| + return fail(CodeNoRoom, Summary{}) |
| + } |
| + conn, err := a.dial(pctx) |
| + if err != nil { |
| + a.logf("dbreads: %s: the worker did not start: %v", req.ID, err) |
| + a.askProbe() |
| + return fail(CodeInterrupted, Summary{}) |
| + } |
| + defer conn.Close() |
| + defer context.AfterFunc(ctx, func() { conn.Close() })() |
| + stopPlanBound := context.AfterFunc(pctx, func() { conn.Close() }) |
| + defer stopPlanBound() |
| + |
| + if err := writeJSONFrame(conn, frameHeader, planHeader{V: ProtocolVersion, Op: req.Op, Files: plan.Planned, |
| + Target: plan.TXID, MaxRestored: a.cfg.MaxRestored}); err != nil { |
| + closeThenProbe(a, conn) |
| + return fail(CodeInterrupted, Summary{}) |
| + } |
| + for _, f := range plan.Planned { |
| + vanished, err := sendFile(pctx, conn, rd, f) |
| + if vanished { |
| + return Result{}, true |
| + } |
| + if err != nil { |
| + // The worker went before ready: its unit may have failed to |
| + // start after the socket accepted (spec §7.1; plan review |
| + // finding 15). Probe once this connection is closed. |
| + closeThenProbe(a, conn) |
| + return fail(CodeInterrupted, Summary{}) |
| + } |
| + } |
| + typ, p, err := readFrame(conn) |
| + switch { |
| + case err != nil: |
| + closeThenProbe(a, conn) |
| + return fail(CodeInterrupted, Summary{}) |
| + case typ == frameEnd: |
| + var e endMsg |
| + json.Unmarshal(p, &e) |
| + if e.Code != CodeTooLarge { |
| + e.Code = CodeCheckFailed |
| + } |
| + return fail(e.Code, Summary{Error: e.Error, Restored: plan.RestoredBytes, Cap: a.cfg.MaxRestored}) |
| + } |
| + var ready readyMsg |
| + if typ != frameReady || json.Unmarshal(p, &ready) != nil || ready.TXID != plan.TXID { |
| + return fail(CodeCheckFailed, Summary{}) |
| + } |
| + if _, code, err := a.check(pctx, req); err != nil || code != "" { // check B |
| + writeFrame(conn, frameStop, nil) |
| + if err != nil { |
| + return fail(CodeInterrupted, Summary{}) |
| + } |
| + 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)) |
| + 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) |
| + 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} |
| + switch { |
| + case werr != nil: |
| + a.logf("dbreads: %s: write output: %v", req.ID, werr) |
| + return a.ended(pub, req.ID, StateFailed, CodeInterrupted, Summary{}, last), false |
| + case cw.capped(): |
| + return a.ended(pub, req.ID, StateDone, CodeOutputCap, s, last), false |
| + case rerr != nil: |
| + return a.ended(pub, req.ID, StateFailed, CodeInterrupted, Summary{}, last), false |
| + case endCode == "": |
| + return a.ended(pub, req.ID, StateDone, "", s, last), false |
| + case endCode == CodeSQLError, endCode == CodeTimeout: |
| + return a.ended(pub, req.ID, StateFailed, endCode, s, last), false |
| + } |
| + return a.ended(pub, req.ID, StateFailed, CodeInterrupted, Summary{}, last), false |
| +} |
| + |
| +// sendFile streams one planned file, whole, from the bucket into the |
| +// worker. A file that is gone, or not the size the plan listed, vanished |
| +// under the plan: the caller re-plans. |
| +func sendFile(ctx context.Context, w io.Writer, rd dbdoor.ReplicaReader, f dbdoor.LTXFile) (bool, error) { |
| + rc, err := rd.OpenLTXFile(ctx, f.Level, ltx.TXID(f.MinTXID), ltx.TXID(f.MaxTXID), 0, 0) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return true, nil |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + defer rc.Close() |
| + buf := make([]byte, fileFrameBytes) |
| + var sent int64 |
| + for { |
| + n, rerr := rc.Read(buf) |
| + if n > 0 { |
| + if sent+int64(n) > f.Size { |
| + return true, nil |
| + } |
| + if err := writeFrame(w, frameFile, buf[:n]); err != nil { |
| + return false, err |
| + } |
| + sent += int64(n) |
| + } |
| + if rerr == io.EOF { |
| + break |
| + } |
| + if errors.Is(rerr, os.ErrNotExist) { |
| + return true, nil |
| + } |
| + if rerr != nil { |
| + return false, rerr |
| + } |
| + } |
| + return sent != f.Size, nil |
| +} |
| + |
| +// relay moves the worker's output into the chunk writer until the worker's |
| +// end frame, or until the cap: then the agent stops reading and closes the |
| +// connection, which the worker sees as EOF. |
| +func relay(conn net.Conn, cw *chunkWriter) (string, string, error) { |
| + for { |
| + typ, p, err := readFrame(conn) |
| + if err != nil { |
| + return "", "", err |
| + } |
| + switch typ { |
| + case frameOutput: |
| + if _, err := cw.Write(p); errors.Is(err, errCapped) { |
| + return "", "", nil |
| + } else if err != nil { |
| + return "", "", err |
| + } |
| + case frameEnd: |
| + var e endMsg |
| + if json.Unmarshal(p, &e) != nil { |
| + return "", "", errProtocol |
| + } |
| + return e.Code, e.Error, nil |
| + default: |
| + return "", "", errProtocol |
| + } |
| + } |
| +} |
diff --git a/internal/dbreads/read_test.go b/internal/dbreads/read_test.go| new file mode 100644 |
| index 000000000..95d16bb75 |
| --- /dev/null |
| +++ b/internal/dbreads/read_test.go |
| @@ -0,0 +1,426 @@ |
| +package dbreads |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "os" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "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/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func serveOne(t *testing.T, a *Agent, fx *fixture, req Request) ([]byte, Summary, Result) { |
| + t.Helper() |
| + e := fx.submit(req) |
| + a.consider(context.Background(), e) |
| + a.Wait() |
| + return fx.answer(req.ID) |
| +} |
| + |
| +func TestReadServesAQuery(t *testing.T) { |
| + t.Parallel() |
| + fx := newFixture(t, 3) |
| + a, w := fx.agent("uk-1") |
| + rows, s, r := serveOne(t, a, fx, fx.request("SELECT count(*) AS n FROM t", "")) |
| + if r.State != StateDone || r.Code != "" || string(rows) != "n\n30\n" || r.Box != "uk-1" { |
| + t.Fatalf("result %+v, rows %q", r, rows) |
| + } |
| + plan, err := dbdoor.PlanFrom(context.Background(), lsfile.NewReplicaClient(fx.replica), time.Time{}) |
| + if err != nil || s.TXID != plan.TXID || !s.At.Equal(plan.At) { |
| + t.Fatalf("summary %+v, plan %+v %v", s, plan, err) |
| + } |
| + if w.dials.Load() != 1 { |
| + t.Fatalf("%d worker connections for one read", w.dials.Load()) |
| + } |
| +} |
| + |
| +// vanishing makes full-file opens of the first planned file answer |
| +// os.ErrNotExist, `times` times: litestream's compaction removing an L0 |
| +// file under the plan. |
| +type vanishing struct { |
| + dbdoor.ReplicaReader |
| + mu sync.Mutex |
| + times int |
| +} |
| + |
| +func (v *vanishing) OpenLTXFile(ctx context.Context, level int, lo, hi ltx.TXID, off, size int64) (io.ReadCloser, error) { |
| + v.mu.Lock() |
| + gone := off == 0 && size == 0 && v.times > 0 |
| + if gone { |
| + v.times-- |
| + } |
| + v.mu.Unlock() |
| + if gone { |
| + return nil, os.ErrNotExist |
| + } |
| + return v.ReplicaReader.OpenLTXFile(ctx, level, lo, hi, off, size) |
| +} |
| + |
| +// Review Focus 3: one quiet re-plan, then changed-twice, and no chunk. |
| +func TestReadRePlansOnceThenSaysChangedTwice(t *testing.T) { |
| + t.Parallel() |
| + for _, c := range []struct { |
| + times int |
| + want string |
| + }{{1, ""}, {2, CodeChangedTwice}} { |
| + fx := newFixture(t, 2) |
| + v := &vanishing{ReplicaReader: lsfile.NewReplicaClient(fx.replica), times: c.times} |
| + a, _ := fx.agent("uk-1", func(cfg *AgentConfig, _ *inProcWorkers) { |
| + cfg.OpenReplica = func(context.Context, string) (dbdoor.ReplicaReader, error) { return v, nil } |
| + }) |
| + req := fx.request("SELECT count(*) FROM t", "") |
| + _, _, r := serveOne(t, a, fx, req) |
| + if r.Code != c.want { |
| + t.Fatalf("vanished %d times: %+v", c.times, r) |
| + } |
| + if c.want != "" && len(fx.chunkKeys(req.ID)) != 0 { |
| + t.Fatal("a chunk exists for a read that never ran") |
| + } |
| + } |
| +} |
| + |
| +// Plan review finding 10: after a vanished file, the retry waits for the |
| +// first worker's unit to stop before it dials again, and keeps that unit's |
| +// reservation until then. 12 GiB of 20 fits one floor at a time. |
| +// Mutations: drop the settle call in read (the second dial sees a live unit, |
| +// and the retired floor makes the new one no-room); or drop retry's move of |
| +// the old reservation (TestAdmissionRetryHoldsTheOldReservation goes red). |
| +func TestRetryWaitsForTheFirstWorkerToStop(t *testing.T) { |
| + t.Parallel() |
| + fx := newFixture(t, 2) |
| + v := &vanishing{ReplicaReader: lsfile.NewReplicaClient(fx.replica), times: 1} |
| + a, w := fx.agent("uk-1", func(c *AgentConfig, w *inProcWorkers) { |
| + c.OpenReplica = func(context.Context, string) (dbdoor.ReplicaReader, error) { return v, nil } |
| + c.Free = func() (uint64, uint64, error) { return 12 << 30, 20 << 30, nil } |
| + w.linger = 300 * time.Millisecond |
| + }) |
| + _, _, r := serveOne(t, a, fx, fx.request("SELECT count(*) FROM t", "")) |
| + if r.State != StateDone { |
| + t.Fatalf("result %+v", r) |
| + } |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + if len(w.liveAtDial) != 2 || w.liveAtDial[1] != 0 { |
| + t.Fatalf("live units at each dial: %v; the retry dialed beside the first worker", w.liveAtDial) |
| + } |
| +} |
| + |
| +// Plan review finding 15: a worker that ends before ready (its service |
| +// failed after the socket accepted) asks for a probe at once. Mutation: |
| +// drop the askProbe after a pre-ready sendFile or readFrame failure; |
| +// probeAfter stays empty and this test is red. |
| +func TestAWorkerThatNeverStartsAsksForAProbe(t *testing.T) { |
| + t.Parallel() |
| + fx := newFixture(t, 1) |
| + a, _ := fx.agent("uk-1", func(_ *AgentConfig, w *inProcWorkers) { w.failStart.Store(true) }) |
| + _, _, r := serveOne(t, a, fx, fx.request("SELECT 1", "")) |
| + if r.Code != CodeInterrupted || len(a.probeAfter) != 1 { |
| + t.Fatalf("result %+v, probe asked %d", r, len(a.probeAfter)) |
| + } |
| +} |
| + |
| +// stageHook changes the record at one stage of the read: planning (the |
| +// first listing), download (the first full-file open), or after the last |
| +// byte has been read from the bucket (EOF of the last planned file). |
| +type stageHook struct { |
| + dbdoor.ReplicaReader |
| + stage, lastSpan string |
| + once sync.Once |
| + change func() |
| +} |
| + |
| +func (h *stageHook) LTXFiles(ctx context.Context, level int, seek ltx.TXID, m bool) (ltx.FileIterator, error) { |
| + if h.stage == "planning" { |
| + h.once.Do(h.change) |
| + } |
| + return h.ReplicaReader.LTXFiles(ctx, level, seek, m) |
| +} |
| + |
| +func (h *stageHook) OpenLTXFile(ctx context.Context, level int, lo, hi ltx.TXID, off, size int64) (io.ReadCloser, error) { |
| + rc, err := h.ReplicaReader.OpenLTXFile(ctx, level, lo, hi, off, size) |
| + if err != nil || off != 0 || size != 0 { |
| + return rc, err |
| + } |
| + switch { |
| + case h.stage == "download": |
| + h.once.Do(h.change) |
| + case h.stage == "after the last byte" && dbdoor.Span(uint64(lo), uint64(hi)) == h.lastSpan: |
| + return &eofHook{ReadCloser: rc, at: func() { h.once.Do(h.change) }}, nil |
| + } |
| + return rc, nil |
| +} |
| + |
| +type eofHook struct { |
| + io.ReadCloser |
| + at func() |
| +} |
| + |
| +func (e *eofHook) Read(p []byte) (int, error) { |
| + n, err := e.ReadCloser.Read(p) |
| + if err == io.EOF { |
| + e.at() |
| + } |
| + return n, err |
| +} |
| + |
| +// T9: a record change at every stage ends with its code, and no chunk is |
| +// ever written (codex 1). |
| +func TestRecordChangeAtEveryStageWritesNoChunk(t *testing.T) { |
| + t.Parallel() |
| + no := false |
| + changes := map[string]struct { |
| + change func(fx *fixture) |
| + want string |
| + }{ |
| + "moved": {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}, |
| + "class changed": {func(fx *fixture) { r := fx.record(); r.Hibernate = &no; fx.putRecord(r) }, CodeRecordChanged}, |
| + } |
| + for _, stage := range []string{"before the pick", "planning", "download", "after the last byte"} { |
| + for name, c := range changes { |
| + t.Run(stage+"/"+name, func(t *testing.T) { |
| + t.Parallel() |
| + fx := newFixture(t, 2) |
| + plan, err := dbdoor.PlanFrom(context.Background(), lsfile.NewReplicaClient(fx.replica), time.Time{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + last := plan.Planned[len(plan.Planned)-1] |
| + hook := &stageHook{ReplicaReader: lsfile.NewReplicaClient(fx.replica), stage: stage, |
| + lastSpan: dbdoor.Span(last.MinTXID, last.MaxTXID), change: func() { c.change(fx) }} |
| + a, _ := fx.agent("uk-1", func(cfg *AgentConfig, _ *inProcWorkers) { |
| + cfg.OpenReplica = func(context.Context, string) (dbdoor.ReplicaReader, error) { return hook, nil } |
| + }) |
| + req := fx.request("SELECT count(*) FROM t", "") |
| + if stage == "before the pick" { |
| + c.change(fx) |
| + } |
| + _, _, r := serveOne(t, a, fx, req) |
| + if r.State != StateRefused || r.Code != c.want { |
| + t.Fatalf("result %+v, want refused %s", r, c.want) |
| + } |
| + if keys := fx.chunkKeys(req.ID); len(keys) != 0 { |
| + t.Fatalf("chunks written: %v", keys) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestReadTooLargeAndNoRoom(t *testing.T) { |
| + t.Parallel() |
| + fx := newFixture(t, 2) |
| + a, _ := fx.agent("uk-1", func(c *AgentConfig, _ *inProcWorkers) { c.MaxRestored = 1024 }) |
| + _, s, r := serveOne(t, a, fx, fx.request("SELECT 1", "")) |
| + if r.Code != CodeTooLarge || s.Cap != 1024 || s.Restored <= 1024 { |
| + t.Fatalf("too large: %+v %+v", r, s) |
| + } |
| + fx2 := newFixture(t, 2) |
| + b, _ := fx2.agent("uk-1", func(c *AgentConfig, _ *inProcWorkers) { |
| + calls := 0 |
| + c.Free = func() (uint64, uint64, error) { |
| + calls++ |
| + if calls == 1 { // the floor fits; the plan's growth does not |
| + return 11 << 30, 20 << 30, nil |
| + } |
| + return 5<<30 + 1, 20 << 30, nil |
| + } |
| + }) |
| + _, _, r2 := serveOne(t, b, fx2, fx2.request("SELECT 1", "")) |
| + if r2.Code != CodeNoRoom { |
| + t.Fatalf("no room: %+v", r2) |
| + } |
| +} |
| + |
| +// Review Focus 4: the cap is exact, a row bigger than a chunk is split, and |
| +// the summary covers exactly the kept bytes. |
| +func TestChunkWriterCapIsExact(t *testing.T) { |
| + t.Parallel() |
| + for _, extra := range []int{0, 1} { |
| + fx := newFixture(t, 0) |
| + max := int64(3*ChunkBytes + 7) |
| + cw := newChunkWriter(context.Background(), fx.store, "dbr_aaaaaaaaaaaaaaaaaaaaaaaaaa", fx.reply.PublicKey(), StreamRows, time.Hour, max) |
| + big := bytes.Repeat([]byte("x"), 2*ChunkBytes+5) |
| + rest := bytes.Repeat([]byte("y"), int(max)-len(big)+extra) |
| + cw.Write(big) |
| + _, err := cw.Write(rest) |
| + if (extra == 1) != (err == errCapped) || cw.capped() != (extra == 1) { |
| + t.Fatalf("extra %d: Write = %v, capped %v", extra, err, cw.capped()) |
| + } |
| + last, n, sum, err := cw.close() |
| + if err != nil || n != max { |
| + t.Fatalf("extra %d: kept %d of %d: %v", extra, n, max, err) |
| + } |
| + want := sha256.Sum256(append(append([]byte{}, big...), rest[:int(max)-len(big)]...)) |
| + if sum != hex.EncodeToString(want[:]) { |
| + t.Fatal("the summary hash is not the kept bytes'") |
| + } |
| + for seq := int64(1); seq <= last; seq++ { |
| + sealed, _, err := fx.store.Get(context.Background(), ChunkKey("dbr_aaaaaaaaaaaaaaaaaaaaaaaaaa", seq)) |
| + if err != nil || len(sealed)-SealOverhead > ChunkBytes { |
| + t.Fatalf("chunk %d: %d bytes, %v", seq, len(sealed), err) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// The output cap end to end: done, output-cap, and exactly the cap kept. |
| +func TestReadOutputCap(t *testing.T) { |
| + t.Parallel() |
| + fx := newFixture(t, 2) |
| + a, _ := fx.agent("uk-1", func(c *AgentConfig, _ *inProcWorkers) { c.MaxOutput = 100 }) |
| + rows, s, r := serveOne(t, a, fx, fx.request("SELECT body FROM t", "")) |
| + if r.State != StateDone || r.Code != CodeOutputCap || len(rows) != 100 || s.Bytes != 100 { |
| + t.Fatalf("result %+v, %d bytes", r, len(rows)) |
| + } |
| +} |
| + |
| +func TestCancelStopsTheOwner(t *testing.T) { |
| + t.Parallel() |
| + fx := newFixture(t, 2) |
| + hang := make(chan struct{}) |
| + t.Cleanup(func() { close(hang) }) |
| + a, _ := fx.agent("uk-1", func(c *AgentConfig, w *inProcWorkers) { |
| + c.CancelEvery = 20 * time.Millisecond |
| + w.opt.Restore = func(ctx context.Context, _ litestream.ReplicaClient, _ string, _ uint64) error { |
| + select { |
| + case <-ctx.Done(): |
| + case <-hang: |
| + } |
| + return ctx.Err() |
| + } |
| + }) |
| + req := fx.request("SELECT 1", "") |
| + e := fx.submit(req) |
| + a.consider(context.Background(), e) |
| + if _, err := fx.store.Put(context.Background(), CancelKey(req.ID), nil, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + done := make(chan struct{}) |
| + go func() { a.Wait(); close(done) }() |
| + select { |
| + case <-done: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the owner did not stop within 5 s of cancel") |
| + } |
| + if _, _, r := fx.answer(req.ID); r.State != StateCancelled { |
| + t.Fatalf("result %+v", r) |
| + } |
| +} |
| + |
| +// refusedChunk never lets one chunk's create land: every attempt answers an |
| +// error and the object stays absent. |
| +type refusedChunk struct { |
| + release.Store |
| + key string |
| +} |
| + |
| +func (s refusedChunk) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + if key == s.key { |
| + return "", errors.New("connection reset") |
| + } |
| + return s.Store.Put(ctx, key, body, ifMatch) |
| +} |
| + |
| +// Plan review finding 9: a chunk that is never confirmed is never named by |
| +// the result. The read ends interrupted, and every chunk through its |
| +// last_seq exists. Mutation: flushLocked increments seq before the create is |
| +// confirmed; the result then names chunk 2 and this test is red. |
| +func TestResultNamesOnlyConfirmedChunks(t *testing.T) { |
| + t.Parallel() |
| + fx := newFixture(t, 1) |
| + req := fx.request("SELECT hex(randomblob(300000))", "") // about 600 KB: three chunks |
| + a, _ := fx.agent("uk-1", func(c *AgentConfig, _ *inProcWorkers) { |
| + c.Store = refusedChunk{Store: fx.store, key: ChunkKey(req.ID, 2)} |
| + c.OwnerDeadline = 2 * time.Second |
| + }) |
| + a.consider(context.Background(), fx.submit(req)) |
| + a.Wait() |
| + raw, _, err := fx.store.Get(context.Background(), ResultKey(req.ID)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var r Result |
| + json.Unmarshal(raw, &r) |
| + if r.State != StateFailed || r.Code != CodeInterrupted || r.LastSeq != 1 { |
| + t.Fatalf("result %+v", r) |
| + } |
| + for seq := int64(1); seq <= r.LastSeq; seq++ { |
| + if _, _, err := fx.store.Get(context.Background(), ChunkKey(req.ID, seq)); err != nil { |
| + t.Fatalf("the result names chunk %d, which does not exist", seq) |
| + } |
| + } |
| +} |
| + |
| +// strictStore fails the test on any protocol delete or replacing write |
| +// under db-reads/ (T16, the box'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, 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, Prefix) { |
| + s.t.Errorf("a delete of %s", key) |
| + } |
| + return s.Store.Delete(ctx, key) |
| +} |
| + |
| +func TestReadNeverDeletesOrReplaces(t *testing.T) { |
| + t.Parallel() |
| + fx := newFixture(t, 2) |
| + a, _ := fx.agent("uk-1", func(c *AgentConfig, _ *inProcWorkers) { c.Store = strictStore{Store: fx.store, t: t} }) |
| + if _, _, r := serveOne(t, a, fx, fx.request("SELECT count(*) FROM t", "")); r.State != StateDone { |
| + t.Fatalf("%+v", r) |
| + } |
| +} |
| + |
| +func TestOwnerDeadlineEndsAHungRead(t *testing.T) { |
| + t.Parallel() |
| + fx := newFixture(t, 1) |
| + var started atomic.Bool |
| + a, _ := fx.agent("uk-1", func(c *AgentConfig, w *inProcWorkers) { |
| + c.OwnerDeadline = 200 * time.Millisecond |
| + w.opt.Restore = func(ctx context.Context, _ litestream.ReplicaClient, _ string, _ uint64) error { |
| + started.Store(true) |
| + <-ctx.Done() |
| + return ctx.Err() |
| + } |
| + }) |
| + _, _, r := serveOne(t, a, fx, fx.request("SELECT 1", "")) |
| + if !started.Load() || r.State != StateFailed || r.Code != CodeInterrupted { |
| + t.Fatalf("result %+v", r) |
| + } |
| +} |