carlos / platform Public

instancectl: /size holds every in-flight start's tier; the tier write takes no lock

Review fix round 2 (Task 5): a start that set its tier and released the
lock could populate the slice after /size saw it empty, and /size's
shrink then landed under the running unit (R1-3). Every legacy start
(handleStart run and sidecar, startGen through it, handleSeed, handleCmd)
now registers its tier under the slice-memory lock before its tier step
and keeps it until the handler returns. /size treats a registered start
as populating the slice and never writes memory below a registered tier.

setTier no longer takes the lock (round 1 put it there): registration is
the sync point, so a wedged tier write blocks no other verb of the host,
which round 1 broke (TestOtherVerbsPassThroughDuringALegacyStop).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev c0aa4bb3b5335645c0ab4df089dfbaeb9947b2b0 parent 3ed9cd6
4 files changed, +214 −22
  • internal/instancectl/cmd.go +3 −0
  • internal/instancectl/server.go +64 −15
  • internal/instancectl/size.go +21 −7
  • internal/instancectl/size_test.go +126 −0
diff --git a/internal/instancectl/cmd.go b/internal/instancectl/cmd.go
index 3de279d51..a947e3697 100644
--- a/internal/instancectl/cmd.go
+++ b/internal/instancectl/cmd.go
@@ -50,6 +50,9 @@ func (s *Server) handleCmd(w http.ResponseWriter, r *http.Request) {
lock, _ := s.cmdLocks.LoadOrStore(req.host, new(sync.Mutex))
lock.(*sync.Mutex).Lock()
defer lock.(*sync.Mutex).Unlock()
+ // A command's unit runs in the host slice: counted until it has
+ // started, as every start is (beginSliceStart).
+ defer s.beginSliceStart(req.host, req.tier)()
ctx := r.Context()
unit := UnitName(RoleCmd, req.host)
switch state := s.showValue(ctx, "ActiveState", unit); state {
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go
index bf05d3ec7..e324e9502 100644
--- a/internal/instancectl/server.go
+++ b/internal/instancectl/server.go
@@ -106,12 +106,13 @@ type Server struct {
// ActiveState read to its answer, so two starts for one host cannot both
// pass the check.
cmdLocks sync.Map
- // sliceMemLocks holds one *sync.Mutex per host slice, keyed by
- // SliceName: every legacy write of a slice's memory takes it
- // (lockSliceMemory), so /size's populated-slice pre-check and its
- // writes are never interleaved with another write of that memory
- // (#329, R1-3).
- sliceMemLocks sync.Map
+ // sliceMems holds one *sliceMem per host slice, keyed by SliceName:
+ // every legacy write of a slice's memory takes its lock
+ // (lockSliceMemory), and every legacy start counts itself in it
+ // (beginSliceStart), so /size's populated-slice pre-check and its
+ // writes are never interleaved with another write of that memory or
+ // with a start that is about to populate the slice (#329, R1-3).
+ sliceMems sync.Map
// Run executes one command as root and returns its combined output;
// production is exec.CommandContext, tests record. Only
@@ -491,22 +492,66 @@ func parseRequest(r *http.Request, v verbShape) (request, error) {
// setTier writes the whole tier onto the host slice in one call: the
// memory caps, and the CPU and IO shares that follow from the same tier
// (#214 item 1). Seed, instance and sidecar share all of it.
+//
+// It takes no lock: every caller registered its tier with
+// beginSliceStart first, and /size never writes memory below a registered
+// tier, so a wedged write here holds up no other verb of the host.
func (s *Server) setTier(ctx context.Context, host string, tier cgroup.Limit) error {
- defer s.lockSliceMemory(host)()
return sliceTier(ctx, s.Systemctl, host, tier)
}
+// sliceMem is one host slice's memory lock and its in-flight starts.
+type sliceMem struct {
+ mu sync.Mutex
+ // starting holds the memory tier of each legacy start of the slice's
+ // units between its beginSliceStart and its handler's return: from
+ // before the tier step until systemctl start has returned. Guarded by
+ // mu.
+ starting []int64
+}
+
+func (s *Server) sliceMem(host string) *sliceMem {
+ m, _ := s.sliceMems.LoadOrStore(SliceName(host), new(sliceMem))
+ return m.(*sliceMem)
+}
+
// lockSliceMemory takes host's slice-memory lock and returns its unlock.
// It is held for one host at a time and never across a unit start or a
-// wait: /size holds it from its pre-check to its read-back, /parent and
-// setTier across their one set-property. Callers may already hold the
-// host's cmdLocks entry (handleCmd); nothing takes cmdLocks, legacyMu,
-// genMu or the egress asserter's lock while holding this one.
+// wait: /size holds it from its pre-check to its read-back, /parent
+// across its one set-property, beginSliceStart and its end across a list
+// update. Callers may already hold the host's cmdLocks entry (handleCmd);
+// nothing takes cmdLocks, legacyMu, genMu or the egress asserter's lock
+// while holding this one.
func (s *Server) lockSliceMemory(host string) func() {
- l, _ := s.sliceMemLocks.LoadOrStore(SliceName(host), new(sync.Mutex))
- m := l.(*sync.Mutex)
- m.Lock()
- return m.Unlock
+ m := s.sliceMem(host)
+ m.mu.Lock()
+ return m.mu.Unlock
+}
+
+// beginSliceStart registers a legacy start of one of host's units and
+// its tier, before its tier step or populated check, and returns the end
+// the handler defers: the registration stays until the handler returns,
+// so past its systemctl start, success or failure. While any start is
+// registered, /size treats the slice as populated, though its cgroup may
+// still be empty, and never writes memory below a registered tier: a
+// start that set (or is about to set) its tier is about to run under it
+// (R1-3). Registering waits only for a /size of the same host in flight;
+// the tier write after it runs unlocked.
+func (s *Server) beginSliceStart(host string, tier cgroup.Limit) (end func()) {
+ m := s.sliceMem(host)
+ m.mu.Lock()
+ m.starting = append(m.starting, tier.MemoryMax)
+ m.mu.Unlock()
+ return func() {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ for i, t := range m.starting {
+ if t == tier.MemoryMax {
+ m.starting = append(m.starting[:i], m.starting[i+1:]...)
+ return
+ }
+ }
+ }
}
// sliceTier is setTier's one systemctl call, shared with the claim launch.
@@ -539,6 +584,9 @@ func (s *Server) handleStart(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
+ // Counted from before the tier step until the start has returned,
+ // generations included (startGen is reached only from here).
+ defer s.beginSliceStart(req.host, req.tier)()
if req.gen != 0 {
s.startGen(w, r, req)
return
@@ -658,6 +706,7 @@ func (s *Server) handleSeed(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
+ defer s.beginSliceStart(req.host, req.tier)()
ctx := r.Context()
unit := UnitName(RoleSeed, req.host)
if s.refuseStagedExe(w, req, unit) {
diff --git a/internal/instancectl/size.go b/internal/instancectl/size.go
index c32bc5caa..aa0de4f6d 100644
--- a/internal/instancectl/size.go
+++ b/internal/instancectl/size.go
@@ -106,14 +106,29 @@ func (s *Server) handleSize(w http.ResponseWriter, r *http.Request) {
http.Error(w, "memory_max "+strconv.Quote(q.Get("memory_max"))+" is not a platform size's memory", http.StatusBadRequest)
return
}
- // From the pre-check to the read-back, no other write of this slice's
- // memory runs (R1-3): two requests that both passed the check at the
- // old figure could otherwise land a shrink after a growth.
- defer s.lockSliceMemory(req.host)()
+ // From the pre-check to the read-back, no other /size or /parent of
+ // this slice runs and no start registers (R1-3): two requests that
+ // both passed the check at the old figure could otherwise land a
+ // shrink after a growth. A start registered before this point may
+ // still write its tier meanwhile; nothing here goes below that tier.
+ mem := s.sliceMem(req.host)
+ mem.mu.Lock()
+ defer mem.mu.Unlock()
if s.refuseInactiveGen(ctx, w, req) {
return
}
- if s.slicePopulated(req.host) {
+ // A start in flight is about to populate the slice under the memory
+ // its tier step wrote or is about to write (or the memory a populated
+ // slice holds), so it counts as populated, and its tier is held as
+ // the slice's is: otherwise a shrink checked against an empty slice
+ // lands under the unit it just started.
+ for _, tier := range mem.starting {
+ if n < tier {
+ http.Error(w, "memory never shrinks while the slice is populated: a start in flight runs at "+strconv.FormatInt(tier, 10), http.StatusConflict)
+ return
+ }
+ }
+ if len(mem.starting) > 0 || s.slicePopulated(req.host) {
held := []string{SliceName(req.host)}
if req.unit != "" {
held = append(held, req.unit)
@@ -131,8 +146,7 @@ func (s *Server) handleSize(w http.ResponseWriter, r *http.Request) {
}
}
}
- mem := cgroup.Limit{MemoryMax: n}
- if err := sliceSize(ctx, s.Systemctl, req.host, mem, size.Shares); err != nil {
+ if err := sliceSize(ctx, s.Systemctl, req.host, cgroup.Limit{MemoryMax: n}, size.Shares); err != nil {
http.Error(w, "set-property "+SliceName(req.host)+": "+err.Error(), http.StatusBadGateway)
return
}
diff --git a/internal/instancectl/size_test.go b/internal/instancectl/size_test.go
index 29f6b0dbd..78654b7a5 100644
--- a/internal/instancectl/size_test.go
+++ b/internal/instancectl/size_test.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
+ "fmt"
"io"
"net/http"
"os"
@@ -457,3 +458,128 @@ func TestSizeSerializesConcurrentSliceMemoryWrites(t *testing.T) {
})
}
}
+
+// startInFlight is a start path held inside its `systemctl start`, after
+// its tier step wrote the slice's memory, on genHost's slice, which has
+// no cgroup.events yet: nothing runs in it.
+type startInFlight struct {
+ name string
+ path string // the verb's query
+ start string // the start call's prefix
+}
+
+var startsInFlight = []startInFlight{
+ {"run", "/start?host=" + genHost + "&role=run&memory_max=536870912", "start " + UnitName(RoleRun, genHost)},
+ {"sidecar", "/start?host=" + genHost + "&role=sidecar&memory_max=536870912", "start " + UnitName(RoleSidecar, genHost)},
+ {"seed", "/seed?host=" + genHost + "&memory_max=536870912", "start " + UnitName(RoleSeed, genHost)},
+ {"cmd", "/cmd?host=" + genHost + "&memory_max=536870912", "start --no-block " + UnitName(RoleCmd, genHost)},
+ {"generation", "/start?host=" + genHost + "&role=run&memory_max=536870912&gen=7", "start " + genUnit},
+}
+
+// Review fix round 2 (R1-3): a start sets its tier (512 MiB) and is held
+// in its systemctl start; the slice's cgroup is still empty. A /size
+// shrink to 256 MiB arriving then must see the start as populating the
+// slice and refuse with no write; a growth is still applied. Once the
+// start returns, success or failure, the count is back to 0, and a
+// shrink of the empty slice goes through.
+func TestSizeTreatsAStartInFlightAsPopulated(t *testing.T) {
+ for _, tc := range startsInFlight {
+ for _, fail := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%s/fail=%v", tc.name, fail), func(t *testing.T) {
+ ctl := genCtl()
+ ctl.answers["show -p MemoryMax --value "+SliceName(genHost)] = "536870912\n"
+ ctl.answers["show -p MemoryMax -p CPUQuotaPerSecUSec"] = "MemoryMax=536870912\n"
+ entered, release := make(chan struct{}), make(chan struct{})
+ ctl.before = map[string]func(){"start": func() { close(entered); <-release }}
+ if fail {
+ ctl.fail = map[string]error{tc.start: errSizeWrite}
+ }
+ s, c := newServer(t, ctl, func(s *Server) {
+ s.DropInDir, s.ExeRoot = t.TempDir(), t.TempDir()
+ s.cmdStartBound, s.cmdPollEvery = 20*time.Millisecond, 5*time.Millisecond
+ })
+ started := make(chan int, 1)
+ go func() {
+ resp, err := c.Post("http://control"+tc.path, "", nil)
+ if err != nil {
+ started <- 0
+ return
+ }
+ resp.Body.Close()
+ started <- resp.StatusCode
+ }()
+ select {
+ case <-entered:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the start never reached systemctl start")
+ }
+ tier := `set-property --runtime ` + SliceName(genHost) + ` MemoryMax=536870912 `
+ if got := ctl.joined(); !strings.Contains(got, tier) {
+ t.Fatalf("the start did not set its tier before starting:\n%s", got)
+ }
+ writes := countSetProperty(ctl.joined())
+ status, body := postSize(t, c, "host="+genHost+"&size=small&memory_max=268435456")
+ if status != http.StatusConflict || !strings.Contains(body, "memory never shrinks") {
+ t.Errorf("a shrink during the start answered %d %s, want 409", status, body)
+ }
+ if got := countSetProperty(ctl.joined()); got != writes {
+ t.Errorf("the refused shrink wrote:\n%s", ctl.joined())
+ }
+ if status, body := postSize(t, c, "host="+genHost+"&size=large&memory_max=1073741824"); status != http.StatusOK {
+ t.Errorf("a growth during the start answered %d %s, want 200", status, body)
+ }
+ close(release)
+ <-started
+ m := s.sliceMem(genHost)
+ m.mu.Lock()
+ n := len(m.starting)
+ m.mu.Unlock()
+ if n != 0 {
+ t.Errorf("in-flight starts after the start returned = %d, want 0", n)
+ }
+ if fail {
+ // The failed start left nothing running: the slice is
+ // empty, so memory may go down.
+ if status, body := postSize(t, c, "host="+genHost+"&size=small&memory_max=268435456"); status != http.StatusOK {
+ t.Errorf("a shrink after the failed start answered %d %s, want 200", status, body)
+ }
+ }
+ })
+ }
+ }
+}
+
+// The tier write itself takes no lock, so a start can be registered and
+// still before its tier step while the slice holds less than its tier. A
+// /size then may not write memory below the start's tier, or the start's
+// write and the /size write could land in either order around the unit's
+// start.
+func TestSizeHoldsAStartsTierBeforeItIsWritten(t *testing.T) {
+ ctl := genCtl()
+ ctl.answers["show -p MemoryMax --value "+SliceName(genHost)] = "268435456\n"
+ entered, release := make(chan struct{}), make(chan struct{})
+ ctl.before = map[string]func(){"set-property": func() { close(entered); <-release }}
+ _, c := newServer(t, ctl)
+ started := make(chan struct{})
+ go func() {
+ defer close(started)
+ if resp, err := c.Post("http://control/start?host="+genHost+"&role=run&memory_max=536870912", "", nil); err == nil {
+ resp.Body.Close()
+ }
+ }()
+ select {
+ case <-entered:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the start never reached its tier step")
+ }
+ status, body := postSize(t, c, "host="+genHost+"&size=small&memory_max=268435456")
+ if status != http.StatusConflict || !strings.Contains(body, "a start in flight runs at 536870912") {
+ t.Errorf("a write below the in-flight start's tier answered %d %s, want 409", status, body)
+ }
+ // The start's own write is held before it is recorded: none at all.
+ if got := countSetProperty(ctl.joined()); got != 0 {
+ t.Errorf("set-property calls = %d, want none while the start's is held:\n%s", got, ctl.joined())
+ }
+ close(release)
+ <-started
+}