carlos / platform Public

db forward task 9: admission, reservations held until the worker unit is gone, the orphan rule

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 04be05a79684f90214d2c3072c2cea656925450f parent 0ad4e59
2 files changed, +375 −0
  • internal/dbreads/admission.go +191 −0
  • internal/dbreads/admission_test.go +184 −0
diff --git a/internal/dbreads/admission.go b/internal/dbreads/admission.go
new file mode 100644
index 000000000..a841de9e3
--- /dev/null
+++ b/internal/dbreads/admission.go
@@ -0,0 +1,191 @@
+package dbreads
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sync"
+ "time"
+)
+
+var (
+ errBusy = errors.New("dbreads: this box is running its two reads")
+ errOrphans = errors.New("dbreads: a carlos-dbread@ unit this agent is not running is still active")
+ errNoRoom = errors.New("dbreads: not enough disk for the read")
+)
+
+// admission is the agent's one table (spec §5.7, J5): how many worker
+// connections it holds, which reads it is running, and every disk
+// reservation. The agent is the only process that starts workers, so one
+// mutex covers it all.
+type admission struct {
+ units func(context.Context) (int, error)
+ free func() (avail, total uint64, err error)
+
+ mu sync.Mutex
+ conns int
+ running map[string]bool
+ held map[string]int64
+ probing bool
+}
+
+func newAdmission(units func(context.Context) (int, error), free func() (uint64, uint64, error)) *admission {
+ return &admission{units: units, free: free, running: map[string]bool{}, held: map[string]int64{}}
+}
+
+// reconcileLocked is the refusal-based reconciliation (spec §5.7): while any
+// carlos-dbread@ unit is active, activating or deactivating beyond the
+// connections this agent holds, nothing is admitted. A finished read's
+// reservation is released only when no unit is left at all: then every
+// stopped unit's scratch has been removed by systemd.
+func (a *admission) reconcileLocked(ctx context.Context) error {
+ n, err := a.units(ctx)
+ if err != nil {
+ return fmt.Errorf("dbreads: list carlos-dbread@ units: %w", err)
+ }
+ if n > a.conns {
+ return errOrphans
+ }
+ if n == 0 {
+ for id := range a.held {
+ if !a.running[id] {
+ delete(a.held, id)
+ }
+ }
+ }
+ return nil
+}
+
+// fitsLocked: after subtracting every other reservation and need, the
+// filesystem holding /var/tmp keeps DiskFloor and DiskFreePercent free.
+func (a *admission) fitsLocked(id string, need int64) bool {
+ avail, total, err := a.free()
+ if err != nil {
+ return false
+ }
+ left := int64(avail) - need
+ for k, v := range a.held {
+ if k != id {
+ left -= v
+ }
+ }
+ return left >= DiskFloor && left >= int64(total)*DiskFreePercent/100
+}
+
+// admitRead admits a read before it enters the election: a free read slot,
+// no orphan, and room for the floor reservation.
+func (a *admission) admitRead(ctx context.Context, id string) error {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if err := a.reconcileLocked(ctx); err != nil {
+ return err
+ }
+ if len(a.running) >= ReadsPerBox {
+ return errBusy
+ }
+ if !a.fitsLocked(id, DiskFloor) {
+ return errNoRoom
+ }
+ a.running[id] = true
+ a.held[id] = DiskFloor
+ return nil
+}
+
+// grow raises a running read's reservation to need (never below the floor)
+// once its plan is known.
+func (a *admission) grow(id string, need int64) error {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ need = max(need, DiskFloor)
+ if !a.fitsLocked(id, need) {
+ return errNoRoom
+ }
+ a.held[id] = need
+ return nil
+}
+
+// finish ends a read's slot. Its reservation stays until reconcileLocked
+// sees no unit left.
+func (a *admission) finish(id string) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ delete(a.running, id)
+}
+
+// abandon gives back a read this agent admitted and then did not run (it
+// lost the election, or stopped before it): no worker was started for it,
+// so its reservation goes at once rather than waiting for the units to drain.
+func (a *admission) abandon(id string) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ delete(a.running, id)
+ delete(a.held, id)
+}
+
+// retry is a read starting a fresh plan after a planned file vanished (spec
+// §8.2). Its previous worker may still hold scratch until its unit stops, so
+// that reservation moves to a retired key, held until no unit is left (J5),
+// and the read starts again from the floor (plan review finding 10).
+func (a *admission) retry(id string, attempt int) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if v, ok := a.held[id]; ok {
+ a.held[fmt.Sprintf("%s#%d", id, attempt)] = v
+ }
+ a.held[id] = DiskFloor
+}
+
+// settle waits until no carlos-dbread@ unit is running beyond this agent's
+// open connections, so a retry opens its next worker only once the last one
+// is gone, and never into the probe's connection. It releases retired
+// reservations once no unit is left at all.
+func (a *admission) settle(ctx context.Context, poll time.Duration) error {
+ for {
+ a.mu.Lock()
+ err := a.reconcileLocked(ctx)
+ a.mu.Unlock()
+ if !errors.Is(err, errOrphans) {
+ return err
+ }
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-time.After(poll):
+ }
+ }
+}
+
+// admitProbe admits the readiness probe: no orphan and no other probe. The
+// probe's connection is the third (opened checks the count).
+func (a *admission) admitProbe(ctx context.Context) bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if a.probing || a.reconcileLocked(ctx) != nil {
+ return false
+ }
+ a.probing = true
+ return true
+}
+
+func (a *admission) probeDone() {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.probing = false
+}
+
+// opened takes a connection slot; the agent never opens a fourth.
+func (a *admission) opened() bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if a.conns >= MaxConnections {
+ return false
+ }
+ a.conns++
+ return true
+}
+
+func (a *admission) closed() {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.conns--
+}
diff --git a/internal/dbreads/admission_test.go b/internal/dbreads/admission_test.go
new file mode 100644
index 000000000..d6ac5f332
--- /dev/null
+++ b/internal/dbreads/admission_test.go
@@ -0,0 +1,184 @@
+package dbreads
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+)
+
+type unitsSeam struct {
+ n int
+ err error
+}
+
+func (u *unitsSeam) count(context.Context) (int, error) { return u.n, u.err }
+
+func gib(n uint64) uint64 { return n << 30 }
+
+func TestAdmissionTwoReadsThenBusy(t *testing.T) {
+ t.Parallel()
+ u := &unitsSeam{}
+ a := newAdmission(u.count, func() (uint64, uint64, error) { return gib(100), gib(200), nil })
+ ctx := context.Background()
+ for _, id := range []string{"r1", "r2"} {
+ if err := a.admitRead(ctx, id); err != nil {
+ t.Fatalf("%s: %v", id, err)
+ }
+ }
+ if err := a.admitRead(ctx, "r3"); !errors.Is(err, errBusy) {
+ t.Fatalf("a third read: %v", err)
+ }
+ // The probe still has its connection (spec §7.1, codex 9).
+ if !a.opened() || !a.opened() || !a.admitProbe(ctx) || !a.opened() {
+ t.Fatal("two reads and a probe do not fit three connections")
+ }
+ if a.opened() {
+ t.Fatal("a fourth connection was allowed")
+ }
+}
+
+// T12, unit half: free space that fits one read admits one.
+func TestAdmissionDiskFitsOneOfTwo(t *testing.T) {
+ t.Parallel()
+ a := newAdmission((&unitsSeam{}).count, func() (uint64, uint64, error) { return gib(12), gib(20), nil })
+ ctx := context.Background()
+ if err := a.admitRead(ctx, "r1"); err != nil {
+ t.Fatal(err)
+ }
+ if err := a.admitRead(ctx, "r2"); !errors.Is(err, errNoRoom) {
+ t.Fatalf("a second read on a box with room for one: %v", err)
+ }
+ if err := a.grow("r1", int64(gib(8))); !errors.Is(err, errNoRoom) {
+ t.Fatalf("growing past the floor and 10%%: %v", err)
+ }
+ if err := a.grow("r1", int64(gib(6))); err != nil {
+ t.Fatalf("growing within room: %v", err)
+ }
+}
+
+// An orphan (a unit this agent is not running) blocks every admission until
+// it is gone, and no size is guessed for it (spec §5.7, codex 8).
+func TestAdmissionRefusesBesideAnOrphan(t *testing.T) {
+ t.Parallel()
+ u := &unitsSeam{n: 1}
+ a := newAdmission(u.count, func() (uint64, uint64, error) { return gib(100), gib(200), nil })
+ ctx := context.Background()
+ if err := a.admitRead(ctx, "r1"); !errors.Is(err, errOrphans) {
+ t.Fatalf("beside an orphan: %v", err)
+ }
+ if a.admitProbe(ctx) {
+ t.Fatal("a probe beside an orphan")
+ }
+ u.n = 0
+ if err := a.admitRead(ctx, "r1"); err != nil {
+ t.Fatalf("once the orphan is gone: %v", err)
+ }
+}
+
+// A finished read's reservation is held until no db-read unit is left, since
+// systemd removes the scratch only at unit stop.
+func TestAdmissionHoldsAReservationUntilItsUnitIsGone(t *testing.T) {
+ t.Parallel()
+ u := &unitsSeam{}
+ // 12 GiB free of 20: r1 grown to 6 leaves room for r2's floor only once
+ // r1's reservation is released.
+ a := newAdmission(u.count, func() (uint64, uint64, error) { return gib(12), gib(20), nil })
+ ctx := context.Background()
+ if err := a.admitRead(ctx, "r1"); err != nil {
+ t.Fatal(err)
+ }
+ a.opened()
+ if err := a.grow("r1", int64(gib(6))); err != nil {
+ t.Fatal(err)
+ }
+ u.n = 1
+ a.closed()
+ a.finish("r1")
+ // The unit is still deactivating: one unit, no connection. Refused.
+ if err := a.admitRead(ctx, "r2"); !errors.Is(err, errOrphans) {
+ t.Fatalf("while the unit deactivates: %v", err)
+ }
+ u.n = 0
+ if err := a.admitRead(ctx, "r2"); err != nil {
+ t.Fatalf("after the unit is gone the reservation is free: %v", err)
+ }
+}
+
+// Review Focus 5: a unit listing that fails admits nothing and skips the
+// probe rather than guessing.
+func TestAdmissionFailsClosedWhenUnitsCannotBeListed(t *testing.T) {
+ t.Parallel()
+ u := &unitsSeam{err: errors.New("systemctl: not found")}
+ a := newAdmission(u.count, func() (uint64, uint64, error) { return gib(100), gib(200), nil })
+ if err := a.admitRead(context.Background(), "r1"); err == nil {
+ t.Fatal("admitted with no unit listing")
+ }
+ if a.admitProbe(context.Background()) {
+ t.Fatal("probed with no unit listing")
+ }
+}
+
+// A read admitted and then lost in the election started no worker: its
+// floor goes at once, even while another read's unit is running.
+func TestAdmissionAbandonFreesAtOnce(t *testing.T) {
+ t.Parallel()
+ u := &unitsSeam{}
+ // 17 GiB of 20: room for two floors (17-10 = 7), not three.
+ a := newAdmission(u.count, func() (uint64, uint64, error) { return gib(17), gib(20), nil })
+ ctx := context.Background()
+ if err := a.admitRead(ctx, "running"); err != nil {
+ t.Fatal(err)
+ }
+ a.opened()
+ u.n = 1 // its worker unit is up, so finished reservations stay held
+ if err := a.admitRead(ctx, "lost"); err != nil {
+ t.Fatal(err)
+ }
+ a.abandon("lost") // it lost the election; no worker started
+ if err := a.admitRead(ctx, "next"); err != nil {
+ t.Fatalf("the lost read's floor is still held: %v", err)
+ }
+}
+
+// Plan review finding 10: a retried read keeps its first attempt's
+// reservation while that worker's unit is still stopping, and settle waits
+// for the unit. Mutation: retry leaves held[id] in place instead of moving
+// it to a retired key; the grow below then fits and this test is red.
+func TestAdmissionRetryHoldsTheOldReservation(t *testing.T) {
+ t.Parallel()
+ u := &unitsSeam{}
+ a := newAdmission(u.count, func() (uint64, uint64, error) { return gib(12), gib(20), nil })
+ ctx := context.Background()
+ if err := a.admitRead(ctx, "r1"); err != nil {
+ t.Fatal(err)
+ }
+ if err := a.grow("r1", int64(gib(6))); err != nil {
+ t.Fatal(err)
+ }
+ u.n = 1 // the first worker's connection is closed; its unit is stopping
+ a.retry("r1", 1)
+ if err := a.grow("r1", int64(gib(5))); !errors.Is(err, errNoRoom) {
+ t.Fatalf("the stopping worker's scratch was not held: %v", err)
+ }
+ short, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
+ defer cancel()
+ if err := a.settle(short, 10*time.Millisecond); !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("settle returned beside a live unit: %v", err)
+ }
+ u.n = 0
+ if err := a.settle(ctx, 10*time.Millisecond); err != nil {
+ t.Fatal(err)
+ }
+ if err := a.grow("r1", int64(gib(5))); err != nil {
+ t.Fatalf("after the unit stopped: %v", err)
+ }
+}
+
+func TestAdmissionFailsClosedWhenTheDiskCannotBeRead(t *testing.T) {
+ t.Parallel()
+ a := newAdmission((&unitsSeam{}).count, func() (uint64, uint64, error) { return 0, 0, errors.New("statfs") })
+ if err := a.admitRead(context.Background(), "r1"); !errors.Is(err, errNoRoom) {
+ t.Fatalf("admitted with no disk reading: %v", err)
+ }
+}