activator: default GOMEMLIMIT to 80% of a binary instance's memory.max
Tenant instances ran with no GOMEMLIMIT, so a Go runtime under a cgroup cap kept GOGC's headroom and hit memory.high throttling or the OOM killer before its collector worked hard (#991). A binary instance's run process now gets GOMEMLIMIT set to cgroup.GoMemLimitOf(memory.max), max/10*8 as HighOf computes, from the limit its own cgroup is given for that start: the flat exec child's carlos-exec@ (or generation) cgroup, and the tier root is asked to put on the nested unit. The tier is read once and handed to the spawn, so the env and the cgroup cannot disagree across a live-link repoint; startRole now honours a non-zero tier at generation 0 too. It is a default, not agent-owned: an app whose own layers name GOMEMLIMIT keeps its value verbatim, empty or odd. An uncapped flat child (no delegation) gets none. Under gVisor none is written, since root supplies its own fixed value and drops any the launch carries. Rootfs instances, co-spawned sidecars, sidecar members, seeds and commands are unchanged. LaunchLayers leaves the default out so move env pins do not change across the rollout.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+366
−19
internal/activator/backend_exec.go+31 −5internal/activator/containment.go+7 −7internal/activator/gomemlimit.go+40 −0internal/activator/gomemlimit_test.go+264 −0internal/activator/unitproc_test.go+5 −0internal/cgroup/cgroup.go+6 −0internal/cgroup/cgroup_test.go+13 −7
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go| index 2959a2e4f..10db3c295 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -2597,6 +2597,19 @@ func (b *ExecBackend) spawnChildFrom(ctx context.Context, rt registry.Route, soc |
| // both are live for exec-backed instances, and converging them is deferred |
| // (spec §10.3). |
| childVars := b.agentOwnedVars(rt, controlSocket, fileEnv, ctl != nil) |
| + // The limit this spawn's cgroup takes, read once (b.tier reads the live |
| + // build's manifest) and handed to the spawn below, so GOMEMLIMIT is |
| + // derived from the very memory.max the child runs under (#991). With |
| + // no cgroup manager (no delegation) the child runs uncapped, and gets |
| + // no default. |
| + if tier == (cgroup.Limit{}) { |
| + tier = b.tier(rt) |
| + } |
| + capped := tier |
| + if b.Cgroups == nil { |
| + capped = cgroup.Limit{} |
| + } |
| + childVars = withGoMemLimit(childVars, fileEnv, capped) |
| // Record the build we're about to exec — read the symlink immediately before |
| // the start so it names the version the kernel will resolve. Reading it here, |
| // rather than back in wake() after the health wait, closes a real window: a |
| @@ -2889,6 +2902,17 @@ func (b *ExecBackend) spawnUnitFrom(ctx context.Context, rt registry.Route, sock |
| return nil, "", err |
| } |
| childVars := b.agentOwnedVars(rt, sock+".control", fileEnv, ctl != nil) |
| + // The limit root is asked to start the unit at (startRole), read once |
| + // and handed to it below, so GOMEMLIMIT is derived from the memory.max |
| + // the unit runs under (#991). Under gVisor root supplies its own fixed |
| + // value and drops any the launch file carries (instance-exec's |
| + // gvisorLauncher), so none is written. |
| + if tier == (cgroup.Limit{}) { |
| + tier = b.tier(rt) |
| + } |
| + if b.SandboxEffective != execsandbox.EffectiveGVisor { |
| + childVars = withGoMemLimit(childVars, fileEnv, tier) |
| + } |
| argv := []string{b.liveLink(rt.Host), "--socket", sock, "--db", p.dbPath} |
| if rt.Stateless { |
| argv = b.statelessArgv(rt, b.liveLink(rt.Host), sock) |
| @@ -2992,11 +3016,7 @@ func (b *ExecBackend) spawnUnitFrom(ctx context.Context, rt registry.Route, sock |
| // families gone before this failed wake releases its lease. |
| return fail(markLegacyStartUncertain(markStartUncertain(fmt.Errorf("%s: %w", rt.Host, exitedUnobserved{unit: inv.Unit})))) |
| } |
| - started := tier |
| - if started == (cgroup.Limit{}) { |
| - started = b.tier(rt) |
| - } |
| - log.Printf("activator: %s: started %s memory.max=%d (%s)", rt.Host, inv.Unit, started.MemoryMax, steps.String()) |
| + log.Printf("activator: %s: started %s memory.max=%d (%s)", rt.Host, inv.Unit, tier.MemoryMax, steps.String()) |
| up, err := b.newUnitProcFor(rt, instancectl.RoleRun, gen, p, inv, ctl, logs) |
| if err != nil { |
| // Root has started the unit by now, so the build may have run. |
| @@ -3326,6 +3346,12 @@ func (b *ExecBackend) instanceEnvParts(rt registry.Route) (cfgEnv, ownEnv map[st |
| // is computed over exactly this env, so a target compares what would run, |
| // not a reconstruction of it. The values are raw: the caller HMACs them |
| // and must never log or return them. |
| +// |
| +// One spawn-time default is left out on purpose: GOMEMLIMIT |
| +// (withGoMemLimit, #991). It follows the size and the box's cgroup, not |
| +// the instance's layers, and an app-set value is in fileEnv and so here |
| +// already; pinning the default would refuse every move between a box that |
| +// sets it and one whose agent predates it. |
| func (b *ExecBackend) LaunchEnvironment(rt registry.Route) (map[string]string, []string, error) { |
| env, _, shadowed, err := b.LaunchLayers(rt) |
| return env, shadowed, err |
diff --git a/internal/activator/containment.go b/internal/activator/containment.go| index d3cf6231d..125df502f 100644 |
| --- a/internal/activator/containment.go |
| +++ b/internal/activator/containment.go |
| @@ -363,26 +363,26 @@ func (b *ExecBackend) startRole(ctx context.Context, rt registry.Route, role ins |
| if b.Cfg.HostWrites.Enabled { |
| return instancectl.StartResponse{}, ErrClaimIsolationUnavailable |
| } |
| + // Zero is the live tier. A caller that read it already (spawnUnitFrom, |
| + // whose launch file's GOMEMLIMIT follows it) passes what it read, so |
| + // root is asked for that limit, not a second read of the live build. |
| + if tier == (cgroup.Limit{}) { |
| + tier = b.tier(rt) |
| + } |
| if gen == 0 { |
| if exe == nil { |
| - return b.Control.Start(ctx, rt.Host, role, b.tier(rt).MemoryMax) |
| + return b.Control.Start(ctx, rt.Host, role, tier.MemoryMax) |
| } |
| xc, err := b.stagedExeControl() |
| if err != nil { |
| return instancectl.StartResponse{}, fmt.Errorf("%s: not started on %s: %w", rt.Host, exe.Version, err) |
| } |
| - if tier == (cgroup.Limit{}) { |
| - tier = b.tier(rt) |
| - } |
| return xc.StartExe(ctx, rt.Host, role, tier.MemoryMax, *exe) |
| } |
| gc, err := b.genControl() |
| if err != nil { |
| return instancectl.StartResponse{}, err |
| } |
| - if tier == (cgroup.Limit{}) { |
| - tier = b.tier(rt) |
| - } |
| if exe != nil { |
| // The staged artifact's own tier, not the live link's. |
| return gc.StartGenExe(ctx, rt.Host, gen, tier.MemoryMax, *exe) |
diff --git a/internal/activator/gomemlimit.go b/internal/activator/gomemlimit.go| new file mode 100644 |
| index 000000000..99f23b34e |
| --- /dev/null |
| +++ b/internal/activator/gomemlimit.go |
| @@ -0,0 +1,40 @@ |
| +package activator |
| + |
| +import ( |
| + "strconv" |
| + |
| + "github.com/carlosframework/platform/internal/cgroup" |
| +) |
| + |
| +// goMemLimitVar is the Go runtime's soft memory limit. An instance's cgroup |
| +// caps it (memory.max from its size, memory.high at 90 percent), but a Go |
| +// runtime that is not told the cap keeps GOGC's headroom and meets the |
| +// throttle or the OOM killer before its collector works hard (#991). |
| +const goMemLimitVar = "GOMEMLIMIT" |
| + |
| +// withGoMemLimit is childVars with GOMEMLIMIT defaulted for a binary |
| +// instance's run process whose cgroup memory.max is limit.MemoryMax: |
| +// cgroup.GoMemLimitOf, 80 percent, in bytes. |
| +// |
| +// It is a DEFAULT, never agent-owned: when fileEnv (the app's own layers, |
| +// the rendered config and the instance's <host>.env) names GOMEMLIMIT at |
| +// all, childVars is returned as it is, so the app's value runs verbatim, |
| +// an empty or unparsable one included. A zero limit is a child the agent |
| +// does not know to be capped, and gets nothing. The agent's own process |
| +// environment is not the app's: a GOMEMLIMIT inherited from it (childEnv) |
| +// is overridden by the default. |
| +// |
| +// Only the binary instance run paths call it (spawnChildFrom, |
| +// spawnUnitFrom). A co-spawned sidecar shares its instance's cgroup, and a |
| +// rootfs instance runs several processes under one limit, so 80 percent |
| +// of the cap for each process would overcommit it. Seeds, commands and |
| +// sidecar members (StartWorkerStaged) are left as they were. |
| +func withGoMemLimit(childVars, fileEnv map[string]string, limit cgroup.Limit) map[string]string { |
| + if limit.MemoryMax <= 0 { |
| + return childVars |
| + } |
| + if _, set := fileEnv[goMemLimitVar]; set { |
| + return childVars |
| + } |
| + return withVar(childVars, goMemLimitVar, strconv.FormatInt(cgroup.GoMemLimitOf(limit.MemoryMax), 10)) |
| +} |
diff --git a/internal/activator/gomemlimit_test.go b/internal/activator/gomemlimit_test.go| new file mode 100644 |
| index 000000000..1078aec74 |
| --- /dev/null |
| +++ b/internal/activator/gomemlimit_test.go |
| @@ -0,0 +1,264 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/cgroup" |
| + "github.com/carlosframework/platform/internal/execsandbox" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// withGoMemLimit defaults GOMEMLIMIT to 80 percent of the cgroup's |
| +// memory.max for every size (#991), keeps whatever the app's own layers |
| +// set verbatim (empty and unparsable included), sets nothing for a child |
| +// the agent does not know to be capped, and never writes into the maps it |
| +// is handed. |
| +func TestWithGoMemLimit(t *testing.T) { |
| + want := map[string]string{"small": "214748360", "standard": "429496728", "large": "858993456", "xlarge": "1717986912"} |
| + for _, s := range cgroup.Sizes { |
| + child := map[string]string{"CARLOS_HOST": "h.example.com"} |
| + got := withGoMemLimit(child, map[string]string{"APP": "1"}, s.Limit) |
| + if got[goMemLimitVar] != want[s.Name] { |
| + t.Errorf("%s: GOMEMLIMIT = %q, want %q", s.Name, got[goMemLimitVar], want[s.Name]) |
| + } |
| + if got["CARLOS_HOST"] != "h.example.com" { |
| + t.Errorf("%s: other variables lost: %v", s.Name, got) |
| + } |
| + if _, leaked := child[goMemLimitVar]; leaked { |
| + t.Errorf("%s: the caller's map was written", s.Name) |
| + } |
| + } |
| + small, _ := cgroup.SizeByName("small") |
| + for _, app := range []string{"512MiB", "", "lots", " 1GiB", "off"} { |
| + // The app's value is already in childVars (agentOwnedVars layers |
| + // over fileEnv); the default must leave it exactly as it is. |
| + fileEnv := map[string]string{goMemLimitVar: app} |
| + got := withGoMemLimit(map[string]string{goMemLimitVar: app}, fileEnv, small.Limit) |
| + if v, ok := got[goMemLimitVar]; !ok || v != app { |
| + t.Errorf("app set %q: child has %q (set=%v), want the app's value", app, v, ok) |
| + } |
| + } |
| + if got := withGoMemLimit(map[string]string{"A": "1"}, nil, cgroup.Limit{}); len(got) != 1 || got["A"] != "1" { |
| + t.Errorf("uncapped child: %v, want no GOMEMLIMIT", got) |
| + } |
| +} |
| + |
| +// withoutAgentGoMemLimit clears GOMEMLIMIT from this test process for the |
| +// test's duration: childEnv hands an exec child the agent's environment, |
| +// and an inherited value would hide what the spawn set. |
| +func withoutAgentGoMemLimit(t *testing.T) { |
| + t.Helper() |
| + t.Setenv(goMemLimitVar, "") |
| + if err := os.Unsetenv(goMemLimitVar); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// childEnvFile parses the env(1) dump stageRecordingLiveFullEnv's binary |
| +// writes. |
| +func childEnvFile(t *testing.T, path string) map[string]string { |
| + t.Helper() |
| + child := map[string]string{} |
| + for _, line := range strings.Split(waitForFileContent(t, path, 2*time.Second), "\n") { |
| + if k, v, ok := strings.Cut(line, "="); ok { |
| + child[k] = v |
| + } |
| + } |
| + return child |
| +} |
| + |
| +// A flat instance's exec child carries GOMEMLIMIT at 80 percent of the |
| +// memory.max its own cgroup was given, for the row's size; an app-set |
| +// value (here an empty one) runs instead, verbatim; and a box with no |
| +// cgroup delegation, whose child runs uncapped, sets none. |
| +func TestFlatStartSetsGoMemLimitFromTheChildsCgroup(t *testing.T) { |
| + withoutAgentGoMemLimit(t) |
| + for _, tc := range []struct { |
| + name, size, appEnv string |
| + delegated bool |
| + want string // "-": unset; "cgroup": GoMemLimitOf(memory.max) |
| + }{ |
| + {name: "small", size: "small", delegated: true, want: "cgroup"}, |
| + {name: "large", size: "large", delegated: true, want: "cgroup"}, |
| + {name: "app sets it empty", size: "large", appEnv: "GOMEMLIMIT=\n", delegated: true, want: ""}, |
| + {name: "app sets its own", size: "small", appEnv: "GOMEMLIMIT=100MiB\n", delegated: true, want: "100MiB"}, |
| + {name: "uncapped", size: "large", want: "-"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + b := testExecBackend(t) |
| + root := t.TempDir() |
| + if tc.delegated { |
| + for _, f := range []string{"cgroup.procs", "cgroup.subtree_control"} { |
| + if err := os.WriteFile(filepath.Join(root, f), nil, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + m, err := cgroup.SetupAt(root, t.Logf) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b.Cgroups = m |
| + } |
| + host := "gomem.example.com" |
| + _, envPath := stageRecordingLiveFullEnv(t, b, host, "v1") |
| + if tc.appEnv != "" { |
| + if err := os.WriteFile(filepath.Join(b.DataDir, host+".config.env"), []byte(tc.appEnv), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + rt := registry.Route{Host: host, Kind: "instance", Size: tc.size, Socket: filepath.Join(t.TempDir(), "instance.sock")} |
| + ctx, cancel := recordedCtx(2*time.Second, envPath) |
| + defer cancel() |
| + proc, _, _ := b.Start(ctx, rt) // the fake binary never binds; a health-wait error is expected |
| + if proc != nil { |
| + defer proc.Stop(context.Background()) |
| + } |
| + got, set := childEnvFile(t, envPath)[goMemLimitVar] |
| + want := tc.want |
| + if want == "cgroup" { |
| + raw, err := os.ReadFile(filepath.Join(root, cgroup.ExecName(host), "memory.max")) |
| + if err != nil { |
| + t.Fatalf("memory.max not written: %v", err) |
| + } |
| + max, err := strconv.ParseInt(string(raw), 10, 64) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + size, _ := cgroup.SizeByName(tc.size) |
| + if max != size.Limit.MemoryMax { |
| + t.Fatalf("memory.max = %d, want the %s size's %d", max, tc.size, size.Limit.MemoryMax) |
| + } |
| + want = strconv.FormatInt(cgroup.GoMemLimitOf(max), 10) |
| + } |
| + switch { |
| + case want == "-" && set: |
| + t.Fatalf("uncapped child has GOMEMLIMIT=%q, want none", got) |
| + case want != "-" && (!set || got != want): |
| + t.Fatalf("child GOMEMLIMIT = %q (set=%v), want %q", got, set, want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// nestedLaunchEnv is the environment spawnUnitFrom wrote to the run unit's |
| +// launch file (generation 0). |
| +func nestedLaunchEnv(t *testing.T, b *ExecBackend, rt registry.Route) map[string]string { |
| + t.Helper() |
| + raw, err := os.ReadFile(filepath.Join(provision.InstanceDir(b.DataDir, rt.Host), "launch.run.json")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var l instancectl.Launch |
| + if err := json.Unmarshal(raw, &l); err != nil { |
| + t.Fatal(err) |
| + } |
| + env := map[string]string{} |
| + for _, kv := range l.Env { |
| + if k, v, ok := strings.Cut(kv, "="); ok { |
| + env[k] = v |
| + } |
| + } |
| + return env |
| +} |
| + |
| +// A nested instance's launch file carries GOMEMLIMIT at 80 percent of the |
| +// memory_max root is asked to start the unit at (the slice's memory.max), |
| +// for the row's size; an app-set value runs instead, verbatim. |
| +func TestNestedStartSetsGoMemLimitFromTheTierRootApplies(t *testing.T) { |
| + withoutAgentGoMemLimit(t) |
| + for _, tc := range []struct { |
| + name, size, appEnv, want string // want "": GoMemLimitOf(memory_max) |
| + }{ |
| + {name: "small", size: "small"}, |
| + {name: "xlarge", size: "xlarge"}, |
| + {name: "app sets its own", size: "large", appEnv: "GOMEMLIMIT=odd value\n", want: "odd value"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + ctl := &fakeControl{inv: "inv1"} |
| + unit := &fakeUnit{} |
| + b, rt := nestedBackend(t, ctl, unit) |
| + rt.Size = tc.size |
| + if tc.appEnv != "" { |
| + dir := provision.InstanceDir(b.DataDir, rt.Host) |
| + if err := os.MkdirAll(dir, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(dir, rt.Host+".config.env"), []byte(tc.appEnv), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + var stopServing func() |
| + ctl.onStart = func() { stopServing = serveOK(t, rt.Socket) } |
| + defer func() { |
| + if stopServing != nil { |
| + stopServing() |
| + } |
| + }() |
| + unit.set("active", "inv1", true, true) |
| + p, _, err := b.Start(context.Background(), rt) |
| + if err != nil { |
| + t.Fatalf("Start: %v", err) |
| + } |
| + defer func() { |
| + unit.set("inactive", "inv1", false, false) |
| + ctx, cancel := context.WithTimeout(context.Background(), time.Second) |
| + defer cancel() |
| + _ = p.Stop(ctx) |
| + }() |
| + ctl.mu.Lock() |
| + maxes := append([]int64(nil), ctl.startMaxes...) |
| + ctl.mu.Unlock() |
| + size, _ := cgroup.SizeByName(tc.size) |
| + if len(maxes) != 1 || maxes[0] != size.Limit.MemoryMax { |
| + t.Fatalf("root was asked for memory_max %v, want [%d]", maxes, size.Limit.MemoryMax) |
| + } |
| + want := tc.want |
| + if want == "" { |
| + want = strconv.FormatInt(cgroup.GoMemLimitOf(maxes[0]), 10) |
| + } |
| + if got, set := nestedLaunchEnv(t, b, rt)[goMemLimitVar]; !set || got != want { |
| + t.Fatalf("launch GOMEMLIMIT = %q (set=%v), want %q", got, set, want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Under gVisor the launch file carries no GOMEMLIMIT: root supplies its |
| +// own fixed value to the sandbox and drops any the launch names |
| +// (instance-exec's gvisorLauncher), so the agent writes none. |
| +func TestNestedGVisorStartLeavesGoMemLimitToRoot(t *testing.T) { |
| + withoutAgentGoMemLimit(t) |
| + b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{}) |
| + rt.Host = "bright-otter-42.ex.co" |
| + rt.Account, rt.App = "bab", "tmp-demo-bright-otter-42" |
| + rt.Provisioned, rt.Region, rt.Assigned = true, "fleet/demo", "demo-1" |
| + rt.DemoID, rt.DemoHost, rt.DemoLifetime = "AAAAAAAAAAAAAAAAAAAAAA", rt.Host, "life-1" |
| + rt.DemoExpiresAt = time.Now().Add(time.Hour).Unix() |
| + rt.DBPath = provision.NestedDBPath(b.DataDir, rt.Host) |
| + rt.Socket = filepath.Join(b.RunDirOverride, "instances", rt.Host, "app.sock") |
| + stageLive(t, b, rt.Host, "v1") |
| + b.SandboxEffective = execsandbox.EffectiveGVisor |
| + // Root's answer names the wrong family, so the start fails after the |
| + // launch file is written, before any handle exists to clean up. |
| + b.Control = sandboxAnswerControl{fakeControl: &fakeControl{}, answer: instancectl.StartResponse{ |
| + Unit: instancectl.GVisorUnitName(rt.Host), Sandbox: execsandbox.EffectiveSystemd, InvocationID: "started"}} |
| + if p, _, err := b.spawnUnitFrom(context.Background(), rt, rt.Socket, 0, nil, cgroup.Limit{}); p != nil || err == nil { |
| + t.Fatalf("start: %v, %v; want the mismatch refusal", p, err) |
| + } |
| + env := nestedLaunchEnv(t, b, rt) |
| + if _, ok := env["CARLOS_HOST"]; !ok { |
| + t.Fatalf("launch env is not the instance's: %v", env) |
| + } |
| + if got, set := env[goMemLimitVar]; set { |
| + t.Fatalf("gVisor launch carries GOMEMLIMIT=%q, want none (root's own)", got) |
| + } |
| +} |
diff --git a/internal/activator/unitproc_test.go b/internal/activator/unitproc_test.go| index 0528d203f..96640e9f1 100644 |
| --- a/internal/activator/unitproc_test.go |
| +++ b/internal/activator/unitproc_test.go |
| @@ -28,6 +28,8 @@ type fakeControl struct { |
| inv string |
| seed instancectl.SeedResponse |
| startErr error |
| + // startMaxes is the memory_max of every Start, in order. |
| + startMaxes []int64 |
| // stopGenErr is what fakeGenControl.StopGen answers. |
| stopGenErr error |
| // stopRootfsErr, when set, is what StopRootfs answers for every unit; |
| @@ -66,6 +68,9 @@ type fakeControl struct { |
| func (f *fakeControl) rec(s string) { f.mu.Lock(); f.calls = append(f.calls, s); f.mu.Unlock() } |
| func (f *fakeControl) Start(_ context.Context, host string, role instancectl.Role, max int64) (instancectl.StartResponse, error) { |
| f.rec("start " + host + " " + string(role)) |
| + f.mu.Lock() |
| + f.startMaxes = append(f.startMaxes, max) |
| + f.mu.Unlock() |
| if f.onStart != nil { |
| f.onStart() |
| } |
diff --git a/internal/cgroup/cgroup.go b/internal/cgroup/cgroup.go| index c924b28e9..9029013db 100644 |
| --- a/internal/cgroup/cgroup.go |
| +++ b/internal/cgroup/cgroup.go |
| @@ -160,6 +160,12 @@ func MaxLimit(a, b Limit) Limit { |
| // same number. |
| func HighOf(max int64) int64 { return max / 10 * 9 } |
| +// GoMemLimitOf is the GOMEMLIMIT a Go process gets by default under a |
| +// memory.max of max (#991): 80 percent, in bytes, computed as HighOf is. |
| +// It sits below memory.high (HighOf, 90 percent), so the runtime's |
| +// collector works hard before the kernel starts throttling the cgroup. |
| +func GoMemLimitOf(max int64) int64 { return max / 10 * 8 } |
| + |
| // ExecOOMScoreAdj is written to every exec child's /proc/<pid>/oom_score_adj |
| // right after it starts. The kernel's OOM killer — the memcg one that fires |
| // when carlos-edge.service's own MemoryMax is hit included — scores per |
diff --git a/internal/cgroup/cgroup_test.go b/internal/cgroup/cgroup_test.go| index dd107eabe..d2340e4cc 100644 |
| --- a/internal/cgroup/cgroup_test.go |
| +++ b/internal/cgroup/cgroup_test.go |
| @@ -464,16 +464,16 @@ func TestTiers(t *testing.T) { |
| // TestSizeTableIsTheSpecsBytes pins the size table to spec §5.1's numbers, |
| // byte for byte: each row's MemoryMax, the memory.high HighOf derives from |
| -// it, its shares, and what SharesOf and SizeOf answer for its limit. |
| +// it, the GOMEMLIMIT default GoMemLimitOf derives (#991), its shares, and what SharesOf and SizeOf answer for its limit. |
| func TestSizeTableIsTheSpecsBytes(t *testing.T) { |
| want := map[string]struct { |
| - max, high int64 |
| - sh Shares |
| + max, high, gomem int64 |
| + sh Shares |
| }{ |
| - "small": {268435456, 241591905, Shares{CPUWeight: 50, CPUQuotaPercent: 50, IOWeight: 50}}, |
| - "standard": {536870912, 483183819, Shares{CPUWeight: 100, CPUQuotaPercent: 100, IOWeight: 100}}, |
| - "large": {1073741824, 966367638, Shares{CPUWeight: 100, CPUQuotaPercent: 200, IOWeight: 100}}, |
| - "xlarge": {2147483648, 1932735276, Shares{CPUWeight: 200, CPUQuotaPercent: 400, IOWeight: 200}}, |
| + "small": {268435456, 241591905, 214748360, Shares{CPUWeight: 50, CPUQuotaPercent: 50, IOWeight: 50}}, |
| + "standard": {536870912, 483183819, 429496728, Shares{CPUWeight: 100, CPUQuotaPercent: 100, IOWeight: 100}}, |
| + "large": {1073741824, 966367638, 858993456, Shares{CPUWeight: 100, CPUQuotaPercent: 200, IOWeight: 100}}, |
| + "xlarge": {2147483648, 1932735276, 1717986912, Shares{CPUWeight: 200, CPUQuotaPercent: 400, IOWeight: 200}}, |
| } |
| order := []string{"small", "standard", "large", "xlarge"} |
| if len(Sizes) != len(order) { |
| @@ -491,6 +491,12 @@ func TestSizeTableIsTheSpecsBytes(t *testing.T) { |
| if got := HighOf(row.Limit.MemoryMax); got != w.high { |
| t.Errorf("%s: HighOf = %d, want %d", row.Name, got, w.high) |
| } |
| + if got := GoMemLimitOf(row.Limit.MemoryMax); got != w.gomem { |
| + t.Errorf("%s: GoMemLimitOf = %d, want %d", row.Name, got, w.gomem) |
| + } |
| + if gomem := GoMemLimitOf(row.Limit.MemoryMax); gomem >= w.high { |
| + t.Errorf("%s: GoMemLimitOf = %d is not below memory.high %d", row.Name, gomem, w.high) |
| + } |
| if row.Shares != w.sh { |
| t.Errorf("%s: Shares = %+v, want %+v", row.Name, row.Shares, w.sh) |
| } |