Skip to content

oom: avoid per-wakeup allocations in cgroup v2 OOM watcher (#13558) - #13635

Open
KeyMoad wants to merge 4 commits into
containerd:mainfrom
KeyMoad:fix-13558-oom-watcher-cpu
Open

KeyMoad wants to merge 4 commits into
containerd:mainfrom
KeyMoad:fix-13558-oom-watcher-cpu

Conversation

@KeyMoad

@KeyMoad KeyMoad commented Jun 20, 2026

Copy link
Copy Markdown

What this does

Reduces continuous CPU/GC overhead of the per-container cgroup v2 OOM
watcher (internal/oom), which is the only steadily-active, workload-
proportional code path in containerd-shim-runc-v2 on a static workload.

Background (#13558)

The watcher arms an inotify IN_MODIFY watch on memory.events. The kernel
notifies that file on every counter change (low/high/max/oom/
oom_kill/oom_group_kill), not just OOM kills. Containers running near
their memory limit churn high/max constantly (and increasingly as page
cache fills toward the limit over the node's uptime), waking the watcher
goroutine very frequently.

Previously each wakeup allocated a new read buffer and a
map[string]uint64, then opened and fully parsed memory.events with
bufio.Scanner/strings.Fields just to read oom_kill. Across ~50–60
shims this steady allocation churn is avoidable CPU and GC pressure that
accumulates on long-running nodes.

Change

  • Allocate the inotify and memory.events read buffers once per watcher and
    reuse them.
  • Read only the oom_kill counter with a small allocation-light parser.
  • No behavioral change: OOM detection and cgroup-deletion handling are
    identical; covered by the existing TestWatcher plus a new parser unit test.

Copilot AI lite review requested due to automatic review settings June 20, 2026 12:04
@github-project-automation github-project-automation Bot moved this to Needs Triage in Pull Request Review Jun 20, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR optimizes the cgroup v2 OOM watcher in internal/oom to reduce steady-state allocation and parsing overhead in long-running containerd-shim-runc-v2 processes, especially on workloads that frequently update memory.events due to reclaim activity.

Changes:

  • Reuse per-watcher inotify and memory.events read buffers to avoid per-wakeup allocations.
  • Replace full memory.events parsing with a focused parser that extracts only the oom_kill counter.
  • Add unit tests for the new oom_kill parser.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
internal/oom/watcher.go Reuses buffers and switches watcher logic to read only the oom_kill counter.
internal/oom/utils.go Introduces a lightweight memory.events parser (readMemoryOOMKill) and supporting constants.
internal/oom/utils_test.go Adds unit tests validating readMemoryOOMKill behavior.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread internal/oom/utils.go Resolved
@KeyMoad
KeyMoad force-pushed the fix-13558-oom-watcher-cpu branch from 46c7ce0 to f955b24 Compare June 20, 2026 12:26
@KeyMoad

KeyMoad commented Jun 20, 2026

Copy link
Copy Markdown
Author

The only failing check is Vagrant integration (almalinux/8, cgroupfs, runc), which fails at the test-cri-integration step (the preceding test-integration step passes). This looks like an unrelated flake rather than something introduced by this PR:

  • This change only touches internal/oom, the cgroup v2 OOM watcher. AlmaLinux 8 runs cgroup v1, so it uses pkg/oom/v1 and this code path isn't exercised there at all.
  • Every other Vagrant variant passed, including the cgroup v2 jobs that do run this code, as well as almalinux/8, systemd and the other cgroupfs hosts (almalinux/9, almalinux/10, fedora/44).
  • 47/50 checks green, 2 skipped, just this 1 failure.

Could a maintainer re-run the failed job? I don't have permission to re-run it on a fork PR. Happy to dig into the log if it reproduces. Thanks!

@fuweid fuweid self-assigned this Jun 22, 2026
Comment thread internal/oom/watcher.go
// updates on every low/high/max reclaim event, not only on OOM kills),
// so avoiding per-wakeup allocations keeps long-running shims with
// stable workloads from accumulating CPU and GC overhead.
// See https://github.com/containerd/containerd/issues/13558.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think the issue you mentioned could wake it up multiple times because v1.29 doesn't enable like low/high setting on cgroups, if I understand it correctly.

Comment thread internal/oom/watcher.go Outdated
// TODO: We should export MemoryEventsStat function
out := make(map[string]uint64)
if err := readKVStatsFile(w.cgroupPath, "memory.events", out); err != nil {
oomKill, err := readMemoryOOMKill(w.cgroupPath, statsBuf)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would like to keep it as it's right now and file change on cgroupv3 first and then update here.

Comment thread internal/oom/watcher.go Outdated
for !shouldExit {
buffer := make([]byte, unix.SizeofInotifyEvent*10)
bytesRead, err := w.eventFD.Read(buffer)
bytesRead, err := w.eventFD.Read(eventBuf)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

before we reuse it, let's use clear(eventBuf) first.

Comment thread internal/oom/utils.go Outdated
// line) on each wakeup, which otherwise accumulates measurable CPU and GC
// overhead over the lifetime of the shim.
// See https://github.com/containerd/containerd/issues/13558.
func readMemoryOOMKill(cgroupPath string, buf []byte) (uint64, error) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can go with buf bytes.Buffer here. There is method ReadFrom which will increase the length if original size is not good enough. After increasing it, we can reuse it in the follow-up.

func (w *watcher) start() {
...
     var (
			statsBuf   bytes.Buffer
      )
     
      readMemoryOOMKill(cgroupPath string, buf *bytes.Buffer)
}

func readMemoryOOMKill(memoryEventsPath string, buf *bytes.Buffer) (uint64, error) {
	buf.Reset()

	f, err := os.Open(memoryEventsPath)
	if err != nil {
		return 0, err
	}
	defer f.Close()

	if _, err := buf.ReadFrom(f); err != nil {
		return 0, err
	}

	v, err := parseOOMKill(buf.Bytes())
	if err != nil {
		return 0, fmt.Errorf("error while parsing %s: %w", memoryEventsPath, err)
	}
	return v, nil
}

Comment thread internal/oom/watcher.go Outdated
var (
oomKills uint64
shouldExit bool
eventBuf = make([]byte, unix.SizeofInotifyEvent*10)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can go with eventBuf = [unix.SizeofInotifyEvent*10]byte which won't be escaped to heap.

@fuweid

fuweid commented Jul 24, 2026

Copy link
Copy Markdown
Member

Hi @KeyMoad Thanks for the patch. It's helpful. Please let us know if you still want to work on this.

@fuweid fuweid added the cherry-pick/2.3.x Change to be cherry picked to release/2.3 label Jul 24, 2026
@KeyMoad

KeyMoad commented Jul 26, 2026

Copy link
Copy Markdown
Author

Hi @fuweid, Sure I would like to continue working on this. Sorry for the late response.
I will update the improvement if it's OK.

@fuweid

fuweid commented Jul 27, 2026

Copy link
Copy Markdown
Member

@KeyMoad sure! Please update it when you have chance. Thanks!

@fuweid

fuweid commented Aug 12, 2026

Copy link
Copy Markdown
Member

kindly ping @KeyMoad any update?

Copilot AI review requested due to automatic review settings August 16, 2026 08:24
@kubernetes-prow kubernetes-prow Bot added size/S and removed size/L labels Aug 16, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 1 out of 1 changed files in this pull request and generated no new comments.

Suppressed comments (2)

internal/oom/watcher.go:115

  • clear(eventBuf[:]) runs on every wakeup and zeros the entire buffer even though only bytesRead bytes are relevant. This adds avoidable work to a hot loop; consider removing the clear(...) and ensuring downstream parsing only examines the eventBuf[:bytesRead] slice.
			eventBuf   [unix.SizeofInotifyEvent * 10]byte
		)
		for !shouldExit {
			clear(eventBuf[:])
			bytesRead, err := w.eventFD.Read(eventBuf[:])

internal/oom/watcher.go:122

  • When err is os.ErrClosed, the code sets shouldExit = true but still falls through and may process eventBuf using an invalid/partial bytesRead value from the failed Read. Add a break or continue after setting shouldExit = true (or return) to avoid processing after the FD is closed.
			if err != nil {
				if !errors.Is(err, os.ErrClosed) {
					w.errCh <- err
					return
				}
				shouldExit = true
			} else if bytesRead < unix.SizeofInotifyEvent {
				continue
			}

@KeyMoad
KeyMoad force-pushed the fix-13558-oom-watcher-cpu branch from 44094c8 to b466c67 Compare August 16, 2026 09:04
@KeyMoad

KeyMoad commented Aug 16, 2026

Copy link
Copy Markdown
Author

kindly ping @KeyMoad any update?

Hi @fuweid, update pushed with your review feedback applied (kept readKVStatsFile, stack eventBuf + clear). Thanks for the ping!

@KeyMoad
KeyMoad requested a review from fuweid August 16, 2026 09:48

@fuweid fuweid left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please confirm this? probably we need benchmark testcase to confirm there is no extra allocations.

Comment thread internal/oom/watcher.go
shouldExit bool
eventBuf [unix.SizeofInotifyEvent * 10]byte
)
for !shouldExit {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I revisit this part and found that go doesn't recreate it.

In amd64, I got this. I think the main reason is that we don't read content and just check bytes.
So, go compile uses stack memory for us.

➜  containerd git:(main) GOTOOLCHAIN=go1.26.6 go build \
    -o /tmp/containerd-shim-runc-v2-base \
    -gcflags='github.com/containerd/containerd/v2/internal/oom=-m=2' \
    ./cmd/containerd-shim-runc-v2 2>&1 |
    ag 'watcher.go.*(escape|does not escape)'
...
internal/oom/watcher.go:112:18: make([]byte, 160) does not escape
...
$ GOTOOLCHAIN=go1.26.6 go tool objdump \
    -s 'github.com/containerd/containerd/v2/internal/oom\.\(\*watcher\)\.start\.func1$' \
    /tmp/containerd-shim-runc-v2-base
...

 watcher.go:112        0x987c18                488d5c2430                      LEAQ 0x30(SP), BX

  watcher.go:112        0x987c1d                440f113b                        MOVUPS X15, 0(BX)

  watcher.go:112        0x987c21                440f117b10                      MOVUPS X15, 0x10(BX)

  watcher.go:112        0x987c26                440f117b20                      MOVUPS X15, 0x20(BX)

  watcher.go:112        0x987c2b                440f117b30                      MOVUPS X15, 0x30(BX)

  watcher.go:112        0x987c30                440f117b40                      MOVUPS X15, 0x40(BX)

  watcher.go:112        0x987c35                440f117b50                      MOVUPS X15, 0x50(BX)

  watcher.go:112        0x987c3a                440f117b60                      MOVUPS X15, 0x60(BX)

  watcher.go:112        0x987c3f                440f117b70                      MOVUPS X15, 0x70(BX)

  watcher.go:112        0x987c44                440f11bb80000000                MOVUPS X15, 0x80(BX)

  watcher.go:112        0x987c4c                440f11bb90000000                MOVUPS X15, 0x90(BX)

  watcher.go:113        0x987c54                440f11bc2438020000              MOVUPS X15, 0x238(SP)

We don't need to cleanup it as well.
So, I don't think we need to update this part.

@github-project-automation github-project-automation Bot moved this from Needs Triage to Needs Update in Pull Request Review Aug 18, 2026
Copilot AI review requested due to automatic review settings August 19, 2026 09:15

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

Suppressed comments (2)

internal/oom/watcher.go:113

  • The watcher loop still allocates a new map[string]uint64 on every inotify wakeup (out := make(...)), which undermines the goal of reducing steady per-wakeup allocations/GC pressure. Consider moving the map allocation outside the loop and clear-ing it each iteration before calling readKVStatsFile.
		var (
			oomKills   uint64
			shouldExit bool
			eventBuf   [unix.SizeofInotifyEvent * 10]byte
		)

internal/oom/watcher_test.go:122

  • This benchmark currently includes one-time map growth allocations (and readKVStatsFile also allocates via bufio.Scanner/strings.Fields), so the comment stating it "does not allocate" is misleading and the measurement is noisy. Pre-size/warm the map before ResetTimer, and adjust the comment to reflect that it measures allocations rather than asserting zero allocs.
// BenchmarkReadKVStatsFile confirms that reading the oom_kill counter from
// memory.events via readKVStatsFile does not allocate on the reused-map path.
// Run with: go test -bench=BenchmarkReadKVStatsFile -benchmem ./internal/oom/
func BenchmarkReadKVStatsFile(b *testing.B) {
	dir := b.TempDir()

The cgroup v2 OOM watcher arms an inotify IN_MODIFY watch on a
container's memory.events file. The kernel rewrites/notifies that file on
every change to any of its counters (low/high/max/oom/oom_kill/
oom_group_kill), not only on OOM kills. For workloads running near their
memory limit the low/high/max reclaim counters churn continuously, so the
watcher goroutine is woken very frequently.

On every wakeup the watcher allocated a fresh inotify read buffer and a
new map[string]uint64, then opened and fully parsed memory.events with a
bufio.Scanner + strings.Fields, only to read the single oom_kill counter.
On long-running nodes with stable workloads this steady allocation churn
accumulates measurable CPU and GC overhead in each shim, contributing to
the slowly growing shim CPU usage reported in containerd#13558.

Hoist both buffers out of the loop so they are reused for the lifetime of
the watcher, and read only the oom_kill counter via a small allocation-light
parser instead of building a map and re-parsing every line.

No behavior change: oom_kill detection and cgroup-deletion handling are
preserved. Adds a unit test for the new parser.

Fixes: containerd#13558
Signed-off-by: KeyMoad <[email protected]>
The previous change read memory.events into a fixed-size reusable buffer.
If the file were ever larger than that buffer (e.g. a future kernel adds
counters, or very large values), the oom_kill line could fall beyond what
was read and an OOM event would be silently missed.

Keep the allocation-free fast path for the common case where the file fits
in the buffer, but when io.ReadFull fills the buffer completely (meaning the
file may be larger) fall back to reading the remainder so the oom_kill
counter is never truncated away. A genuinely absent oom_kill line still
reports 0, matching the previous Scanner-based behavior.

Adds a regression test that parses a normal file through an undersized
buffer to exercise the fallback.

Addresses review feedback on containerd#13558.

Signed-off-by: KeyMoad <[email protected]>
Keep readKVStatsFile for memory.events parsing until a helper is exported from cgroups/v3, and reuse a stack-allocated inotify buffer cleared before each read so the hot path avoids heap allocations.

Signed-off-by: KeyMoad <[email protected]>
Go zero-initializes the stack-allocated eventBuf array so clear is redundant; remove it. Add a continue after setting shouldExit to avoid calling readKVStatsFile on a closed fd. Add BenchmarkReadKVStatsFile to confirm per-wakeup allocation behaviour of the reused-map path.

Signed-off-by: KeyMoad <[email protected]>
Copilot AI review requested due to automatic review settings August 19, 2026 09:23
@KeyMoad
KeyMoad force-pushed the fix-13558-oom-watcher-cpu branch from 0acfd89 to 2020b34 Compare August 19, 2026 09:23

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

Suppressed comments (1)

internal/oom/watcher.go:114

  • The watcher loop still allocates out := make(map[string]uint64) on every inotify wakeup, which defeats the stated goal of avoiding per-wakeup allocations (and makes the new benchmark’s “reused-map path” not reflect the watcher’s behavior). Allocate the map once for the lifetime of the watcher and clear(out) each iteration before reuse.
		var (
			oomKills   uint64
			shouldExit bool
			eventBuf   [unix.SizeofInotifyEvent * 10]byte
		)

@KeyMoad

KeyMoad commented Aug 19, 2026

Copy link
Copy Markdown
Author

Hey @fuweid, thanks for the detailed investigation.

Updated in the latest commit:

  • Removed clear(eventBuf[:]), you're right, Go already zero-initializes the stack array so it's redundant overhead
  • Added continue after shouldExit = true to avoid falling into readKVStatsFile on a closed fd
  • Added BenchmarkReadKVStatsFile to document the per-wakeup allocation behaviour of the reused-map path

@fuweid

fuweid commented Aug 19, 2026

Copy link
Copy Markdown
Member

Hi @KeyMoad The original code (main branch) doesn't escape to heap. It already uses stack memory for it. We don't need such change if you have chance to check out my last comment. Thanks

@fuweid fuweid removed the cherry-pick/2.3.x Change to be cherry picked to release/2.3 label Sep 7, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: Needs Update

Development

Successfully merging this pull request may close these issues.

3 participants