Repository navigation
GC: Suspend Go GC during boot, checkpoint, and restore. - #16735
parth-opensrc wants to merge 1 commit into
Conversation
|
Will squash the commits once approved |
d7d7264 to
d7ae7eb
Compare
konstantin-s-bogom
left a comment
There was a problem hiding this comment.
Can you explain the regressions, like
Restore/vcpus=16/app=bigheap/cpu=unlimited-16 937.0m ± 1% 975.1m ± 1% +4.06% (p=0.000 n=8)
konstantin-s-bogom
left a comment
There was a problem hiding this comment.
Fix the PR description, it still mentions --suspend-lifecycle-gc
9b62a57 to
9d3e651
Compare
7eccf74 to
874db9f
Compare
874db9f to
5068ecb
Compare
There was a problem hiding this comment.
I don't review the code changes, just read benchmark results, one question I have is that, what is the baseline for your benchmark, like which commit?
It never compares against the reference patches. Both linked issues (#16134 and #16152) ask for results that beat a reference patch, but the PR only compares against master. Going by the posted numbers alone, it doesn't clearly beat them:
- Restore at cpu=1: −4.6% here, against −20.7% for the reference.
- Large-heap peak memory: +12% here; the #16152 reference made it go down by 1.6–6.1%.
- Base suite: the reference showed small but significant startup, restore and checkpoint gains; this PR shows none.
The reference capped the heap at about 2× current use; this PR lets it grow to 1 GiB, and on a non-resuming save keeps GC off for another 500 ms.
Meanwhile, there are multiple regression
- Sentry peak memory during checkpoint goes up by about 5% on the small workload and by 75 MiB (+12%) on the large one.
- Idle memory after restore goes up 5%.
- Large-heap restore with no CPU quota is 4% slower.
On the benchmark itself, n=8 may have too much noise, can you run with n=32+ or p<0.01?
We will need more investigation on the PR I believe to figure out whether or not this change is needed.
cc: @EtiennePerot
The original benchmarks were against Added an
|
| if v, err := strconv.ParseUint(metadata[metadataMemoryFileUsedBytesKey], 10 /* base */, 64 /* bitSize */); err == nil { | ||
| savedMemoryFileBytes = v | ||
| } | ||
| return gccontrol.Suspend(totalMemoryLimit(), savedMemoryFileBytes) |
There was a problem hiding this comment.
@parth-opensrc, this uses the limit from sandbox creation. If the user lowers the limit before restore, the kernel enforces the new value but GC still budgets against the old one.
I saved the existing 50,000-file workload under 2 GiB in both cases and restored it with memory.max at 200 MiB. Creating the restore sandbox at 200 MiB gave Go a 99.93 MiB limit and restore succeeded. Creating it at 2 GiB and lowering it with Container.Update before Restore gave Go a 1,023 MiB limit. The restore RPC returned EOF and memory.events recorded one OOM kill, versus zero in the control. The test output and cgroup counters are from the same run.
On the earlier revision, reading the limit when the host sends Restore let both restores finish with a Go limit of about 99 MiB and no OOM kills. Could Sandbox.Restore and Sandbox.Checkpoint pass the current effective cgroup limit with the RPC? The guest /proc checkpoint starts SaveAsync inside the Sentry. When that path has no fresh host limit, it could keep ordinary GC enabled.
Posted by Codex on behalf of @tamird.
There was a problem hiding this comment.
@parth-opensrc, I reran your unchanged TestRestoreCgroupMemoryLimit on a48b7a12c. Both createAtLimit (200 MiB at creation) and lowerBeforeRestore (2 GiB lowered to 200 MiB) passed. In each case memory.events reported oom_kill 0, and the restored process could access /tmpfs. That addresses the resize failure I reported here. Test results.
Posted by Codex on behalf of @tamird.
| defer cont2.Destroy() | ||
|
|
||
| if err := cont2.Restore(conf, imageDir, sandbox.DirectIOOff, false /* background */, nil /* networkArgs */); err != nil { | ||
| events, _ := os.ReadFile(probe.MakePath("memory.events")) |
There was a problem hiding this comment.
@parth-opensrc, on cgroup v2, MakePath takes a controller name and returns the cgroup directory regardless of that argument 1. Both Stat calls here therefore succeed as long as the directory exists, even if memory.swap.max is missing. The failure diagnostic later tries to ReadFile the directory, too, so it drops the OOM counters when restore fails.
Could these use filepath.Join(probe.MakePath(""), "memory.max") (and similarly for memory.swap.max and memory.events)? That makes the optional swap check and the OOM report inspect the intended files. If skipping systems without the memory controller is required, Install can itself fail before these checks.
There is a second reason to read those counters on failure: with the 200 MiB cap applied during fixture setup, the sentry was OOM-killed during Save before this test reached Restore. The same happened with ordinary GC; on this worker the proposed policy declined to suspend anyway. Giving only the checkpoint writer 2 GiB let the restore assertion run against a real 200 MiB cap.
Posted by Codex on behalf of @tamird.
| if totalMem == 0 { | ||
| totalMem = gccontrol.NoMemoryLimit | ||
| } | ||
| s := gccontrol.Suspend(totalMem, 0 /* untrackedMem */) |
There was a problem hiding this comment.
@parth-opensrc, b.totalMem can be larger than the cgroup limit Linux enforces. On the earlier revision I set a parent’s memory.max to 512 MiB and its child’s to 2 GiB. The cgroup reader returned 2 GiB, and Suspend set Go’s soft memory limit to 1 GiB. It did the same with two unlimited levels below the 512 MiB parent. A 256 MiB child correctly got a 128 MiB Go limit.
Could we land #16767 before relying on this value to suspend GC? It fixes the shared cgroup reader. Taking the smallest visible limit gave the first two cases a 256 MiB Go limit and left the control unchanged. Results from a real cgroup-v2 hierarchy. These measure the limit passed to Go; no workload was driven to OOM.
Posted by Codex on behalf of @tamird.
5068ecb to
a48b7a1
Compare
[🤖] Invalidating approval due to rebase as a means to notify @kerumeto to re-review. Current diff looks different from pre-rebase diff.
|
[🤖] Invalidating approval due to rebase as a means to notify @kerumeto to re-review. Current diff looks different from pre-rebase diff. |
|
@parth-opensrc, I reran the 100,000-file tmpfs checkpoint on c31b2ad and its parent 706b124. The earlier 30.12% increase in peak Sentry RSS was on a48b7a1. On this revision, peak RSS was 1.33% higher than on its parent, and save took 3.98% longer. The run used the graph engine without compression, native AMD64 systrap, four CPUs and a 2 GiB limit. Both revisions restored all 100,000 files from every checkpoint, including the warmups. The time rows measure return from checkpoint and exit of the saving Sentry. The RSS row measures the peak sampled through exit. Measurements and restore results · Full benchstat Earlier revisionsI tried a non-resuming checkpoint with the graph state engine, now the default on master. On 100,000 empty tmpfs files, the PR took longer to save and used more memory than its parent. I used systrap on Linux/amd64, four CPUs, no sandbox CPU quota, a 2 GiB memory limit, and uncompressed checkpoints. Each column has 12 measured saves after one warmup, in balanced order. The columns are the parent ( The first two rows are time to checkpoint return and to Sentry exit ( Which state engine and compression setting did your C4 Posted by Codex on behalf of @tamird. |
kerumeto
left a comment
There was a problem hiding this comment.
[🤖🐸🤖] 5 issues found:
- [major · bug] Guest-triggered checkpoint suspends GC with stale boot memory limit, causing cgroup OOM kill (
runsc/boot/restore.go:173, inline) - [major · bug] Subcontainer restore via
StartSubcontainerdropsMemoryLimitand retains stale cgroup limit (runsc/sandbox/sandbox.go:539, details below) - [major · bug] GC budget ignores ancestor cgroup limits; restore is OOM-killed (
runsc/sandbox/sandbox.go:608, inline) - [minor · bug] Loader.run evaluates gccontrol.Suspend before ending the boot startupGC handle (
runsc/boot/loader.go:1479, inline) - [minor · bug] Loader.saveWithOpts does not end l.startupGC before checkpoint save (
runsc/boot/restore.go:891, details below)
runsc/sandbox/sandbox.go:539
[🤖🐸🤖] [major · bug] Subcontainer restore via StartSubcontainer drops MemoryLimit and retains stale cgroup limit
In multi-container pod restore, the root container runs Restore while subcontainers commonly run Start (Sandbox.StartSubcontainer), which the Sentry translates to RestoreSubcontainer while in restoringUnstarted state. Sandbox.StartSubcontainer omits MemoryLimit: s.effectiveMemoryLimit(), sending 0, and restorer.restoreContainerInfo ignores memoryLimit == 0 (if memoryLimit > 0). As a result, if Container.Update lowers the pod cgroup memory.max between rootCont.Restore and subCont.Start, restore suspends Go GC with the stale root limit and triggers a host cgroup OOM kill. Ignoring 0 also prevents RestoreSubcontainer from falling back to ordinary GC when effectiveMemoryLimit() returns 0 (unlimited or read error).
Suggested fix: Set MemoryLimit: s.effectiveMemoryLimit() in Sandbox.StartSubcontainer (runsc/sandbox/sandbox.go:547) and assign r.memoryLimit = memoryLimit unconditionally in restorer.restoreContainerInfo (runsc/boot/restore.go:345-347).
Details (evidence, reproduction and test code)
Evidence: containerManager.StartSubcontainer (runsc/boot/controller.go:217-221) delegates to cm.RestoreSubcontainer(args, nil) when state == restoringUnstarted (a path this PR updated at runsc/boot/controller.go:703-705 to guard reply != nil). While Sandbox.RestoreSubcontainer sets MemoryLimit: s.effectiveMemoryLimit() (runsc/sandbox/sandbox.go:862), Sandbox.StartSubcontainer (runsc/sandbox/sandbox.go:539-548) leaves args.MemoryLimit == 0. restorer.restoreContainerInfo (runsc/boot/restore.go:345-347) then guards if memoryLimit > 0 { r.memoryLimit = memoryLimit }, keeping r.memoryLimit from rootCont.Restore (2 GiB -> GOMEMLIMIT = 1 GiB) even after rootCont.Update lowered memory.max to 200 MiB, or when a later effectiveMemoryLimit() call returns 0 (runsc/sandbox/sandbox.go:609-610).
Reproduced with a test (runsc/container/container_save_restore_test.go): bazel test //runsc/container:container_test --test_filter=TestSubcontainerRestoreCgroupMemoryLimit --strategy=TestRunner=local --test_sharding_strategy=disabled --test_timeout=60 --nocache_test_results → TestSubcontainerRestoreCgroupMemoryLimit checkpoints a 2-container sandbox under a 2 GiB cgroup limit, calls rootCont.Restore, lowers memory.max to 200 MiB via rootCont.Update, and restores the second container via subCont.Start. It fails on PR head with oom_kill 1, and passes (oom_kill 0) with the suggested fix.
Test code:
diff --git a/runsc/container/container_save_restore_test.go b/runsc/container/container_save_restore_test.go
index 040c7dafa..b67247253 100644
--- a/runsc/container/container_save_restore_test.go
+++ b/runsc/container/container_save_restore_test.go
@@ -3033,3 +3033,364 @@ func TestRestoreCgroupMemoryLimit(t *testing.T) {
})
}
}
+
+func probeWritableMemoryCgroupV2(t *testing.T) (newCgPath func(string) string, makeMemRes func(int64) *specs.LinuxMemory) {
+ t.Helper()
+ if sync.RaceEnabled {
+ t.Skip("Skipping test when running with race detector (gotsan)")
+ }
+ if os.Getpagesize() > 4096 {
+ t.Skip("4K page size required for 200 MiB cgroup RSS budget")
+ }
+ if !cgroup.IsOnlyV2() {
+ t.Skip("cgroup v2 required")
+ }
+
+ parentCg := "/"
+ if selfCg, err := os.ReadFile("/proc/self/cgroup"); err == nil {
+ for line := range strings.SplitSeq(strings.TrimSpace(string(selfCg)), "\n") {
+ if rel, ok := strings.CutPrefix(line, "0::"); ok {
+ parentCg = filepath.Dir(filepath.Clean("/" + rel))
+ break
+ }
+ }
+ }
+ newCgPath = func(prefix string) string {
+ return filepath.Join(parentCg, testutil.RandomID(prefix))
+ }
+
+ cgPath := newCgPath("gvisor-test-cg-probe")
+ probe, err := cgroup.NewFromPath(cgPath, false /* useSystemd */)
+ if err != nil {
+ t.Skipf("cgroup v2 unavailable: %v", err)
+ }
+ if err := probe.Install(&specs.LinuxResources{}); err != nil {
+ if errors.Is(err, os.ErrPermission) || errors.Is(err, unix.EROFS) || errors.Is(err, unix.EBUSY) {
+ t.Skipf("writable cgroup v2 hierarchy unavailable: %v", err)
+ }
+ t.Fatalf("probe.Install(): %v", err)
+ }
+ probeInstalled := true
+ defer func() {
+ if probeInstalled {
+ _ = probe.Uninstall()
+ }
+ }()
+ if _, err := os.Stat(filepath.Join(probe.MakePath(""), "memory.max")); err != nil {
+ if os.IsNotExist(err) {
+ t.Skip("cgroup v2 memory controller unavailable")
+ }
+ t.Fatalf("Stat(memory.max): %v", err)
+ }
+ _, swapErr := os.Stat(filepath.Join(probe.MakePath(""), "memory.swap.max"))
+ probeInstalled = false
+ if err := probe.Uninstall(); err != nil {
+ t.Fatalf("probe.Uninstall(): %v", err)
+ }
+
+ makeMemRes = func(limit int64) *specs.LinuxMemory {
+ res := &specs.LinuxMemory{Limit: &limit}
+ if swapErr == nil {
+ res.Swap = &limit
+ }
+ return res
+ }
+ return newCgPath, makeMemRes
+}
+
+func requireNoOOMKill(t *testing.T, eventsPath string) {
+ t.Helper()
+ events, err := os.ReadFile(eventsPath)
+ if err != nil {
+ t.Fatalf("ReadFile(%q): %v", eventsPath, err)
+ }
+ for line := range strings.SplitSeq(string(events), "\n") {
+ if line == "oom_kill 0" {
+ return
+ }
+ }
+ t.Fatalf("unexpected OOM kill in memory.events:\n%s", events)
+}
+
+// TestGuestCheckpointCgroupMemoryLimit verifies that a guest-triggered
+// checkpoint via /proc/gvisor/checkpoint does not cause a host cgroup OOM kill
+// after Container.Update lowers the sandbox memory cgroup limit below the
+// boot-time limit.
+func TestGuestCheckpointCgroupMemoryLimit(t *testing.T) {
+ newCgPath, makeMemRes := probeWritableMemoryCgroupV2(t)
+ testAppPath, err := testutil.FindFile("test/cmd/test_app/test_app")
+ if err != nil {
+ t.Fatalf("FindFile(test_app): %v", err)
+ }
+
+ const (
+ initialMemLimit = int64(2 << 30)
+ checkpointMemLimit = int64(400 << 20)
+ )
+
+ imageDir := makeTempDir(t, "guest-ckpt-img")
+ ctrlDir := makeTempDir(t, "guest-ckpt-ctrl")
+ triggerFile := filepath.Join(ctrlDir, "trigger")
+ doneFile := filepath.Join(ctrlDir, "done")
+
+ script := fmt.Sprintf(
+ "mkdir -p /tmpfs/live /tmpfs/tmp && while [ ! -f %q ]; do sleep 0.05; done; exec 3<>/proc/gvisor/checkpoint; echo 1 >&3; cat <&3 > %q; sleep 1000",
+ triggerFile, doneFile,
+ )
+ spec := testutil.NewSpecWithArgs("/bin/sh", "-c", script)
+ conf := testutil.TestConfig(t)
+ conf.Overlay2.Set("none")
+ conf.Strace = false
+ spec.Mounts = []specs.Mount{
+ {Type: "tmpfs", Destination: "/tmpfs"},
+ {Type: "bind", Source: ctrlDir, Destination: ctrlDir},
+ }
... (249 more lines in the full patch)runsc/boot/restore.go:891
[🤖🐸🤖] [minor · bug] Loader.saveWithOpts does not end l.startupGC before checkpoint save
Unlike containerManager.Restore, Loader.saveWithOpts does not end l.startupGC before calling state.SaveWithOpts. If a checkpoint save runs while the startup or post-restore startupGC handle is still open (before the 250ms idle release or 500ms fallback timer expires), state.Save's gccontrol.Suspend shares l.startupGC's session:
- On a resuming (
Resume: true) or failed save,finishSaveGCSuspensioncallsgcSuspension.End(), butl.startupGC's open reference keeps GC disabled (GCPercent = -1) aftersaveWithOptsreturns. - When
saveOpts.MemoryLimit == 0(unknown bound),Suspend(0, ...)returnsnilwithout ending the active session, leaving GC disabled underl.startupGC's limit during save. - If
l.startupGCresumed early (stateResumed),Suspenddoes not re-suspend GC for the save even when sufficient headroom exists.
Suggested fix: End l.startupGC at the start of Loader.saveWithOpts:
l.saveMu.Lock()
defer l.saveMu.Unlock()
l.startupGC.Swap(nil).End()Details (evidence, reproduction and test code)
Evidence: Loader.saveWithOpts (runsc/boot/restore.go:891-949) calls state.SaveWithOpts without calling l.startupGC.Swap(nil).End() (unlike containerManager.Restore at runsc/boot/controller.go:381). In pkg/sentry/state/state.go:181-184, SaveOpts.Save calls gcSuspension := gccontrol.Suspend(opts.MemoryLimit, memoryFileBytes) and defers finishSaveGCSuspension(gcSuspension, opts.Resume, err). When l.startupGC is still open (current.refs == 1), Suspend increments current.refs to 2 (or hits stateResumed / totalMem == 0), so gcSuspension.End() only decrements current.refs from 2 to 1 instead of calling resumeGCLocked().
Reproduced with a test (runsc/boot/BUILD, runsc/boot/loader_test.go): bazel test //runsc/boot:boot_test --test_filter=TestStartupGC/resumesStartupGCOnSave --nocache_test_results → Fails at PR head with GCPercent after saveWithOpts = -1, want >= 0; passes when l.startupGC.Swap(nil).End() is called in Loader.saveWithOpts.
Test code:
diff --git a/runsc/boot/BUILD b/runsc/boot/BUILD
index 5cac89345..b89aa7420 100644
--- a/runsc/boot/BUILD
+++ b/runsc/boot/BUILD
@@ -201,9 +201,11 @@ go_test(
"//pkg/log",
"//pkg/seccomp",
"//pkg/sentry/checkpoint",
+ "//pkg/sentry/control/controlapi",
"//pkg/sentry/fscheckpoint",
"//pkg/sentry/kernel",
"//pkg/sentry/kernel/auth",
+ "//pkg/sentry/state",
"//pkg/sentry/vfs",
"//pkg/sync",
"//pkg/unet",
diff --git a/runsc/boot/loader_test.go b/runsc/boot/loader_test.go
index 785b77d91..820d19de0 100644
--- a/runsc/boot/loader_test.go
+++ b/runsc/boot/loader_test.go
@@ -16,6 +16,7 @@ package boot
import (
"fmt"
+ "io"
"math"
"math/rand"
"net"
@@ -37,8 +38,10 @@ import (
"gvisor.dev/gvisor/pkg/gccontrol"
"gvisor.dev/gvisor/pkg/lisafs"
"gvisor.dev/gvisor/pkg/log"
+ "gvisor.dev/gvisor/pkg/sentry/control/controlapi"
"gvisor.dev/gvisor/pkg/sentry/kernel"
"gvisor.dev/gvisor/pkg/sentry/kernel/auth"
+ "gvisor.dev/gvisor/pkg/sentry/state"
"gvisor.dev/gvisor/pkg/sentry/vfs"
"gvisor.dev/gvisor/pkg/sync"
"gvisor.dev/gvisor/pkg/unet"
@@ -520,6 +523,46 @@ func TestStartupGC(t *testing.T) {
t.Fatalf("GCPercent after restore run = %d, want >= 0", got)
}
})
+
+ t.Run("suspendsOnStartAfterEarlyBootResume", func(t *testing.T) {
+ l, _ := newSuspendedLoader(t)
+ // Simulate GC running during boot.New before StartRoot arrives, which
+ // transitions the boot suspension session to stateResumed.
+ runtime.GC()
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) {
+ if gcPercent() != gcDisabled {
+ break
+ }
+ time.Sleep(time.Millisecond)
+ }
+ if got := gcPercent(); got == gcDisabled {
+ t.Fatal("GC remained disabled after forced collection during boot")
+ }
+ if err := l.run(); err != nil {
+ t.Fatalf("l.run() in state=created: %v", err)
+ }
+ got := gcPercent()
+ l.WaitExit()
+ if got >= 0 {
+ t.Fatalf("GCPercent after l.run() = %d, want < 0", got)
+ }
+ })
+
+ t.Run("resumesStartupGCOnSave", func(t *testing.T) {
+ l, _ := newSuspendedLoader(t)
+ pr, pw := io.Pipe()
+ pr.Close()
+ defer pw.Close()
+ _ = l.saveWithOpts(&state.SaveOpts{
+ Destination: pw,
+ Resume: true,
+ MemoryLimit: gccontrol.NoMemoryLimit,
+ }, &controlapi.SaveRestoreExecOpts{})
+ if got := gcPercent(); got < 0 {
+ t.Fatalf("GCPercent after saveWithOpts = %d, want >= 0", got)
+ }
+ })
}
// Test that network=host with raw sockets enabled requires CAP_NET_RAW on theAutomated review agent. Please address valid findings before human review, or close them with a reason.
| Resume: specutils.AnnotationToBool(spec, annotationCheckpointResume), | ||
| CudaCheckpointSequential: specutils.AnnotationToBool(spec, annotationCheckpointCudaCheckpointSequential), | ||
| MemoryLimit: configuredMemoryLimit(), | ||
| } |
There was a problem hiding this comment.
[🤖🐸🤖] [major · bug] Guest-triggered checkpoint suspends GC with stale boot memory limit, causing cgroup OOM kill
When a checkpoint is triggered from inside the sandbox via /proc/gvisor/checkpoint, saveOptsFromSpec sets SaveOpts.MemoryLimit to configuredMemoryLimit(), which reads the static --total-memory flag passed at sandbox boot (previously raised by @tamird). Because the chrooted Sentry process cannot observe host cgroup reductions later applied via Container.Update, a guest-triggered checkpoint after lowering memory.max suspends Go GC (GOGC = -1) under a stale soft memory limit (GOMEMLIMIT = initialLimit / 2). Uncollected heap garbage and transient state.Save allocations then accumulate without triggering GC until the host kernel OOM-kills the Sentry.
Suggested fix: Remove MemoryLimit: configuredMemoryLimit() from saveOptsFromSpec (runsc/boot/restore.go:182) so SaveOpts.MemoryLimit remains 0 and ordinary Go GC stays active on the Loader.SaveAsync path.
Details (evidence, reproduction and test code)
Evidence: Loader.SaveAsync() (runsc/boot/restore.go:134-147) builds controlapi.SaveOpts via saveOptsFromSpec, which sets MemoryLimit: configuredMemoryLimit() (runsc/boot/restore.go:182), reading totalMemoryFlag (runsc/boot/restore.go:412-417). Loader.save (runsc/boot/loader.go:1710-1718) passes o.MemoryLimit to state.SaveOpts.SuspendGCMemoryLimit, calling gccontrol.Default.Suspend(opts.MemoryLimit/2, 0) (pkg/sentry/state/state.go:97-100). Meanwhile, Container.Update (runsc/container/container.go:733-764) lowers host cgroup memory.max in place without updating totalMemoryFlag. Prior to this PR, SaveAsync kept GOGC = 100 active and reclaimed unreachable heap allocations before exceeding the lowered cgroup limit.
Reproduced with a test (runsc/container/container_save_restore_test.go): bazel test //runsc/container:container_test --test_filter=TestGuestCheckpointCgroupMemoryLimit --strategy=TestRunner=local --test_sharding_strategy=disabled --test_timeout=60 --nocache_test_results → TestGuestCheckpointCgroupMemoryLimit boots under a 2 GiB cgroup limit, creates live and unlinked tmpfs files, lowers memory.max to 400 MiB via Container.Update, and triggers /proc/gvisor/checkpoint. It fails on PR head with a host cgroup OOM kill (oom_kill 1), and passes (oom_kill 0) both at the merge-base and with MemoryLimit omitted in saveOptsFromSpec.
Test code:
diff --git a/runsc/container/container_save_restore_test.go b/runsc/container/container_save_restore_test.go
index 040c7dafa..b67247253 100644
--- a/runsc/container/container_save_restore_test.go
+++ b/runsc/container/container_save_restore_test.go
@@ -3033,3 +3033,364 @@ func TestRestoreCgroupMemoryLimit(t *testing.T) {
})
}
}
+
+func probeWritableMemoryCgroupV2(t *testing.T) (newCgPath func(string) string, makeMemRes func(int64) *specs.LinuxMemory) {
+ t.Helper()
+ if sync.RaceEnabled {
+ t.Skip("Skipping test when running with race detector (gotsan)")
+ }
+ if os.Getpagesize() > 4096 {
+ t.Skip("4K page size required for 200 MiB cgroup RSS budget")
+ }
+ if !cgroup.IsOnlyV2() {
+ t.Skip("cgroup v2 required")
+ }
+
+ parentCg := "/"
+ if selfCg, err := os.ReadFile("/proc/self/cgroup"); err == nil {
+ for line := range strings.SplitSeq(strings.TrimSpace(string(selfCg)), "\n") {
+ if rel, ok := strings.CutPrefix(line, "0::"); ok {
+ parentCg = filepath.Dir(filepath.Clean("/" + rel))
+ break
+ }
+ }
+ }
+ newCgPath = func(prefix string) string {
+ return filepath.Join(parentCg, testutil.RandomID(prefix))
+ }
+
+ cgPath := newCgPath("gvisor-test-cg-probe")
+ probe, err := cgroup.NewFromPath(cgPath, false /* useSystemd */)
+ if err != nil {
+ t.Skipf("cgroup v2 unavailable: %v", err)
+ }
+ if err := probe.Install(&specs.LinuxResources{}); err != nil {
+ if errors.Is(err, os.ErrPermission) || errors.Is(err, unix.EROFS) || errors.Is(err, unix.EBUSY) {
+ t.Skipf("writable cgroup v2 hierarchy unavailable: %v", err)
+ }
+ t.Fatalf("probe.Install(): %v", err)
+ }
+ probeInstalled := true
+ defer func() {
+ if probeInstalled {
+ _ = probe.Uninstall()
+ }
+ }()
+ if _, err := os.Stat(filepath.Join(probe.MakePath(""), "memory.max")); err != nil {
+ if os.IsNotExist(err) {
+ t.Skip("cgroup v2 memory controller unavailable")
+ }
+ t.Fatalf("Stat(memory.max): %v", err)
+ }
+ _, swapErr := os.Stat(filepath.Join(probe.MakePath(""), "memory.swap.max"))
+ probeInstalled = false
+ if err := probe.Uninstall(); err != nil {
+ t.Fatalf("probe.Uninstall(): %v", err)
+ }
+
+ makeMemRes = func(limit int64) *specs.LinuxMemory {
+ res := &specs.LinuxMemory{Limit: &limit}
+ if swapErr == nil {
+ res.Swap = &limit
+ }
+ return res
+ }
+ return newCgPath, makeMemRes
+}
+
+func requireNoOOMKill(t *testing.T, eventsPath string) {
+ t.Helper()
+ events, err := os.ReadFile(eventsPath)
+ if err != nil {
+ t.Fatalf("ReadFile(%q): %v", eventsPath, err)
+ }
+ for line := range strings.SplitSeq(string(events), "\n") {
+ if line == "oom_kill 0" {
+ return
+ }
+ }
+ t.Fatalf("unexpected OOM kill in memory.events:\n%s", events)
+}
+
+// TestGuestCheckpointCgroupMemoryLimit verifies that a guest-triggered
+// checkpoint via /proc/gvisor/checkpoint does not cause a host cgroup OOM kill
+// after Container.Update lowers the sandbox memory cgroup limit below the
+// boot-time limit.
+func TestGuestCheckpointCgroupMemoryLimit(t *testing.T) {
+ newCgPath, makeMemRes := probeWritableMemoryCgroupV2(t)
+ testAppPath, err := testutil.FindFile("test/cmd/test_app/test_app")
+ if err != nil {
+ t.Fatalf("FindFile(test_app): %v", err)
+ }
+
+ const (
+ initialMemLimit = int64(2 << 30)
+ checkpointMemLimit = int64(400 << 20)
+ )
+
+ imageDir := makeTempDir(t, "guest-ckpt-img")
+ ctrlDir := makeTempDir(t, "guest-ckpt-ctrl")
+ triggerFile := filepath.Join(ctrlDir, "trigger")
+ doneFile := filepath.Join(ctrlDir, "done")
+
+ script := fmt.Sprintf(
+ "mkdir -p /tmpfs/live /tmpfs/tmp && while [ ! -f %q ]; do sleep 0.05; done; exec 3<>/proc/gvisor/checkpoint; echo 1 >&3; cat <&3 > %q; sleep 1000",
+ triggerFile, doneFile,
+ )
+ spec := testutil.NewSpecWithArgs("/bin/sh", "-c", script)
+ conf := testutil.TestConfig(t)
+ conf.Overlay2.Set("none")
+ conf.Strace = false
+ spec.Mounts = []specs.Mount{
+ {Type: "tmpfs", Destination: "/tmpfs"},
+ {Type: "bind", Source: ctrlDir, Destination: ctrlDir},
+ }
... (249 more lines in the full patch)Automated review agent. Please address valid findings before human review, or close them with a reason.
| // effectiveMemoryLimit reads the current host and cgroup memory bound because | ||
| // container updates can change the cgroup limit after sandbox creation. Returns | ||
| // zero if the bound cannot be read so ordinary GC remains enabled. | ||
| func (s *Sandbox) effectiveMemoryLimit() uint64 { | ||
| host, err := hostos.TotalSystemMemory() | ||
| if err != nil { | ||
| log.Warningf("Reading host memory limit: %v", err) | ||
| return 0 | ||
| } | ||
| if s.CgroupJSON.Cgroup == nil { | ||
| return host | ||
| } | ||
| limit, err := s.CgroupJSON.Cgroup.MemoryLimit() | ||
| if err != nil { | ||
| log.Warningf("Reading cgroup memory limit: %v", err) | ||
| return 0 | ||
| } | ||
| return min(host, limit) | ||
| } |
There was a problem hiding this comment.
[🤖🐸🤖] [major · bug] GC budget ignores ancestor cgroup limits; restore is OOM-killed
Suspension budgets come from Cgroup.MemoryLimit() (here, and via --total-memory for boot). That reader only checks the sandbox cgroup and its direct parent. If the real limit is set two or more levels up, or a child has a larger limit than its parent, Suspend falls back to host memory and allows a 1 GiB Go heap with GC off. A restore under such a limit is OOM-killed by the kernel, but the same restore succeeds at the merge-base. Previously raised by @tamird; still present at the PR head.
Suggested fix: Do not size the GC suspension from a limit that may be too large. Make cgroupV2.MemoryLimit() return the smallest memory.max from the sandbox cgroup up to the cgroup root (as #16767 does), and land that before this PR. Alternatively, read /proc/self/cgroup in the Sentry and walk the ancestors there. Verified: an all-ancestors MemoryLimit() makes the reproducer pass and keeps TestRestoreCgroupMemoryLimit green.
Details (evidence, reproduction and test code)
Evidence: Setup: an ancestor cgroup with memory.max=200 MiB and memory.swap.max=0. The sandbox cgroup is ancestor/mid/leaf with no limits of its own. The checkpoint is the same 50,000-file tmpfs image that TestRestoreCgroupMemoryLimit uses.
cgroupV2.MemoryLimit()(runsc/cgroup/cgroup_v2.go:413) checks onlyleafandmid, bothmax, and returnsMaxUint64.effectiveMemoryLimit()then returns host RAM, and the restore sandbox boots with--total-memory 135161987072.gccontrol.Suspendtherefore sets a 1 GiB soft limit for both the boot and the restore suspension.- PR head:
containerManager.Restore failed: EOF: the sandbox exited before the container started. The ancestormemory.eventsshowsoom_kill 1, andmemory.peakis 209715200 (the limit). - Merge-base: the restore succeeds with
oom_kill 0andmemory.peak140980224 (about 134 MiB). - PR head plus an experimental reader fix that takes the minimum
memory.maxover all ancestors:MemoryLimit()returns 209715200, the restore succeeds withoom_kill 0and peak about 139 MiB, andTestRestoreCgroupMemoryLimitstill passes.
The same budget source feeds Sandbox.Checkpoint, so saves under such hierarchies can hit the same problem.
Reproduced with a test (runsc/container/container_save_restore_test.go): 'bazel test //runsc/container:container_test --test_filter=TestRestoreParentCgroupMemoryLimit --test_sharding_strategy=disabled --nocache_test_results --strategy=TestRunner=local --test_arg=-test.v --test_output=errors > /tmp/head-out.txt 2>&1; rc=$?; ...; exit $rc' (same command with --slot base on the merge-base) → Fails on the PR head: the restore is OOM-killed by the 200 MiB ancestor limit. Passes at the merge-base and with an all-ancestors cgroup reader fix applied.
Test code:
diff --git a/runsc/container/container_save_restore_test.go b/runsc/container/container_save_restore_test.go
index 040c7dafa..e7d9f7139 100644
--- a/runsc/container/container_save_restore_test.go
+++ b/runsc/container/container_save_restore_test.go
@@ -3033,3 +3033,175 @@ func TestRestoreCgroupMemoryLimit(t *testing.T) {
})
}
}
+
+// TestRestoreParentCgroupMemoryLimit restores a checkpoint with a large Sentry
+// Go heap into a sandbox cgroup that has no memory limit of its own, nested
+// two levels below an ancestor cgroup limited to 200 MiB. The restore must not
+// be OOM-killed by the ancestor limit.
+func TestRestoreParentCgroupMemoryLimit(t *testing.T) {
+ if sync.RaceEnabled {
+ t.Skip("Skipping test when running with race detector (gotsan)")
+ }
+ if os.Getpagesize() > 4096 {
+ t.Skip("4K page size required for 200 MiB cgroup RSS budget")
+ }
+ if !cgroup.IsOnlyV2() {
+ t.Skip("cgroup v2 required")
+ }
+ testAppPath, err := testutil.FindFile("test/cmd/test_app/test_app")
+ if err != nil {
+ t.Fatalf("FindFile(test_app): %v", err)
+ }
+
+ parentCg := "/"
+ if selfCg, err := os.ReadFile("/proc/self/cgroup"); err == nil {
+ for line := range strings.SplitSeq(strings.TrimSpace(string(selfCg)), "\n") {
+ if rel, ok := strings.CutPrefix(line, "0::"); ok {
+ parentCg = filepath.Dir(filepath.Clean("/" + rel))
+ break
+ }
+ }
+ }
+ newCgPath := func(prefix string) string {
+ return filepath.Join(parentCg, testutil.RandomID(prefix))
+ }
+
+ const (
+ saveMemLimit = int64(2 << 30)
+ restoreMemLimit = int64(200 << 20)
+ )
+
+ // Checkpoint with ample memory, same as TestRestoreCgroupMemoryLimit.
+ spec, conf := sleepSpecConf(t)
+ conf.Overlay2.Set("none")
+ conf.Strace = false
+ spec.Mounts = []specs.Mount{{Type: "tmpfs", Destination: "/tmpfs"}}
+ saveLimit := saveMemLimit
+ spec.Linux = &specs.Linux{
+ CgroupsPath: newCgPath("gvisor-test-cg"),
+ Resources: &specs.LinuxResources{Memory: &specs.LinuxMemory{Limit: &saveLimit}},
+ }
+ _, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)
+ if err != nil {
+ t.Fatalf("SetupContainer: %v", err)
+ }
+ defer cleanup()
+ cont, err := New(conf, Args{ID: testutil.RandomContainerID(), Spec: spec, BundleDir: bundleDir})
+ if err != nil {
+ t.Fatalf("creating container: %v", err)
+ }
+ defer func() {
+ if cont != nil {
+ _ = cont.Destroy()
+ }
+ }()
+ if err := cont.Start(conf); err != nil {
+ t.Fatalf("starting container: %v", err)
+ }
+ if err := waitForProcessCount(cont, 1); err != nil {
+ t.Fatalf("waiting for init process: %v", err)
+ }
+ execFile, err := os.Open(testAppPath)
+ if err != nil {
+ t.Fatalf("Open(%q): %v", testAppPath, err)
+ }
+ ws, err := cont.executeSync(conf, &controlapi.ExecArgs{
+ Argv: []string{"test_app", "fsTreeCreate", "--target-dir=/tmpfs", "--depth=50", "--file-per-level=1000", "--file-size=0"},
+ FilePayload: controlapi.NewFilePayload(map[int]*os.File{
+ 0: os.Stdin, 1: os.Stdout, 2: os.Stderr,
+ }, execFile),
+ })
+ execFile.Close()
+ if err != nil || !ws.Exited() || ws.ExitStatus() != 0 {
+ t.Fatalf("fsTreeCreate failed: ws=%v, err=%v", ws, err)
+ }
+ imageDir := t.TempDir()
+ if err := os.Chmod(imageDir, 0777); err != nil {
+ t.Fatalf("Chmod(%q): %v", imageDir, err)
+ }
+ if err := cont.Checkpoint(conf, imageDir, sandbox.CheckpointOpts{
+ Compression: statefile.CompressionLevelFlateBestSpeed,
+ }); err != nil {
+ t.Fatalf("checkpointing container: %v", err)
+ }
+ if _, err := cont.Wait(); err != nil {
+ t.Fatalf("waiting after checkpoint: %v", err)
+ }
+ if err := cont.Destroy(); err != nil {
+ t.Fatalf("destroying checkpointed container: %v", err)
+ }
+ cont = nil
+
+ // Ancestor cgroup with a 200 MiB limit. The sandbox cgroup is created two
+ // levels below it with no memory limit of its own.
+ ancestorRel := newCgPath("gvisor-test-cg-ancestor")
+ ancestor := filepath.Join("/sys/fs/cgroup", ancestorRel)
+ if err := os.Mkdir(ancestor, 0755); err != nil {
+ t.Skipf("cannot create ancestor cgroup: %v", err)
+ }
+ defer func() {
+ // Children are removed by the sandbox teardown.
+ for i := 0; i < 50; i++ {
+ if err := os.Remove(ancestor); err == nil || os.IsNotExist(err) {
+ return
+ }
... (60 more lines in the full patch)Automated review agent. Please address valid findings before human review, or close them with a reason.
|
|
||
| switch l.state { | ||
| case created: | ||
| l.setStartupGC(gccontrol.Suspend(configuredMemoryLimit(), 0 /* untrackedMem */)) |
There was a problem hiding this comment.
[🤖🐸🤖] [minor · bug] Loader.run evaluates gccontrol.Suspend before ending the boot startupGC handle
In Loader.run (case created:), l.setStartupGC(gccontrol.Suspend(configuredMemoryLimit(), 0)) evaluates gccontrol.Suspend before l.setStartupGC ends the boot StartupGC handle stored in l.startupGC. If a garbage collection occurred during boot.New (transitioning the boot session to stateResumed), gccontrol.Suspend attaches to the already-resumed session instead of starting a new GC suspension for container startup, even when ample memory headroom is available after the boot GC cycle.
Suggested fix: End the boot startupGC handle before calling gccontrol.Suspend in Loader.run:
case created:
l.startupGC.Swap(nil).End()
l.setStartupGC(gccontrol.Suspend(configuredMemoryLimit(), 0 /* untrackedMem */))Details (evidence, reproduction and test code)
Evidence: boot.New (runsc/boot/loader.go:1060) stores args.StartupGC in l.startupGC. At runsc/boot/loader.go:1479, l.setStartupGC(gccontrol.Suspend(configuredMemoryLimit(), 0)) evaluates gccontrol.Suspend before entering l.setStartupGC (runsc/boot/loader.go:1429-1434), which calls l.startupGC.Swap(gc).End(). When args.StartupGC is in stateResumed, gccontrol.Suspend (pkg/gccontrol/gccontrol.go:210) increments current.refs without calling startSuspensionLocked, leaving GCPercent enabled for the entire Loader.run startup phase.
Reproduced with a test (runsc/boot/BUILD, runsc/boot/loader_test.go): bazel test //runsc/boot:boot_test --test_filter=TestStartupGC/suspendsOnStartAfterEarlyBootResume --nocache_test_results → Fails at PR head with GCPercent after l.run() = 100, want < 0; passes when l.startupGC.Swap(nil).End() is called before gccontrol.Suspend.
Test code:
diff --git a/runsc/boot/BUILD b/runsc/boot/BUILD
index 5cac89345..b89aa7420 100644
--- a/runsc/boot/BUILD
+++ b/runsc/boot/BUILD
@@ -201,9 +201,11 @@ go_test(
"//pkg/log",
"//pkg/seccomp",
"//pkg/sentry/checkpoint",
+ "//pkg/sentry/control/controlapi",
"//pkg/sentry/fscheckpoint",
"//pkg/sentry/kernel",
"//pkg/sentry/kernel/auth",
+ "//pkg/sentry/state",
"//pkg/sentry/vfs",
"//pkg/sync",
"//pkg/unet",
diff --git a/runsc/boot/loader_test.go b/runsc/boot/loader_test.go
index 785b77d91..820d19de0 100644
--- a/runsc/boot/loader_test.go
+++ b/runsc/boot/loader_test.go
@@ -16,6 +16,7 @@ package boot
import (
"fmt"
+ "io"
"math"
"math/rand"
"net"
@@ -37,8 +38,10 @@ import (
"gvisor.dev/gvisor/pkg/gccontrol"
"gvisor.dev/gvisor/pkg/lisafs"
"gvisor.dev/gvisor/pkg/log"
+ "gvisor.dev/gvisor/pkg/sentry/control/controlapi"
"gvisor.dev/gvisor/pkg/sentry/kernel"
"gvisor.dev/gvisor/pkg/sentry/kernel/auth"
+ "gvisor.dev/gvisor/pkg/sentry/state"
"gvisor.dev/gvisor/pkg/sentry/vfs"
"gvisor.dev/gvisor/pkg/sync"
"gvisor.dev/gvisor/pkg/unet"
@@ -520,6 +523,46 @@ func TestStartupGC(t *testing.T) {
t.Fatalf("GCPercent after restore run = %d, want >= 0", got)
}
})
+
+ t.Run("suspendsOnStartAfterEarlyBootResume", func(t *testing.T) {
+ l, _ := newSuspendedLoader(t)
+ // Simulate GC running during boot.New before StartRoot arrives, which
+ // transitions the boot suspension session to stateResumed.
+ runtime.GC()
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) {
+ if gcPercent() != gcDisabled {
+ break
+ }
+ time.Sleep(time.Millisecond)
+ }
+ if got := gcPercent(); got == gcDisabled {
+ t.Fatal("GC remained disabled after forced collection during boot")
+ }
+ if err := l.run(); err != nil {
+ t.Fatalf("l.run() in state=created: %v", err)
+ }
+ got := gcPercent()
+ l.WaitExit()
+ if got >= 0 {
+ t.Fatalf("GCPercent after l.run() = %d, want < 0", got)
+ }
+ })
+
+ t.Run("resumesStartupGCOnSave", func(t *testing.T) {
+ l, _ := newSuspendedLoader(t)
+ pr, pw := io.Pipe()
+ pr.Close()
+ defer pw.Close()
+ _ = l.saveWithOpts(&state.SaveOpts{
+ Destination: pw,
+ Resume: true,
+ MemoryLimit: gccontrol.NoMemoryLimit,
+ }, &controlapi.SaveRestoreExecOpts{})
+ if got := gcPercent(); got < 0 {
+ t.Fatalf("GCPercent after saveWithOpts = %d, want >= 0", got)
+ }
+ })
}
// Test that network=host with raw sockets enabled requires CAP_NET_RAW on theAutomated review agent. Please address valid findings before human review, or close them with a reason.
a48b7a1 to
71b5044
Compare
Sandbox boot, checkpoint save, and checkpoint restore allocate a rapidly growing Go heap from a small initial GOGC target, triggering repeated GC cycles on the critical path. - Add pkg/gccontrol to temporarily disable periodic GC under a cgroup-aware soft memory limit, resuming regular GC automatically if the limit is reached. - Suspend GC at the start of `runsc boot` until the sandbox is idle for 250 ms or at most 500 ms after container start. - Suspend GC across checkpoint save and restore. Fixes gvisor#16134 Fixes gvisor#16152
71b5044 to
c31b2ad
Compare
|
@parth-opensrc, on a one-CPU restore of 100,000 empty tmpfs files, both your PR and Etienne’s #16134 reference got the guest running sooner. From the start of restore to the first verified guest read, the median was 670.0 ms on parent 706b124, 554.0 ms with the reference patch 4a7ccbd applied to that parent, and 547.9 ms on c31b2ad. Benchstat found no timing difference between the reference and the PR on this workload. Sentry RSS at the first read was 308.0 MiB on the parent, 315.7 MiB on the reference and 315.9 MiB on the PR. Each run restored a fresh Sentry under a 2 GiB limit; all 111 runs, including warmups, read back the 100,000-file tree. Original measurements · Benchstat. Posted by Codex on behalf of @tamird. |

Fixes #16134.
Fixes #16152.
Sandbox boot, checkpoint save, and checkpoint restore allocate a rapidly growing
Go heap from a small initial
GOGCtarget, triggering repeated GC cycles on thecritical path (especially under tight container CPU quotas).
This PR suspends periodic Go garbage collection across Sentry lifecycle phases:
pkg/garbageto temporarily disable periodic GC (SetGCPercent(-1))under a cgroup-aware soft memory limit (
min(1 GiB, (totalMem - untrackedMem) / 2)),automatically resuming regular GC if a collection runs.
runsc bootuntil the sandbox is idle for 250 msor at most 500 ms after container start, and coordinate idle heap scavenging
via
garbage.MaybeFreeOSMemory.state.Save) and restore (Loader.Restorethrough async page loading completion).
Benchmarks
Benchmarks vs.
origin/masterRan on 12x GCE
c4-standard-16(cos-129-lts,cgroup2fs), ABBA-interleavedon each VM (
before:origin/masterat0bbcbf9de762,after: this PR).1. Standalone
runsclifecycle, CFS CPU quota (state4k), and large heap (bigheap)busyboxsandbox (RunscRun,RunscCheckpoint,RunscRestore),n=16.state4k(4,000tmpfsfiles) under cgroup v2cpu.max(0.25,1,unlimited) with--sandbox-creation-cpu-policy=1xand--sandbox-lifecycle-cpu-policy=1x,n=16.bigheap(100,000tmpfsfiles, ~320 MiB pre-save Sentry heap) atcpu=unlimitedandcpu=0.25,n=8.2. Sentry memory (
Pss_Anon,RssAnon, and checkpointVmHWM)Notes on memory metrics:
SentryPeakRSS(VmHWMduring non-resumingrunsc checkpoint): increases by~2.6 MiBonstate4kand~75 MiBonbigheapbecause temporaryserialization/compression buffers are not collected right before the Sentry
exits. When a cgroup memory limit is set,
gccontrol.Suspendcaps Go's softmemory limit to half the remaining cgroup budget so GC resumes before OOM.
3.
//test/benchmarks/base(n=16via Docker)Benchmarks vs. Reference Patches (
#16134+#16152,n=32)Ran on 12x GCE
c4-standard-16(cos-129-lts,cgroup2fs), ABBA-interleavedon each VM (
n=32across all suites) on the same base commit (0bbcbf9de762):before:@EtiennePerot's combined reference branches (autoresearch/defer-gcautoresearch/gc-off-during-save) cherry-picked onto0bbcbf9de762after: this PR (5068ecb10)1. Standalone
runsclifecycle, CFS CPU quota (state4k), and large heap (bigheap)2. Sentry memory (
Pss_Anon,RssAnon, and checkpointVmHWM)Note on
bigheapmemory cap tradeoff:pkg/gccontrolbounds unconstrained suspension at1 GiB, whereas thereference branches cap save at
2x usedand restore at256 MiB(whichresumes GC mid-save/restore on
bigheap). Keeping GC suspended throughbigheaptrades+11.6%(~74 MiB)SentryPeakRSSand+5.18%(~44 ms)cpu=unlimitedrestore for-28.75%faster checkpoint and-11.72%fasterrestore under
cpu=0.25.3.
//test/benchmarks/base(n=32via Docker)