carlos / platform Public

activator: live size changes under the operation set; captured tier from read-back; unsettled hosts start no swap

Task 6 of plan 3 (#329). The sweep's retrySizeLocked sends an operator
size change to root's /size verbs through a new SizeBackend (ExecBackend
for nested rows through a separate SizeControl; SplitBackend delegates by
Backing). Per preflight C6 a pass runs only on NoteSize, an unsettled
host, or a 5-minute local-registry backstop, compares the column off a.mu
holding nothing, and takes the resizing mark only after rechecking
eligibility. Memory is never written below what the slice or unit holds;
the captured tier comes from the read-back; a refusal records the size
for the next start; any other write failure marks the host unsettled and
swap admission refuses until a write settles it. joinOps, releasable and
the generations-off reap proof all hold the lease while a resize runs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 7c8995ec4d24e3a5e115afaefc7d20da66b8a3e9 parent 952e0da
10 files changed, +1,339 −15
  • internal/activator/activator.go +15 −0
  • internal/activator/containment.go +49 −0
  • internal/activator/containment_test.go +91 −0
  • internal/activator/control.go +13 −0
  • internal/activator/genbackend.go +30 −0
  • internal/activator/opset.go +41 −10
  • internal/activator/size.go +271 −0
  • internal/activator/size_live_test.go +756 −0
  • internal/activator/swap.go +5 −1
  • internal/activator/swap_fixture_test.go +68 −4
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 97d513ce9..2335c7a00 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -615,6 +615,18 @@ type actEntry struct {
// exited, so an intentional stop is never read as a crash (spec §6.4).
// Written under a.mu.
settleCancel context.CancelFunc
+ // The live size change's view of the size column (#329, size.go), all
+ // written under a.mu. sizeSeen is the column this entry last acted on:
+ // the wake's row, then each pass's. sizeDirty is NoteSize's hint that
+ // the column may have moved. sizeChecking marks a pass in flight, from
+ // its registry compare to its end; unlike ops.resizing it holds nothing
+ // back (no swap, stop or lease waits on it). sizeCheckedAt paces the
+ // slow backstop compare.
+ sizeSeen string
+ sizeSeenSet bool
+ sizeDirty bool
+ sizeChecking bool
+ sizeCheckedAt time.Time
// genReaping is true while reapCurrentGen is running for this pending
// stop, so finishPendingStops does not start a second one. Written
// under a.mu.
@@ -4233,6 +4245,9 @@ func (a *Service) finishPendingStops() {
// A parent restore that failed when the last member left keeps its
// obligation and is retried here (final review F11).
a.retryParentRestoreLocked(e)
+ // An operator size change goes out live once nothing else holds the
+ // host's parent (#329); retrySizeLocked skips everything else.
+ a.retrySizeLocked(e)
// A run whose stop was asked for and is not proven, pending stop
// or not (re-review 6).
a.retryCmdSettlesLocked(e)
diff --git a/internal/activator/containment.go b/internal/activator/containment.go
index 97e59bd00..19a7358ca 100644
--- a/internal/activator/containment.go
+++ b/internal/activator/containment.go
@@ -14,6 +14,11 @@ import (
var (
errNoGenContainment = errors.New("activator: generation containment is off")
errNoGenControl = errors.New("activator: the instance control channel cannot run generation units")
+ // errSizeNotLive refuses a live size change (#329) where this box has
+ // none: a layout other than nested, a channel without root's /size
+ // verbs, or a unit-backed row. Nothing is written; the size takes
+ // effect at the host's next start.
+ errSizeNotLive = errors.New("activator: no live size change for this host")
// errGenUnproven is a generation start that failed and whose kill did
// not prove the generation gone. It may still be running: its listeners
// and launch file are kept, and a caller must keep whatever it owns for
@@ -285,6 +290,18 @@ func (b *ExecBackend) genControl() (GenControl, error) {
return gc, nil
}
+// sizeControl is Control's live size half, or errSizeNotLive.
+func (b *ExecBackend) sizeControl() (SizeControl, error) {
+ if b.Control == nil {
+ return nil, errSizeNotLive
+ }
+ sc, ok := b.Control.(SizeControl)
+ if !ok {
+ return nil, errSizeNotLive
+ }
+ return sc, nil
+}
+
// errNoStagedExeControl refuses a start or seed of an original template
// that names a staged build when the control channel cannot name one.
// Binding the live link instead would run a build nobody recorded.
@@ -385,6 +402,38 @@ func (b *ExecBackend) ParentLimit(ctx context.Context, rt registry.Route, l cgro
return b.Cgroups.SetParentLimit(rt.Host, l)
}
+// liveSizeControl is the size channel for rt, which only a nested host has:
+// root owns its slice. Every other layout, and a channel without the size
+// verbs, is errSizeNotLive. Unlike ParentLimit it does not need
+// GenContainment: gen 0 is the run template's slice alone.
+func (b *ExecBackend) liveSizeControl(rt registry.Route) (SizeControl, error) {
+ if p := b.pathsFor(rt); p.layout != LayoutNested {
+ return nil, fmt.Errorf("%s: %w (layout %q)", rt.Host, errSizeNotLive, p.layout)
+ }
+ return b.sizeControl()
+}
+
+// ResizeLive asks root to size rt's slice and, with gen, that generation's
+// unit (#329): CPU and IO from size, memory at memoryMax, which the caller
+// never puts below what it read. It answers root's read-back.
+func (b *ExecBackend) ResizeLive(ctx context.Context, rt registry.Route, gen uint64, size cgroup.Size, memoryMax int64) (instancectl.SizeReadBack, error) {
+ sc, err := b.liveSizeControl(rt)
+ if err != nil {
+ return instancectl.SizeReadBack{}, err
+ }
+ return sc.Size(ctx, rt.Host, gen, size.Name, memoryMax)
+}
+
+// ReadSize reads what rt's slice and, with gen, that generation's unit hold
+// now. It writes nothing.
+func (b *ExecBackend) ReadSize(ctx context.Context, rt registry.Route, gen uint64) (instancectl.SizeReadBack, error) {
+ sc, err := b.liveSizeControl(rt)
+ if err != nil {
+ return instancectl.SizeReadBack{}, err
+ }
+ return sc.ReadSize(ctx, rt.Host, gen)
+}
+
// KillGen kills generation n outright and returns once its child is empty
// (spec §7.3, §8.2 step 1). It acts on that generation's child only.
func (b *ExecBackend) KillGen(ctx context.Context, rt registry.Route, n uint64) error {
diff --git a/internal/activator/containment_test.go b/internal/activator/containment_test.go
index e0aac8bb1..79170f722 100644
--- a/internal/activator/containment_test.go
+++ b/internal/activator/containment_test.go
@@ -14,6 +14,7 @@ import (
"github.com/carlosframework/platform/internal/cgroup"
"github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
)
@@ -50,6 +51,96 @@ func (f fakeGenControl) Parent(_ context.Context, host string, max int64) error
return nil
}
+// fakeSizeControl is fakeGenControl plus root's /size verbs (Task 6, Astra
+// plan R8-2): a separate interface, as GenControl's method set has none.
+type fakeSizeControl struct {
+ fakeGenControl
+ rb instancectl.SizeReadBack
+ err error
+}
+
+func (f fakeSizeControl) Size(_ context.Context, host string, gen uint64, size string, mem int64) (instancectl.SizeReadBack, error) {
+ f.rec(fmt.Sprintf("size %s %d %s %d", host, gen, size, mem))
+ return f.rb, f.err
+}
+
+func (f fakeSizeControl) ReadSize(_ context.Context, host string, gen uint64) (instancectl.SizeReadBack, error) {
+ f.rec(fmt.Sprintf("readsize %s %d", host, gen))
+ return f.rb, f.err
+}
+
+// The exec backend sizes a nested host only through SizeControl, never
+// GenControl, and refuses every other layout and a channel without the
+// verbs before any call (Astra plan R8-2).
+func TestExecBackendSizesThroughSizeControl(t *testing.T) {
+ t.Parallel()
+ large, _ := cgroup.SizeByName("large")
+ rb := instancectl.SizeReadBack{SliceMemoryMax: 1 << 30, UnitMemoryMax: 1 << 30, CPUQuotaPercent: 200, CPUWeight: 100, IOWeight: 100}
+ ctx := context.Background()
+
+ ctl := &fakeControl{}
+ b, rt := nestedBackend(t, ctl, &fakeUnit{})
+ b.Control = fakeSizeControl{fakeGenControl: fakeGenControl{ctl}, rb: rb}
+ got, err := b.ReadSize(ctx, rt, 3)
+ if err != nil || got != rb {
+ t.Fatalf("ReadSize = %+v, %v; want %+v", got, err, rb)
+ }
+ got, err = b.ResizeLive(ctx, rt, 3, large, 1<<30)
+ if err != nil || got != rb {
+ t.Fatalf("ResizeLive = %+v, %v; want %+v", got, err, rb)
+ }
+ if calls, want := strings.Join(ctl.calls, "\n"), "readsize h.example.com 3\nsize h.example.com 3 large 1073741824"; calls != want {
+ t.Fatalf("calls:\n%s\nwant:\n%s", calls, want)
+ }
+
+ refused := func(name string, b *ExecBackend, rt registry.Route, ctl *fakeControl) {
+ t.Helper()
+ before := len(ctl.calls)
+ if _, err := b.ReadSize(ctx, rt, 3); !errors.Is(err, errSizeNotLive) {
+ t.Errorf("%s: ReadSize = %v, want errSizeNotLive", name, err)
+ }
+ if _, err := b.ResizeLive(ctx, rt, 3, large, 1<<30); !errors.Is(err, errSizeNotLive) {
+ t.Errorf("%s: ResizeLive = %v, want errSizeNotLive", name, err)
+ }
+ if len(ctl.calls) != before {
+ t.Errorf("%s: calls %v, want none", name, ctl.calls[before:])
+ }
+ }
+
+ // A channel with the generation verbs but no size verbs.
+ ctl2 := &fakeControl{}
+ b2, rt2 := nestedBackend(t, ctl2, &fakeUnit{})
+ b2.Control = fakeGenControl{ctl2}
+ refused("no size verbs", b2, rt2, ctl2)
+
+ // A fenced row (a layout migration in flight).
+ ctl3 := &fakeControl{}
+ b3, rt3 := nestedBackend(t, ctl3, &fakeUnit{})
+ b3.Control = fakeSizeControl{fakeGenControl: fakeGenControl{ctl3}, rb: rb}
+ b3.LayoutFacts.Journal = func(string) bool { return true }
+ if l, _ := Classify(rt3, b3.layoutInputs()); l != LayoutFenced {
+ t.Fatalf("the fenced fixture classifies as %q", l)
+ }
+ refused("fenced", b3, rt3, ctl3)
+
+ // A flat row: no root slice to size.
+ ctl4 := &fakeControl{}
+ b4 := testExecBackend(t)
+ b4.Control = fakeSizeControl{fakeGenControl: fakeGenControl{ctl4}, rb: rb}
+ flatSock, _ := b4.layoutInputs().sockets("flat.example.com")
+ rt4 := registry.Route{Host: "flat.example.com", Kind: "instance", Hibernate: true, Socket: flatSock,
+ DBPath: provision.DefaultDBPath(b4.DataDir, "flat.example.com")}
+ if l, _ := Classify(rt4, b4.layoutInputs()); l != LayoutFlat {
+ t.Fatalf("the flat fixture classifies as %q", l)
+ }
+ refused("flat", b4, rt4, ctl4)
+
+ // No control channel at all.
+ b5, rt5 := nestedBackend(t, &fakeControl{}, &fakeUnit{})
+ b5.Control = nil
+ refused("no channel", b5, rt5, &fakeControl{})
+}
+
func TestPlaceForIsSingleLevelWithContainmentOff(t *testing.T) {
b := testExecBackend(t)
for _, kind := range []spawnKind{spawnInstance, spawnSidecar, spawnSeed, spawnWorker} {
diff --git a/internal/activator/control.go b/internal/activator/control.go
index bdac8ae1c..e2416d17d 100644
--- a/internal/activator/control.go
+++ b/internal/activator/control.go
@@ -46,6 +46,19 @@ type GenControl interface {
var _ GenControl = (*instancectl.Client)(nil)
+// SizeControl is root's live size verbs (#329, spec §5.4): POST /size
+// writes host's slice and, with gen, that generation unit's memory; GET
+// /size reads both back. It is separate from GenControl, as
+// StagedExeControl is, so a channel without it (a fake, an older client)
+// still satisfies GenControl, and no call through genControl() can reach a
+// size verb (Astra plan R8-2).
+type SizeControl interface {
+ Size(ctx context.Context, host string, gen uint64, size string, memoryMax int64) (instancectl.SizeReadBack, error)
+ ReadSize(ctx context.Context, host string, gen uint64) (instancectl.SizeReadBack, error)
+}
+
+var _ SizeControl = (*instancectl.Client)(nil)
+
// StagedExeControl is the original templates' half of naming an
// executable (settings spec §4.2): the run unit at generation 0 and the
// seed unit, started on a staged build root validates and binds in place
diff --git a/internal/activator/genbackend.go b/internal/activator/genbackend.go
index 5f0a5f2cd..29bf2134b 100644
--- a/internal/activator/genbackend.go
+++ b/internal/activator/genbackend.go
@@ -361,6 +361,36 @@ func (b *SplitBackend) GenTier(rt registry.Route, build string) cgroup.Limit {
return gb.GenTier(rt, build)
}
+// sizeExec picks the exec half for a live size change (#329). A unit-backed
+// row has no size, and an exec half without the seam has no live change:
+// both are errSizeNotLive.
+func (b *SplitBackend) sizeExec(rt registry.Route) (SizeBackend, error) {
+ if rt.Backing == registry.BackingUnit {
+ return nil, fmt.Errorf("%s: %w (unit-backed)", rt.Host, errSizeNotLive)
+ }
+ sb, ok := b.Exec.(SizeBackend)
+ if !ok {
+ return nil, errSizeNotLive
+ }
+ return sb, nil
+}
+
+func (b *SplitBackend) ResizeLive(ctx context.Context, rt registry.Route, gen uint64, size cgroup.Size, memoryMax int64) (instancectl.SizeReadBack, error) {
+ sb, err := b.sizeExec(rt)
+ if err != nil {
+ return instancectl.SizeReadBack{}, err
+ }
+ return sb.ResizeLive(ctx, rt, gen, size, memoryMax)
+}
+
+func (b *SplitBackend) ReadSize(ctx context.Context, rt registry.Route, gen uint64) (instancectl.SizeReadBack, error) {
+ sb, err := b.sizeExec(rt)
+ if err != nil {
+ return instancectl.SizeReadBack{}, err
+ }
+ return sb.ReadSize(ctx, rt, gen)
+}
+
func (b *SplitBackend) GenReady(rt registry.Route, g Gen, p Proc) {
if gb, err := b.genExec(rt); err == nil {
gb.GenReady(rt, g, p)
diff --git a/internal/activator/opset.go b/internal/activator/opset.go
index 27c3d9578..1cc2442ea 100644
--- a/internal/activator/opset.go
+++ b/internal/activator/opset.go
@@ -79,11 +79,23 @@ type straySidecar struct {
// flight, and restoreDone closes when it has finished: the retry is a
// lifecycle operation of the entry, joined by the barrier like a member
// (final review R2-2).
+//
+// resizing marks a live size change in flight (#329, retrySizeLocked), and
+// resizeDone closes when it has finished. It writes the host's slice, which
+// a later instance of the host would share, so it is joined like a
+// restore: the barrier waits for it, and a pending stop keeps the lease
+// until it returns. sizeUnsettled records that a live write may have left
+// the slice and the serving unit at different memory limits (a write that
+// failed partway, or a read-back that disagreed): no swap is admitted until
+// a write settles it.
type opSet struct {
- members map[uint64]*genMember
- raised bool
- restoring bool
- restoreDone chan struct{}
+ members map[uint64]*genMember
+ raised bool
+ restoring bool
+ restoreDone chan struct{}
+ resizing bool
+ resizeDone chan struct{}
+ sizeUnsettled bool
}
// opJoinBound bounds the barrier's wait. A member's owner needs at most a
@@ -110,7 +122,8 @@ func (a *Service) isMember(e *actEntry, m *genMember) bool {
// an attempt (spawning or successor) and waits, bounded by opJoinBound, for
// every member to leave the set, and for a parent restore retry in flight
// to finish (final review R2-2): its write is keyed by host, so once the
-// entry is gone it could lower a later entry's raised parent. It reports
+// entry is gone it could lower a later entry's raised parent. A live size
+// change in flight is joined the same way (#329). It reports
// false when a member's termination was not proven, or the retry did not
// finish, in time. stop() then keeps the lease, exactly as it does for
// ErrStillRunning. An empty set returns true at once.
@@ -126,6 +139,11 @@ func (a *Service) joinOps(e *actEntry) bool {
if e.ops.restoreDone != nil {
waits = append(waits, e.ops.restoreDone)
}
+ if e.ops.resizeDone != nil {
+ // A live size change writes the host's slice (#329): like a
+ // restore, it must not outlive the entry's lease.
+ waits = append(waits, e.ops.resizeDone)
+ }
hook := a.joinWaiting
a.mu.Unlock()
if len(waits) == 0 {
@@ -669,8 +687,8 @@ func (a *Service) reapExited(e *actEntry, m *genMember) {
// releasable is THE retain-until-proven rule for an entry's lease (spec
// §7.4): a stop finishes, and its lease is released, only when every
-// member has left the operation set, no parent restore retry is in flight
-// (final review R2-2), no stray sidecar of the host is tracked (Task 7),
+// member has left the operation set, no parent restore retry and no live
+// size change is in flight (final review R2-2, #329), no stray sidecar of the host is tracked (Task 7),
// the current generation has passed genTerminated (its leader exited and
// its child, or a worker's host cgroup, empty), and every run of the
// instance is proven stopped, its unit stopped and its cgroup empty
@@ -681,14 +699,24 @@ func (a *Service) reapExited(e *actEntry, m *genMember) {
func (a *Service) releasable(e *actEntry) bool {
a.mu.Lock()
members, strays, restoring := len(e.ops.members), len(a.straySidecars[e.host]), e.ops.restoring
+ resizing := e.ops.resizing
rt, g, p := e.route, e.gen, e.proc
a.mu.Unlock()
- if members > 0 || strays > 0 || restoring {
+ if members > 0 || strays > 0 || restoring || resizing {
return false
}
return a.genTerminated(rt, g, p) && a.settleCmds(e)
}
+// resizeInFlight reports whether a live size change of e is in flight
+// (#329). Its write is to the host's slice, so a stop keeps the lease until
+// it returns.
+func (a *Service) resizeInFlight(e *actEntry) bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return e.ops.resizing
+}
+
// keepPendingLocked leaves a stop pending with its lease held: the entry
// stays in stopping, and finishPendingStops finishes it once termination
// is proven. stopRetriedAt is this attempt, so the sweep's re-stop cadence
@@ -701,14 +729,17 @@ func (a *Service) keepPendingLocked(e *actEntry, outcome *stopObservation) {
// reapCurrentGen finishes a pending stop whose main process has exited
// (finishPendingStops), once its termination proof holds: with generations
-// on, the retain-until-proven rule (releasable); with them off, every
+// on, the retain-until-proven rule (releasable); with them off, no live
+// size change in flight (resizeInFlight, #329), every
// sidecar the stop kept unproven re-stopped and exited (sidecarsExited, fix
// wave 1, item 1), then the host cgroup proven empty (stopHostProven, Task
// 8, F6). A failed proof leaves the stop pending, and the next sweep tries
// again. The caller set e.genReaping; this clears it. Never called with
// a.mu held.
func (a *Service) reapCurrentGen(e *actEntry) {
- proven := func(e *actEntry) bool { return a.sidecarsExited(e, true) && a.stopHostProven(e) }
+ proven := func(e *actEntry) bool {
+ return !a.resizeInFlight(e) && a.sidecarsExited(e, true) && a.stopHostProven(e)
+ }
if a.gens {
proven = a.releasable
}
diff --git a/internal/activator/size.go b/internal/activator/size.go
index 3f116520c..ff89a01b3 100644
--- a/internal/activator/size.go
+++ b/internal/activator/size.go
@@ -1,10 +1,14 @@
package activator
import (
+ "context"
+ "errors"
"log"
"sync"
+ "time"
"github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/registry"
)
@@ -45,3 +49,270 @@ func EffectiveSize(gb interface {
s, _ := cgroup.SizeByName("standard")
return s
}
+
+// SizeBackend is the optional Backend capability behind a live size change
+// (#329, spec §5.4): root's /size verbs for a nested host. ResizeLive sizes
+// rt's slice and, with gen, that generation's unit; ReadSize reads both
+// back and writes nothing. A host with no live change (another layout, a
+// channel without the verbs, a unit-backed row) answers errSizeNotLive.
+type SizeBackend interface {
+ ResizeLive(ctx context.Context, rt registry.Route, gen uint64, size cgroup.Size, memoryMax int64) (instancectl.SizeReadBack, error)
+ ReadSize(ctx context.Context, rt registry.Route, gen uint64) (instancectl.SizeReadBack, error)
+}
+
+var (
+ _ SizeBackend = (*ExecBackend)(nil)
+ _ SizeBackend = (*SplitBackend)(nil)
+)
+
+// sizeBackstop is how often an awake entry compares its size column with
+// what it last acted on when no NoteSize has said it moved: the backstop
+// for a missed note. It reads only the local registry, never the store
+// (spec §3a). Each entry's clock starts at its wake, so entries do not
+// compare together.
+const sizeBackstop = 5 * time.Minute
+
+// genTierer is the tier source EffectiveSize reads.
+type genTierer interface {
+ GenTier(registry.Route, string) cgroup.Limit
+}
+
+// sizedDefault is the tier source of a backend with no GenTier: the size
+// column over the default tier.
+type sizedDefault struct{}
+
+func (sizedDefault) GenTier(rt registry.Route, _ string) cgroup.Limit {
+ return SizedLimit(rt, cgroup.TierDefault)
+}
+
+// tierSource is the Service's backend as EffectiveSize's tier source:
+// production's *SplitBackend (Ruling C1), which answers TierDefault for a
+// unit-backed row.
+func (a *Service) tierSource() genTierer {
+ if gt, ok := a.backend.(genTierer); ok {
+ return gt
+ }
+ return sizedDefault{}
+}
+
+// genUnitOf is the generation unit a live size change names for g: g.N
+// when the entry runs in a generation unit of its own (not a worker, and
+// the generation bound a socket of its own, so startRole started it through
+// GenControl), else 0. A canonical handle is numbered with generations off
+// too, but no unit has that number, and root would refuse it (Astra plan
+// R1-8). 0 is root's run-template path: the slice alone.
+func genUnitOf(rt registry.Route, g Gen) uint64 {
+ if !g.Worker && linksCanonical(rt, g) {
+ return g.N
+ }
+ return 0
+}
+
+// SizeState is an awake instance's live size (#329): Gen is the generation
+// unit a change names (0: the slice alone), Raised that a swap holds the
+// parent, Unsettled that a live write may have left the slice and the unit
+// apart, and Want the size its route and build run at now.
+type SizeState struct {
+ Gen uint64
+ Raised bool
+ Unsettled bool
+ Want cgroup.Size
+}
+
+// SizeState answers for an awake instance that is not a worker.
+func (a *Service) SizeState(host string) (SizeState, bool) {
+ a.mu.Lock()
+ e := a.entries[host]
+ if e == nil || e.state != actAwake || e.worker {
+ a.mu.Unlock()
+ return SizeState{}, false
+ }
+ st := SizeState{Gen: genUnitOf(e.route, e.gen), Raised: e.ops.raised, Unsettled: e.ops.sizeUnsettled}
+ rt, build := e.route, e.gen.Build
+ a.mu.Unlock()
+ st.Want = EffectiveSize(a.tierSource(), rt, build)
+ return st, true
+}
+
+// NoteSize says host's size column may have moved (the agent's
+// PolicyChanged): the next sweep compares it at once rather than at the
+// backstop. It never blocks on anything but a.mu.
+func (a *Service) NoteSize(host string) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if e := a.entries[host]; e != nil {
+ e.sizeDirty = true
+ }
+}
+
+// sizeEligibleLocked reports whether e may start a live size change now: it
+// is the host's awake instance entry, not a worker, and nothing else holds
+// its parent (no member, no raised parent, no restore or resize in
+// flight). The caller holds a.mu.
+func (a *Service) sizeEligibleLocked(e *actEntry) bool {
+ return !a.shuttingDown && a.entries[e.host] == e && e.state == actAwake && !e.worker &&
+ e.route.Kind == "instance" && len(e.ops.members) == 0 &&
+ !e.ops.raised && !e.ops.restoring && !e.ops.resizing
+}
+
+// sizeSnap is what a size pass took from its entry under a.mu.
+type sizeSnap struct {
+ sb SizeBackend
+ gt genTierer
+ rt registry.Route
+ g Gen
+ seen string
+ dirty bool
+ unsettled bool
+}
+
+// retrySizeLocked starts a live size pass for e when one is due (#329,
+// spec §5.4): NoteSize marked the column moved, a previous write left the
+// host unsettled, or the slow backstop compare is due. Otherwise it does
+// nothing at all. The pass first compares the column off a.mu, holding
+// nothing back (preflight C6), and only a change takes the resizing mark,
+// after the eligibility checks again. The caller holds a.mu; called from
+// the sweep (finishPendingStops), patterned on retryParentRestoreLocked.
+func (a *Service) retrySizeLocked(e *actEntry) {
+ if e.sizeChecking || !a.sizeEligibleLocked(e) {
+ return
+ }
+ sb, ok := a.backend.(SizeBackend)
+ if !ok {
+ return
+ }
+ now := a.now()
+ if !e.sizeSeenSet {
+ // The wake's fresh row: the size the entry was started at.
+ e.sizeSeen, e.sizeSeenSet, e.sizeCheckedAt = e.route.Size, true, now
+ }
+ dirty, unsettled := e.sizeDirty, e.ops.sizeUnsettled
+ if !dirty && !unsettled && now.Sub(e.sizeCheckedAt) < sizeBackstop {
+ return
+ }
+ e.sizeChecking, e.sizeDirty, e.sizeCheckedAt = true, false, now
+ go a.sizePass(e, sizeSnap{sb: sb, gt: a.tierSource(), rt: e.route, g: e.gen,
+ seen: e.sizeSeen, dirty: dirty, unsettled: unsettled})
+}
+
+// endSizeCheck ends a pass that wrote nothing. redo keeps the change marked
+// for the next sweep.
+func (a *Service) endSizeCheck(e *actEntry, redo bool) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ e.sizeChecking = false
+ if redo {
+ e.sizeDirty = true
+ }
+}
+
+// sizePass is one live size pass, off a.mu. It reads only snapshots of the
+// entry; every entry field is read and written under a.mu.
+//
+// With no operator change (the column is what the entry last acted on) and
+// nothing unsettled it ends after the registry read, with no root call.
+// Otherwise it reads what the slice and the serving unit hold, and writes
+// the size with memory never below anything observed (R1-3, Astra plan
+// R1-9): a shrink sends CPU and IO only, and a unit lagging the slice is
+// brought up to it. The captured tier comes from the read-back, never from
+// the request (R2-1). A refusal (root under host claims, a host with no
+// live change) writes nothing: the size is recorded on the route, and the
+// next start, an overlap successor's included, sizes from it (Astra plan
+// R6-1). Any other failure of the write marks the host unsettled, and no
+// swap is admitted until a write settles it.
+func (a *Service) sizePass(e *actEntry, s sizeSnap) {
+ host := s.rt.Host
+ fresh := s.rt
+ if a.Routes != nil {
+ r, err := a.Routes.Get(host)
+ if err != nil {
+ log.Printf("activator: %s: size check: route lookup: %v (retried next sweep)", host, err)
+ }
+ if err != nil || r == nil {
+ a.endSizeCheck(e, s.dirty)
+ return
+ }
+ fresh = *r
+ }
+ if !s.unsettled && fresh.Size == s.seen {
+ a.endSizeCheck(e, false)
+ return
+ }
+
+ a.mu.Lock()
+ if !a.sizeEligibleLocked(e) || e.gen.N != s.g.N {
+ // A swap, a restore or a stop began since the snapshot: the change
+ // stays marked, and the next sweep that finds the entry eligible
+ // sends it.
+ e.sizeChecking, e.sizeDirty = false, true
+ a.mu.Unlock()
+ return
+ }
+ done := make(chan struct{})
+ e.ops.resizing, e.ops.resizeDone = true, done
+ a.mu.Unlock()
+
+ unit := genUnitOf(s.rt, s.g)
+ want := EffectiveSize(s.gt, fresh, s.g.Build)
+ wrote := false
+ ctx, cancel := context.WithTimeout(context.Background(), instancectl.DeadlineControl)
+ rb, err := s.sb.ReadSize(ctx, fresh, unit)
+ cancel()
+ if err == nil {
+ observed := cgroup.Limit{MemoryMax: rb.SliceMemoryMax}
+ if unit > 0 {
+ observed = cgroup.MaxLimit(observed, cgroup.Limit{MemoryMax: rb.UnitMemoryMax})
+ }
+ mem := cgroup.MaxLimit(want.Limit, observed)
+ ctx, cancel := context.WithTimeout(context.Background(), instancectl.DeadlineControl)
+ rb, err = s.sb.ResizeLive(ctx, fresh, unit, want, mem.MemoryMax)
+ cancel()
+ wrote = true
+ }
+ refused := errors.Is(err, instancectl.ErrSizeRefused) || errors.Is(err, errSizeNotLive)
+
+ a.mu.Lock()
+ switch {
+ case err == nil:
+ // Settled only when the read-back shows the slice and the serving
+ // unit at one memory limit.
+ if rb.SliceMemoryMax > 0 && (unit == 0 || rb.UnitMemoryMax == rb.SliceMemoryMax) {
+ e.ops.sizeUnsettled = false
+ if e.gen.N == s.g.N {
+ e.gen.Tier = cgroup.Limit{MemoryMax: rb.SliceMemoryMax}
+ }
+ } else {
+ e.ops.sizeUnsettled = true
+ }
+ e.sizeSeen, e.route.Size = fresh.Size, fresh.Size
+ case refused:
+ // Nothing written: the next start sizes from the column. The
+ // captured tier and the unsettled mark are unchanged, since a
+ // refusal proves nothing about the limits already on the host.
+ e.sizeSeen, e.route.Size = fresh.Size, fresh.Size
+ case !wrote:
+ // The read failed: nothing was written, so nothing is unsettled,
+ // and the change is retried next sweep.
+ e.sizeDirty = true
+ default:
+ // The write failed partway or not at all: the slice may be written.
+ e.ops.sizeUnsettled = true
+ }
+ unsettled := e.ops.sizeUnsettled
+ e.ops.resizing, e.ops.resizeDone, e.sizeChecking = false, nil, false
+ a.mu.Unlock()
+ close(done)
+
+ switch {
+ case err == nil && unsettled:
+ log.Printf("activator: %s: size %s: the slice holds %d and generation %d holds %d; retried until they agree", host, want.Name, rb.SliceMemoryMax, unit, rb.UnitMemoryMax)
+ case err == nil:
+ log.Printf("activator: %s: size %s applied live (memory.max=%d, gen %d)", host, want.Name, rb.SliceMemoryMax, unit)
+ case refused:
+ log.Printf("activator: %s: size %s not applied live: %v; it takes effect at the next start", host, want.Name, err)
+ case !wrote:
+ log.Printf("activator: %s: size check: read: %v (retried next sweep)", host, err)
+ default:
+ log.Printf("activator: %s: size %s: %v (no swap until a write settles it)", host, want.Name, err)
+ }
+}
diff --git a/internal/activator/size_live_test.go b/internal/activator/size_live_test.go
new file mode 100644
index 000000000..a1c899852
--- /dev/null
+++ b/internal/activator/size_live_test.go
@@ -0,0 +1,756 @@
+package activator
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "slices"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+const (
+ half = int64(1 << 29) // standard
+ gib = int64(1 << 30) // large
+ two = int64(2 << 30) // xlarge
+)
+
+// liveRoutes is the local registry as the live size pass reads it
+// (RouteLookup). gate, when armed, holds the next Get until it closes, and
+// entered is sent to (non-blocking) as that Get reaches it.
+type liveRoutes struct {
+ mu sync.Mutex
+ rows map[string]registry.Route
+ gets int
+ gate chan struct{}
+ entered chan struct{}
+}
+
+func (r *liveRoutes) Get(host string) (*registry.Route, error) {
+ r.mu.Lock()
+ r.gets++
+ gate, entered := r.gate, r.entered
+ r.gate = nil
+ r.mu.Unlock()
+ if gate != nil {
+ select {
+ case entered <- struct{}{}:
+ default:
+ }
+ <-gate
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ rt, ok := r.rows[host]
+ if !ok {
+ return nil, nil
+ }
+ return &rt, nil
+}
+
+func (r *liveRoutes) put(rt registry.Route) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.rows[rt.Host] = rt
+}
+
+func (r *liveRoutes) setSize(host, size string) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ rt := r.rows[host]
+ rt.Size = size
+ r.rows[host] = rt
+}
+
+func (r *liveRoutes) count() int {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.gets
+}
+
+// arm holds the next Get until the returned gate closes; entered receives
+// once that Get is waiting.
+func (r *liveRoutes) arm() (gate, entered chan struct{}) {
+ gate, entered = make(chan struct{}), make(chan struct{}, 1)
+ r.mu.Lock()
+ r.gate, r.entered = gate, entered
+ r.mu.Unlock()
+ return gate, entered
+}
+
+// sizeFixture is the swap fixture with a size column: the entry's route
+// carries size, the incumbent runs at tier (captured), and the fake slice
+// and unit hold tier. The local registry (a.Routes) holds the same row.
+type sizeFixture struct {
+ *swapFixture
+ routes *liveRoutes
+}
+
+func newSizeFixture(t *testing.T, size string, tier int64) *sizeFixture {
+ t.Helper()
+ f := newSwapFixture(t)
+ f.a.mu.Lock()
+ e := f.a.entries[f.host]
+ e.route.Size = size
+ e.gen.Tier = cgroup.Limit{MemoryMax: tier}
+ rt := e.route
+ f.a.mu.Unlock()
+ routes := &liveRoutes{rows: map[string]registry.Route{f.host: rt}}
+ f.a.Routes = routes
+ f.b.gmu.Lock()
+ f.b.sliceMem, f.b.unitMem = tier, tier
+ f.b.gmu.Unlock()
+ return &sizeFixture{swapFixture: f, routes: routes}
+}
+
+// operatorSets is the agent's converge of a new size column: the local
+// registry row changes, then PolicyChanged (NoteSize).
+func (f *sizeFixture) operatorSets(size string) {
+ f.routes.setSize(f.host, size)
+ f.a.NoteSize(f.host)
+}
+
+// sweep runs one sweep and waits for a size pass it launched to finish.
+func (f *sizeFixture) sweep(t *testing.T) {
+ t.Helper()
+ f.a.sweepOnce()
+ waitFor(t, "the size pass to finish", func() bool { return f.a.sizeIdleForTest(f.host) })
+}
+
+func (f *sizeFixture) sizeEvents() []string { return sizeEvents(f.b.events()) }
+
+func (f *sizeFixture) tier() int64 {
+ g, _ := f.a.genStateForTest(f.host)
+ return g.Tier.MemoryMax
+}
+
+func (f *sizeFixture) state(t *testing.T) SizeState {
+ t.Helper()
+ st, ok := f.a.SizeState(f.host)
+ if !ok {
+ t.Fatalf("SizeState(%s) reported no awake instance", f.host)
+ }
+ return st
+}
+
+// sizeEvents keeps the live size calls of an order log.
+func sizeEvents(ev []string) []string {
+ var out []string
+ for _, e := range ev {
+ if strings.HasPrefix(e, "readsize:") || strings.HasPrefix(e, "size:") {
+ out = append(out, e)
+ }
+ }
+ return out
+}
+
+func (a *Service) sizeIdleForTest(host string) bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ e := a.entries[host]
+ return e == nil || (!e.sizeChecking && !e.ops.resizing)
+}
+
+func (a *Service) resizingForTest(host string) bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ e := a.entries[host]
+ return e != nil && e.ops.resizing
+}
+
+func readSizeEv(n uint64) string { return fmt.Sprintf("readsize:%d", n) }
+func sizeEv(name string, mem int64, n uint64) string {
+ return fmt.Sprintf("size:%s/%d/%d", name, mem, n)
+}
+
+func refusedByRoot(code int) error {
+ return fmt.Errorf("%w: instance control /size: %d: refused", instancectl.ErrSizeRefused, code)
+}
+
+var errSize502 = errors.New("instance control /size: 502: set-property carlos-instance-gen@swap.example.com:1.service: failed")
+
+func swapBusy(t *testing.T, f *sizeFixture) {
+ t.Helper()
+ res := f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest)
+ if res.Outcome != SwapAbandoned || !strings.Contains(res.Reason, errSwapBusy.Error()) {
+ t.Fatalf("Swap = %+v, want abandoned as busy", res)
+ }
+}
+
+// An operator growth writes the slice and the serving unit, after reading
+// what they hold, and the captured tier comes from the read-back.
+func TestLiveGrowthWritesSliceAndUnitAndCapturesTheReadBack(t *testing.T) {
+ t.Parallel()
+ f := newSizeFixture(t, "", half)
+ n := f.incumbent.N
+ f.operatorSets("large")
+ f.sweep(t)
+ if got, want := f.sizeEvents(), []string{readSizeEv(n), sizeEv("large", gib, n)}; !slices.Equal(got, want) {
+ t.Fatalf("size calls %v, want %v", got, want)
+ }
+ if got := f.tier(); got != cgroup.TierChildren.MemoryMax {
+ t.Fatalf("captured tier %d, want %d", got, cgroup.TierChildren.MemoryMax)
+ }
+ if st := f.state(t); st.Unsettled || st.Raised || st.Gen != n || st.Want.Name != "large" {
+ t.Fatalf("SizeState = %+v", st)
+ }
+}
+
+// Astra plan R1-8: with generations off the handle is numbered but no unit
+// has that number, so the pass sizes the run template's slice (gen 0).
+func TestLiveGrowthWithGenerationsOffUsesTheRunTemplate(t *testing.T) {
+ t.Parallel()
+ f := newSizeFixture(t, "", half)
+ f.a.gens = false
+ f.a.mu.Lock()
+ rt := f.a.entries[f.host].route
+ f.a.mu.Unlock()
+ g := canonicalGen(rt, 7, "v1")
+ g.Tier = cgroup.Limit{MemoryMax: half}
+ setCurrentGen(t, f.a, f.host, g)
+ f.b.setSizeHooks(func(gen uint64) (instancectl.SizeReadBack, error) {
+ if gen != 0 {
+ return instancectl.SizeReadBack{}, refusedByRoot(409)
+ }
+ return instancectl.SizeReadBack{SliceMemoryMax: half}, nil
+ }, func(gen uint64, _ cgroup.Size, mem int64) (instancectl.SizeReadBack, error) {
+ if gen != 0 {
+ return instancectl.SizeReadBack{}, refusedByRoot(409)
+ }
+ return instancectl.SizeReadBack{SliceMemoryMax: mem}, nil
+ })
+ f.operatorSets("large")
+ f.sweep(t)
+ if got, want := f.sizeEvents(), []string{readSizeEv(0), sizeEv("large", gib, 0)}; !slices.Equal(got, want) {
+ t.Fatalf("size calls %v, want %v", got, want)
+ }
+ st := f.state(t)
+ if st.Gen != 0 || st.Unsettled || st.Want.Name != "large" {
+ t.Fatalf("SizeState = %+v", st)
+ }
+ if got := f.tier(); got != gib {
+ t.Fatalf("captured tier %d, want %d (no pending mark)", got, gib)
+ }
+}
+
+// A change that lands mid-swap waits for the set to empty and the parent
+// to be restored, then goes out once.
+func TestLiveChangeWaitsForTheSwapToRestore(t *testing.T) {
+ t.Parallel()
+ f := newSizeFixture(t, "", half)
+ f.b.gmu.Lock()
+ f.b.genGate = make(chan struct{})
+ f.b.gmu.Unlock()
+ swapped := make(chan SwapResult, 1)
+ go func() { swapped <- f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest) }()
+ waitFor(t, "the successor in the operation set", func() bool {
+ _, members := f.a.genStateForTest(f.host)
+ return len(members) == 1
+ })
+ f.operatorSets("large")
+ f.sweep(t)
+ if ev := f.sizeEvents(); len(ev) != 0 {
+ t.Fatalf("size calls %v while a swap held the parent", ev)
+ }
+ f.b.gmu.Lock()
+ close(f.b.genGate)
+ f.b.gmu.Unlock()
+ if res := <-swapped; res.Outcome != SwapDone {
+ t.Fatalf("Swap = %+v", res)
+ }
+ f.sweep(t)
+ ev := f.b.events()
+ var sizes []int
+ for i, e := range ev {
+ if strings.HasPrefix(e, "size:") {
+ sizes = append(sizes, i)
+ }
+ }
+ restore := -1
+ for i, e := range ev {
+ if strings.HasPrefix(e, "restore:") {
+ restore = i
+ }
+ }
+ if len(sizes) != 1 || restore < 0 || sizes[0] < restore {
+ t.Fatalf("events %v: want exactly one size call, after the parent restore", ev)
+ }
+ succ, _ := f.a.genStateForTest(f.host)
+ if want := sizeEv("large", gib, succ.N); ev[sizes[0]] != want {
+ t.Fatalf("size call %q, want %q", ev[sizes[0]], want)
+ }
+}
+
+// Astra plan R6-1: a refused live change still records the size on the
+// entry's route, so the next start, an overlap successor included, sizes
+// from it.
+func TestARefusedLiveResizeStillReachesTheNextSwap(t *testing.T) {
+ t.Parallel()
+ f := newSizeFixture(t, "standard", half)
+ f.b.setSizeHooks(func(uint64) (instancectl.SizeReadBack, error) {
+ return instancectl.SizeReadBack{}, fmt.Errorf("flat row: %w", errSizeNotLive)
+ }, nil)
+ f.operatorSets("xlarge")
+ f.sweep(t)
+ if got, want := f.sizeEvents(), []string{readSizeEv(f.incumbent.N)}; !slices.Equal(got, want) {
+ t.Fatalf("size calls %v, want %v", got, want)
+ }
+ if st := f.state(t); st.Unsettled || st.Want.Name != "xlarge" {
+ t.Fatalf("SizeState = %+v", st)
+ }
+ res := f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest)
+ if res.Outcome != SwapDone || res.Gen.Tier.MemoryMax != two {
+ t.Fatalf("Swap = %+v, want done at %d", res, two)
+ }
+ if ev := f.b.events(); indexPrefix(ev, fmt.Sprintf("raise:%d+%d", half, two)) < 0 {
+ t.Fatalf("events %v: want the raise to 512 MiB + 2 GiB", ev)
+ }
+}
+
+// A resize in flight, and then a write that did not settle, keep every
+// swap out until a write's read-back shows slice and unit at one value.
+func TestSwapRefusedWhileResizingOrUnsettled(t *testing.T) {
+ t.Parallel()
+ f := newSizeFixture(t, "", half)
+ n := f.incumbent.N
+ entered, gate := make(chan struct{}, 1), make(chan struct{})
+ var failing atomic.Bool
+ failing.Store(true)
+ f.b.setSizeHooks(nil, func(_ uint64, _ cgroup.Size, mem int64) (instancectl.SizeReadBack, error) {
+ select {
+ case entered <- struct{}{}:
+ default:
+ }
+ <-gate
+ if failing.Load() {
+ return instancectl.SizeReadBack{}, errSize502
+ }
+ return instancectl.SizeReadBack{SliceMemoryMax: mem, UnitMemoryMax: mem}, nil
+ })
+ f.operatorSets("large")
+ f.a.sweepOnce()
+ <-entered
+ swapBusy(t, f) // resizing
+ close(gate)
+ waitFor(t, "the size pass to finish", func() bool { return f.a.sizeIdleForTest(f.host) })
+ if st := f.state(t); !st.Unsettled {
+ t.Fatalf("SizeState = %+v after a 502, want unsettled", st)
+ }
+ swapBusy(t, f) // unsettled
+
+ failing.Store(false)
+ f.sweep(t) // no operator change: the unsettled mark alone retries
+ want := []string{readSizeEv(n), sizeEv("large", gib, n), readSizeEv(n), sizeEv("large", gib, n)}
+ if got := f.sizeEvents(); !slices.Equal(got, want) {
+ t.Fatalf("size calls %v, want %v", got, want)
+ }
+ if st := f.state(t); st.Unsettled {
+ t.Fatalf("SizeState = %+v, want settled", st)
+ }
+ if got := f.tier(); got != gib {
+ t.Fatalf("captured tier %d, want %d from the read-back", got, gib)
+ }
+ if res := f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest); res.Outcome != SwapDone {
+ t.Fatalf("Swap = %+v once settled", res)
+ }
+}
+
+// Astra plan R1-9: a policy reversed after a partial growth brings the
+// unit up to the slice rather than asking for a shrink, and only a write
+// that settles clears the mark.
+func TestPolicyReversalAfterAPartialGrowthStaysUnsettled(t *testing.T) {
+ t.Parallel()
+ for _, refuse := range []bool{false, true} {
+ t.Run(fmt.Sprintf("refused=%v", refuse), func(t *testing.T) {
+ t.Parallel()
+ f := newSizeFixture(t, "", half)
+ n := f.incumbent.N
+ var mu sync.Mutex
+ slice, unit, failNext := half, half, true
+ f.b.setSizeHooks(func(uint64) (instancectl.SizeReadBack, error) {
+ mu.Lock()
+ defer mu.Unlock()
+ return instancectl.SizeReadBack{SliceMemoryMax: slice, UnitMemoryMax: unit}, nil
+ }, func(_ uint64, _ cgroup.Size, mem int64) (instancectl.SizeReadBack, error) {
+ mu.Lock()
+ defer mu.Unlock()
+ if failNext {
+ // The slice was written; the unit's write failed.
+ failNext, slice = false, mem
+ return instancectl.SizeReadBack{}, errSize502
+ }
+ if refuse {
+ return instancectl.SizeReadBack{}, refusedByRoot(409)
+ }
+ slice, unit = mem, mem
+ return instancectl.SizeReadBack{SliceMemoryMax: slice, UnitMemoryMax: unit}, nil
+ })
+ f.operatorSets("xlarge")
+ f.sweep(t)
+ if st := f.state(t); !st.Unsettled {
+ t.Fatalf("SizeState = %+v after a partial growth, want unsettled", st)
+ }
+ f.operatorSets("standard")
+ f.sweep(t)
+ want := []string{readSizeEv(n), sizeEv("xlarge", two, n), readSizeEv(n), sizeEv("standard", two, n)}
+ if got := f.sizeEvents(); !slices.Equal(got, want) {
+ t.Fatalf("size calls %v, want %v", got, want)
+ }
+ if refuse {
+ if st := f.state(t); !st.Unsettled {
+ t.Fatalf("SizeState = %+v, a refusal must not settle", st)
+ }
+ if got := f.tier(); got != half {
+ t.Fatalf("captured tier %d after a refusal, want %d unchanged", got, half)
+ }
+ swapBusy(t, f)
+ return
+ }
+ if st := f.state(t); st.Unsettled || st.Want.Name != "standard" {
+ t.Fatalf("SizeState = %+v, want settled at standard", st)
+ }
+ if got := f.tier(); got != two {
+ t.Fatalf("captured tier %d, want %d", got, two)
+ }
+ res := f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest)
+ if res.Outcome != SwapDone || res.Gen.Tier.MemoryMax != two {
+ t.Fatalf("Swap = %+v, want done at %d", res, two)
+ }
+ ev := f.b.events()
+ if indexPrefix(ev, fmt.Sprintf("raise:%d+%d", two, two)) < 0 {
+ t.Fatalf("events %v: want the raise from 2 GiB", ev)
+ }
+ for _, e := range ev {
+ if strings.HasPrefix(e, "restore:") && e != fmt.Sprintf("restore:%d", two) {
+ t.Fatalf("events %v: a restore below the slice", ev)
+ }
+ }
+ })
+ }
+}
+
+// A memory shrink sends CPU and IO only: memory is held where it is, and
+// the size stays pending until a cold start.
+func TestMemoryShrinkSendsOnlyCPUAndIOAndStaysPending(t *testing.T) {
+ t.Parallel()
+ f := newSizeFixture(t, "large", gib)
+ n := f.incumbent.N
+ f.operatorSets("small")
+ f.sweep(t)
+ if got, want := f.sizeEvents(), []string{readSizeEv(n), sizeEv("small", gib, n)}; !slices.Equal(got, want) {
+ t.Fatalf("size calls %v, want %v", got, want)
+ }
+ if st := f.state(t); st.Want.Name != "small" || st.Unsettled {
+ t.Fatalf("SizeState = %+v, want small", st)
+ }
+ if got := f.tier(); got != gib {
+ t.Fatalf("captured tier %d, want %d held", got, gib)
+ }
+}
+
+// Back to the size in force: nothing is pending any more.
+func TestSizeBackToTheOneInForceClearsPending(t *testing.T) {
+ t.Parallel()
+ f := newSizeFixture(t, "large", gib)
+ n := f.incumbent.N
+ f.operatorSets("small")
+ f.sweep(t)
+ f.operatorSets("large")
+ f.sweep(t)
+ ev := f.sizeEvents()
+ if len(ev) != 4 || ev[3] != sizeEv("large", gib, n) {
+ t.Fatalf("size calls %v, want the last %s", ev, sizeEv("large", gib, n))
+ }
+ st := f.state(t)
+ if s, _ := cgroup.SizeOf(cgroup.Limit{MemoryMax: f.tier()}); st.Want.Name != "large" || s.Name != st.Want.Name {
+ t.Fatalf("SizeState = %+v at tier %d, want large with nothing pending", st, f.tier())
+ }
+}
+
+// A release that changes the build's tier, sweeps, the backstop and a
+// NoteSize with no size change: no live call, ever.
+func TestNoLiveCallWithoutAnOperatorChange(t *testing.T) {
+ t.Parallel()
+ f := newSizeFixture(t, "", gib)
+ f.b.tiers = map[string]cgroup.Limit{"v1": cgroup.TierChildren, "v2": cgroup.TierDefault}
+ f.sweep(t)
+ if res := f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest); res.Outcome != SwapDone {
+ t.Fatalf("Swap = %+v", res)
+ }
+ f.sweep(t)
+ f.clk.advance(sizeBackstop)
+ f.sweep(t)
+ f.a.NoteSize(f.host) // an egress-only policy change
+ f.sweep(t)
+ if ev := f.sizeEvents(); len(ev) != 0 {
+ t.Fatalf("size calls %v with no operator change", ev)
+ }
+}
+
+// Preflight C6: a check that finds no change holds nothing. While it reads
+// the registry the entry is not resizing, so a swap is admitted, and no
+// root call follows.
+func TestASizeCheckWithNoChangeHoldsNothing(t *testing.T) {
+ t.Parallel()
+ f := newSizeFixture(t, "", half)
+ f.sweep(t)
+ gate, entered := f.routes.arm()
+ f.a.NoteSize(f.host)
+ f.a.sweepOnce()
+ <-entered
+ if f.a.resizingForTest(f.host) {
+ t.Fatal("a registry compare marked the entry resizing")
+ }
+ if res := f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest); res.Outcome != SwapDone {
+ t.Fatalf("Swap during the check = %+v, want done", res)
+ }
+ close(gate)
+ waitFor(t, "the size check to finish", func() bool { return f.a.sizeIdleForTest(f.host) })
+ if ev := f.sizeEvents(); len(ev) != 0 {
+ t.Fatalf("size calls %v with no operator change", ev)
+ }
+}
+
+// A size change whose NoteSize was missed is found by the slow backstop
+// compare, and nothing reads the registry before it is due.
+func TestTheBackstopCatchesAMissedNoteSize(t *testing.T) {
+ t.Parallel()
+ f := newSizeFixture(t, "", half)
+ n := f.incumbent.N
+ f.sweep(t)
+ f.routes.setSize(f.host, "large") // no NoteSize
+ before := f.routes.count()
+ f.sweep(t)
+ if ev := f.sizeEvents(); len(ev) != 0 {
+ t.Fatalf("size calls %v before the backstop", ev)
+ }
+ if got := f.routes.count(); got != before {
+ t.Fatalf("%d registry reads before the backstop was due", got-before)
+ }
+ f.clk.advance(sizeBackstop)
+ f.sweep(t)
+ if got, want := f.sizeEvents(), []string{readSizeEv(n), sizeEv("large", gib, n)}; !slices.Equal(got, want) {
+ t.Fatalf("size calls %v, want %v", got, want)
+ }
+}
+
+// Nothing is sized live for a host that is asleep or a worker, and a host
+// with no live size (flat) is asked once per change, with no unsettled
+// mark and no retries.
+func TestNoLiveCallForAsleepWorkerOrFlat(t *testing.T) {
+ t.Parallel()
+ t.Run("asleep", func(t *testing.T) {
+ t.Parallel()
+ f := newSizeFixture(t, "", half)
+ asleep := testRoute("asleep.example.com")
+ asleep.Size = "large"
+ f.routes.put(asleep)
+ f.a.NoteSize(asleep.Host)
+ f.sweep(t)
+ f.clk.advance(sizeBackstop)
+ f.sweep(t)
+ if ev := f.sizeEvents(); len(ev) != 0 {
+ t.Fatalf("size calls %v for an asleep host", ev)
+ }
+ if _, ok := f.a.SizeState(asleep.Host); ok {
+ t.Fatal("SizeState answered for an asleep host")
+ }
+ })
+ t.Run("worker", func(t *testing.T) {
+ t.Parallel()
+ f := newSizeFixture(t, "", half)
+ w := testWorkerRoute("bot.example.com")
+ w.Hibernate = false
+ f.routes.put(w)
+ if err := f.a.WakeWorker(w); err != nil {
+ t.Fatalf("WakeWorker: %v", err)
+ }
+ f.routes.setSize(w.Host, "large")
+ f.a.NoteSize(w.Host)
+ f.sweep(t)
+ f.clk.advance(sizeBackstop)
+ f.sweep(t)
+ if ev := f.sizeEvents(); len(ev) != 0 {
+ t.Fatalf("size calls %v for a worker", ev)
+ }
+ if _, ok := f.a.SizeState(w.Host); ok {
+ t.Fatal("SizeState answered for a worker")
+ }
+ })
+ t.Run("flat", func(t *testing.T) {
+ t.Parallel()
+ f := newSizeFixture(t, "", half)
+ f.b.setSizeHooks(func(uint64) (instancectl.SizeReadBack, error) {
+ return instancectl.SizeReadBack{}, fmt.Errorf("flat row: %w", errSizeNotLive)
+ }, func(uint64, cgroup.Size, int64) (instancectl.SizeReadBack, error) {
+ return instancectl.SizeReadBack{}, fmt.Errorf("flat row: %w", errSizeNotLive)
+ })
+ f.operatorSets("large")
+ f.sweep(t)
+ f.sweep(t)
+ f.clk.advance(sizeBackstop)
+ f.sweep(t)
+ if got, want := f.sizeEvents(), []string{readSizeEv(f.incumbent.N)}; !slices.Equal(got, want) {
+ t.Fatalf("size calls %v, want only %v", got, want)
+ }
+ if st := f.state(t); st.Unsettled {
+ t.Fatalf("SizeState = %+v, want no unsettled mark", st)
+ }
+ })
+}
+
+// Under host claims root answers 503 to the read: nothing is written live,
+// the size is recorded, and the next start carries it (spec §5.4 rev 8).
+func TestNoLiveChangeUnderClaims(t *testing.T) {
+ t.Parallel()
+ f := newSizeFixture(t, "", half)
+ refused := func() (instancectl.SizeReadBack, error) { return instancectl.SizeReadBack{}, refusedByRoot(503) }
+ f.b.setSizeHooks(func(uint64) (instancectl.SizeReadBack, error) { return refused() },
+ func(uint64, cgroup.Size, int64) (instancectl.SizeReadBack, error) { return refused() })
+ f.operatorSets("xlarge")
+ f.sweep(t)
+ f.sweep(t)
+ f.clk.advance(sizeBackstop)
+ f.sweep(t)
+ if got, want := f.sizeEvents(), []string{readSizeEv(f.incumbent.N)}; !slices.Equal(got, want) {
+ t.Fatalf("size calls %v, want only %v", got, want)
+ }
+ if st := f.state(t); st.Unsettled || st.Want.Name != "xlarge" {
+ t.Fatalf("SizeState = %+v, want xlarge pending with no unsettled mark", st)
+ }
+ if got := f.tier(); got != half {
+ t.Fatalf("captured tier %d, want %d unchanged", got, half)
+ }
+ // The next spawn: the host sleeps, then wakes on the size column.
+ f.clk.advance(2 * time.Hour)
+ f.a.sweepOnce()
+ waitFor(t, "the host asleep", func() bool { return f.a.entryCount() == 0 })
+ f.routes.mu.Lock()
+ rt := f.routes.rows[f.host]
+ f.routes.mu.Unlock()
+ rt.Size = ""
+ arrangeAwake(t, f.a, rt)
+ if got := f.b.lastStartedRoute(); got.Size != "xlarge" || SizedLimit(got, cgroup.TierDefault).MemoryMax != two {
+ t.Fatalf("the next spawn's route size %q, want xlarge at %d", got.Size, two)
+ }
+}
+
+// A terminal stop joins a resize in flight before it releases the lease.
+func TestJoinOpsWaitsForAResizeInFlight(t *testing.T) {
+ t.Parallel()
+ f := newSizeFixture(t, "", half)
+ entered, gate := make(chan struct{}, 1), make(chan struct{})
+ f.b.setSizeHooks(nil, func(_ uint64, _ cgroup.Size, mem int64) (instancectl.SizeReadBack, error) {
+ select {
+ case entered <- struct{}{}:
+ default:
+ }
+ <-gate
+ return instancectl.SizeReadBack{SliceMemoryMax: mem, UnitMemoryMax: mem}, nil
+ })
+ var joined atomic.Bool
+ f.a.mu.Lock()
+ f.a.joinWaiting = func(_, what string) {
+ if what == "operation set" {
+ joined.Store(true)
+ }
+ }
+ f.a.mu.Unlock()
+ f.operatorSets("large")
+ f.a.sweepOnce()
+ <-entered
+ rep := f.b.lastRep()
+ if !f.a.Bounce(f.host) {
+ t.Fatal("Bounce found no awake instance")
+ }
+ waitFor(t, "the stop at the barrier", joined.Load)
+ time.Sleep(150 * time.Millisecond)
+ if rep.isClosed() {
+ t.Fatal("the lease was released while a resize was in flight")
+ }
+ close(gate)
+ waitFor(t, "the lease released after the resize", rep.isClosed)
+}
+
+// sizingBackend is the barrier fixture's backend with the live size seam:
+// ReadSize answers a 512 MiB slice, and ResizeLive signals entered and
+// blocks on gate.
+type sizingBackend struct {
+ *fakeBackend
+ entered chan struct{}
+ gate chan struct{}
+}
+
+func (s *sizingBackend) ReadSize(context.Context, registry.Route, uint64) (instancectl.SizeReadBack, error) {
+ return instancectl.SizeReadBack{SliceMemoryMax: half}, nil
+}
+
+func (s *sizingBackend) ResizeLive(_ context.Context, _ registry.Route, _ uint64, _ cgroup.Size, mem int64) (instancectl.SizeReadBack, error) {
+ select {
+ case s.entered <- struct{}{}:
+ default:
+ }
+ <-s.gate
+ return instancectl.SizeReadBack{SliceMemoryMax: mem}, nil
+}
+
+// Astra plan R8-1: a stop whose barrier gave up on a resize stays pending
+// with the lease, and neither of reapCurrentGen's proofs releases it while
+// the resize runs. Not parallel: it sets opJoinBound.
+func TestPendingStopKeepsTheLeaseWhileAResizeRuns(t *testing.T) {
+ prev := opJoinBound
+ opJoinBound = 100 * time.Millisecond
+ t.Cleanup(func() { opJoinBound = prev })
+ for _, gens := range []bool{true, false} {
+ name := "generations off"
+ if gens {
+ name = "generations on"
+ }
+ t.Run(name, func(t *testing.T) {
+ x := awakeForBarrier(t, gens)
+ sb := &sizingBackend{fakeBackend: x.b, entered: make(chan struct{}, 1), gate: make(chan struct{})}
+ x.a.mu.Lock()
+ x.a.backend = sb
+ rt := x.a.entries[x.host].route
+ x.a.mu.Unlock()
+ rt.Size = "large"
+ x.a.Routes = &liveRoutes{rows: map[string]registry.Route{x.host: rt}}
+ x.a.NoteSize(x.host)
+ x.a.sweepOnce()
+ <-sb.entered
+ rep := x.b.lastRep()
+ if !x.a.Bounce(x.host) {
+ t.Fatal("Bounce found no awake instance")
+ }
+ entry := func() (pending, reaping, resizing bool) {
+ x.a.mu.Lock()
+ defer x.a.mu.Unlock()
+ e := x.a.entries[x.host]
+ if e == nil {
+ return false, false, false
+ }
+ return e.pendingStop, e.genReaping, e.ops.resizing
+ }
+ waitFor(t, "the stop pending past the barrier's bound", func() bool { p, _, _ := entry(); return p })
+ for i := 0; i < 2; i++ {
+ x.a.sweepOnce()
+ waitFor(t, "the reap pass to finish", func() bool { _, r, _ := entry(); return !r })
+ pending, _, resizing := entry()
+ if rep.isClosed() || !pending || !resizing {
+ t.Fatalf("sweep %d: lease closed %v, pending %v, resizing %v; want the lease held while the resize runs", i, rep.isClosed(), pending, resizing)
+ }
+ }
+ close(sb.gate)
+ waitFor(t, "the resize to finish", func() bool { _, _, r := entry(); return !r })
+ x.a.sweepOnce()
+ waitFor(t, "the lease released", rep.isClosed)
+ })
+ }
+}
diff --git a/internal/activator/swap.go b/internal/activator/swap.go
index 2cded1bc0..2827cc05b 100644
--- a/internal/activator/swap.go
+++ b/internal/activator/swap.go
@@ -466,7 +466,11 @@ func (a *Service) swapOverlap(ctx context.Context, gb SwapBackend, at Attempt, n
// failed and awaits the sweep's retry (final review F11): an overlap
// raising it again now could have that retry lower it under the
// successor.
- if len(e.ops.members) > 0 || e.ops.raised {
+ // A live size change in flight, or one that may have left the
+ // slice and the unit apart (#329), is refused too: the swap would
+ // size its parent from a captured tier below what the slice may
+ // already hold.
+ if len(e.ops.members) > 0 || e.ops.raised || e.ops.resizing || e.ops.sizeUnsettled {
return errSwapBusy
}
// A run's unit may be starting against the incumbent right now
diff --git a/internal/activator/swap_fixture_test.go b/internal/activator/swap_fixture_test.go
index f459eecf2..103358c77 100644
--- a/internal/activator/swap_fixture_test.go
+++ b/internal/activator/swap_fixture_test.go
@@ -15,13 +15,15 @@ import (
"time"
"github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/registry"
)
-// fakeSwapBackend is fakeBackend plus the swap seam (SwapBackend). Every call is recorded in
-// the shared order log: raise:<incumbent>+<successor>, startGen:<path>,
-// switch:<n>, restore:<tier>,
-// startSidecarGen:<path>. Generation children are fakeProcs labelled
+// fakeSwapBackend is fakeBackend plus the swap seam (SwapBackend) and the
+// live size seam (SizeBackend). Every call is recorded in the shared order
+// log: raise:<incumbent>+<successor>, startGen:<path>, switch:<n>,
+// restore:<tier>, startSidecarGen:<path>, readsize:<gen>,
+// size:<name>/<mem>/<gen>. Generation children are fakeProcs labelled
// gen:<n>.
type fakeSwapBackend struct {
*fakeBackend
@@ -73,6 +75,68 @@ type fakeSwapBackend struct {
// and recorded only once it writes.
restoreGate chan struct{}
restoreEntered chan struct{}
+ // The live size seam (Task 6). sizeRead and sizeWrite, when set, answer
+ // ReadSize and ResizeLive after the call is recorded; otherwise the
+ // fake is a slice and a unit that follow the writes (sliceMem,
+ // unitMem; 512 MiB until written). Recorded as readsize:<gen> and
+ // size:<name>/<mem>/<gen>.
+ sizeRead func(gen uint64) (instancectl.SizeReadBack, error)
+ sizeWrite func(gen uint64, size cgroup.Size, mem int64) (instancectl.SizeReadBack, error)
+ sliceMem int64
+ unitMem int64
+}
+
+// sizeReadBackLocked is what the fake slice and unit hold. g.gmu is held.
+func (g *fakeSwapBackend) sizeReadBackLocked(gen uint64) instancectl.SizeReadBack {
+ if g.sliceMem == 0 {
+ g.sliceMem = cgroup.TierDefault.MemoryMax
+ }
+ if g.unitMem == 0 {
+ g.unitMem = cgroup.TierDefault.MemoryMax
+ }
+ rb := instancectl.SizeReadBack{SliceMemoryMax: g.sliceMem}
+ if gen != 0 {
+ rb.UnitMemoryMax = g.unitMem
+ }
+ return rb
+}
+
+func (g *fakeSwapBackend) ReadSize(_ context.Context, _ registry.Route, gen uint64) (instancectl.SizeReadBack, error) {
+ g.record(fmt.Sprintf("readsize:%d", gen))
+ g.gmu.Lock()
+ hook := g.sizeRead
+ g.gmu.Unlock()
+ if hook != nil {
+ return hook(gen)
+ }
+ g.gmu.Lock()
+ defer g.gmu.Unlock()
+ return g.sizeReadBackLocked(gen), nil
+}
+
+func (g *fakeSwapBackend) ResizeLive(_ context.Context, _ registry.Route, gen uint64, size cgroup.Size, mem int64) (instancectl.SizeReadBack, error) {
+ g.record(fmt.Sprintf("size:%s/%d/%d", size.Name, mem, gen))
+ g.gmu.Lock()
+ hook := g.sizeWrite
+ g.gmu.Unlock()
+ if hook != nil {
+ return hook(gen, size, mem)
+ }
+ g.gmu.Lock()
+ defer g.gmu.Unlock()
+ g.sizeReadBackLocked(gen)
+ g.sliceMem = mem
+ if gen != 0 {
+ g.unitMem = mem
+ }
+ return g.sizeReadBackLocked(gen), nil
+}
+
+// setSizeHooks sets the scripted ReadSize and ResizeLive answers.
+func (g *fakeSwapBackend) setSizeHooks(read func(uint64) (instancectl.SizeReadBack, error), write func(uint64, cgroup.Size, int64) (instancectl.SizeReadBack, error)) {
+ g.gmu.Lock()
+ g.sizeRead, g.sizeWrite = read, write
+ g.gmu.Unlock()
}
func (g *fakeSwapBackend) StartStaged(ctx context.Context, _ registry.Route, gen Gen) (Gen, Proc, error) {