carlos / platform Public

instancectl: one per-host lock serializes every legacy write of a slice's memory

Review fix (Task 5): /size held no lock from its populated-slice pre-check
to its writes, so a shrink validated at the old figure could land after a
concurrent growth (R1-3). A per-slice mutex (lockSliceMemory) is now held
by POST and GET /size from the check to the read-back, and by /parent and
setTier across their one set-property. TestSizeSerializesConcurrentSliceMemoryWrites
interleaves a growth with a shrink and with /parent.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 3ed9cd6e4845b8e89c535184a7ab4c869a0400c0 parent 9398ddf
4 files changed, +163 −0
  • internal/instancectl/gen.go +1 −0
  • internal/instancectl/server.go +20 −0
  • internal/instancectl/size.go +6 −0
  • internal/instancectl/size_test.go +136 −0
diff --git a/internal/instancectl/gen.go b/internal/instancectl/gen.go
index afdb696e2..2bda24ba2 100644
--- a/internal/instancectl/gen.go
+++ b/internal/instancectl/gen.go
@@ -465,6 +465,7 @@ func (s *Server) handleParent(w http.ResponseWriter, r *http.Request) {
return
}
max := strconv.FormatInt(n, 10)
+ defer s.lockSliceMemory(host)()
if out, err := s.Systemctl(r.Context(), "set-property", "--runtime", SliceName(host),
"MemoryMax="+max, "MemoryHigh="+strconv.FormatInt(cgroup.HighOf(n), 10), "MemorySwapMax="+max); err != nil {
http.Error(w, "set-property: "+strings.TrimSpace(out+" "+err.Error()), http.StatusBadGateway)
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go
index 61ad91ca0..bf05d3ec7 100644
--- a/internal/instancectl/server.go
+++ b/internal/instancectl/server.go
@@ -106,6 +106,12 @@ 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
// Run executes one command as root and returns its combined output;
// production is exec.CommandContext, tests record. Only
@@ -486,9 +492,23 @@ func parseRequest(r *http.Request, v verbShape) (request, error) {
// 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.
func (s *Server) setTier(ctx context.Context, host string, tier cgroup.Limit) error {
+ defer s.lockSliceMemory(host)()
return sliceTier(ctx, s.Systemctl, host, tier)
}
+// 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.
+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
+}
+
// sliceTier is setTier's one systemctl call, shared with the claim launch.
func sliceTier(ctx context.Context, systemctl func(context.Context, ...string) (string, error), host string, tier cgroup.Limit) error {
return sliceSize(ctx, systemctl, host, tier, cgroup.SharesOf(tier))
diff --git a/internal/instancectl/size.go b/internal/instancectl/size.go
index 076acfd38..c32bc5caa 100644
--- a/internal/instancectl/size.go
+++ b/internal/instancectl/size.go
@@ -106,6 +106,10 @@ 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)()
if s.refuseInactiveGen(ctx, w, req) {
return
}
@@ -151,6 +155,8 @@ func (s *Server) handleSizeReadBack(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
+ // The read is taken between writes, never in the middle of a /size.
+ defer s.lockSliceMemory(req.host)()
if s.refuseInactiveGen(r.Context(), w, req) {
return
}
diff --git a/internal/instancectl/size_test.go b/internal/instancectl/size_test.go
index 725d19de7..29f6b0dbd 100644
--- a/internal/instancectl/size_test.go
+++ b/internal/instancectl/size_test.go
@@ -1,6 +1,7 @@
package instancectl
import (
+ "context"
"encoding/json"
"errors"
"io"
@@ -8,7 +9,9 @@ import (
"os"
"path/filepath"
"strings"
+ "sync"
"testing"
+ "time"
)
const sizeHost = "shop-a.example.com"
@@ -321,3 +324,136 @@ func TestSizeReadBackParsesSystemd(t *testing.T) {
}
}
}
+
+// sliceMemory is a systemd whose slice MemoryMax follows its writes. The
+// first slice write blocks until released, and every pre-check read or
+// slice write that arrives while it is blocked is recorded: under the
+// per-host lock there is none.
+type sliceMemory struct {
+ ctl *fakeCtl
+ mu sync.Mutex
+ max string
+ blocked bool
+ entered chan struct{} // closed when the first slice write blocks
+ release chan struct{}
+ arrived chan string // a call that arrived while the first write blocked
+ duringIt []string
+}
+
+func newSliceMemory(max string) *sliceMemory {
+ return &sliceMemory{ctl: &fakeCtl{}, max: max, entered: make(chan struct{}), release: make(chan struct{}), arrived: make(chan string, 8)}
+}
+
+func (m *sliceMemory) run(ctx context.Context, args ...string) (string, error) {
+ line := strings.Join(args, " ")
+ m.ctl.run(ctx, args...) // records the call
+ m.mu.Lock()
+ if m.blocked && (line == "show -p MemoryMax --value "+sizeSlice || strings.HasPrefix(line, "set-property --runtime "+sizeSlice)) {
+ m.duringIt = append(m.duringIt, line)
+ m.arrived <- line
+ }
+ switch {
+ case line == "show -p MemoryMax --value "+sizeSlice:
+ defer m.mu.Unlock()
+ return m.max + "\n", nil
+ case strings.HasPrefix(line, "set-property --runtime "+sizeSlice):
+ first := m.entered != nil && !m.blocked
+ if first {
+ m.blocked = true
+ close(m.entered)
+ m.entered = nil
+ m.mu.Unlock()
+ <-m.release
+ m.mu.Lock()
+ m.blocked = false
+ }
+ for _, a := range args {
+ if v, ok := strings.CutPrefix(a, "MemoryMax="); ok {
+ m.max = v
+ }
+ }
+ m.mu.Unlock()
+ return "", nil
+ case strings.HasPrefix(line, sizeReadBackSlice):
+ defer m.mu.Unlock()
+ return "MemoryMax=" + m.max + "\n", nil
+ }
+ m.mu.Unlock()
+ return "", nil
+}
+
+// Review fix (R1-3): a growth and a shrink sent together for one populated
+// host. Without a per-host lock both pass the pre-check at 512 MiB, and
+// the shrink's write lands after the growth: memory shrinks while the
+// slice is populated. With it, the second request reads the first's write
+// and is refused. /parent, which also writes the slice's memory, waits on
+// the same lock.
+func TestSizeSerializesConcurrentSliceMemoryWrites(t *testing.T) {
+ for _, second := range []string{"size", "parent"} {
+ t.Run(second, func(t *testing.T) {
+ m := newSliceMemory("536870912")
+ s, c := newServer(t, m.ctl, func(s *Server) { s.Systemctl = m.run })
+ sizePopulated(t, s)
+ entered := m.entered
+ first := make(chan int, 1)
+ go func() {
+ status, _ := postSize(t, c, "host="+sizeHost+"&size=large&memory_max=1073741824")
+ first <- status
+ }()
+ select {
+ case <-entered:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the first request never wrote the slice")
+ }
+ type answer struct {
+ status int
+ body string
+ }
+ done := make(chan answer, 1)
+ go func() {
+ var a answer
+ if second == "size" {
+ a.status, a.body = postSize(t, c, "host="+sizeHost+"&size=standard&memory_max=536870912")
+ } else {
+ resp, err := c.Post("http://control/parent?host="+sizeHost+"&memory_max=536870912", "", nil)
+ if err == nil {
+ a.status = resp.StatusCode
+ resp.Body.Close()
+ }
+ }
+ done <- a
+ }()
+ // The second request reaches its pre-check or its write at once
+ // unless the lock holds it; a quarter second without either,
+ // while the first write is in flight, is the lock at work.
+ select {
+ case line := <-m.arrived:
+ t.Errorf("while the first write was in flight, the second request ran %q", line)
+ case <-time.After(250 * time.Millisecond):
+ }
+ close(m.release)
+ if status := <-first; status != http.StatusOK {
+ t.Fatalf("the growth answered %d", status)
+ }
+ a := <-done
+ m.mu.Lock()
+ final, during := m.max, m.duringIt
+ m.mu.Unlock()
+ if len(during) != 0 {
+ t.Errorf("calls during the first write: %v", during)
+ }
+ if second == "size" {
+ if a.status != http.StatusConflict || !strings.Contains(a.body, "memory never shrinks") {
+ t.Errorf("the shrink answered %d %s, want 409", a.status, a.body)
+ }
+ if final != "1073741824" {
+ t.Errorf("slice MemoryMax = %s after both, want 1073741824 (no shrink while populated)", final)
+ }
+ } else if a.status != http.StatusNoContent || final != "536870912" {
+ // /parent is the swap owner's restore and may lower; it
+ // only has to wait its turn.
+ t.Errorf("/parent answered %d, slice %s; want 204 after the growth", a.status, final)
+ }
+ })
+ }
+}