Skip to content

shim: send event to a queue to reduce lock contention - #13653

Open
ningmingxiao wants to merge 1 commit into
containerd:mainfrom
ningmingxiao:optimize_reap3
Open

ningmingxiao wants to merge 1 commit into
containerd:mainfrom
ningmingxiao:optimize_reap3

Conversation

@ningmingxiao

@ningmingxiao ningmingxiao commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

@dmcgowan @fuweid @mxpv can you take a look.
fix #12678

func (s *service) processExits() {
	for e := range s.ec {
         // if consumer use much time more than 1s event will be dropped
        }

because notify will stop wait notify if consumer use more than 1s (events will not be droped)

func Reap() error {
	now := time.Now()
	exits, err := reap(false)
	for _, e := range exits {
		done := Default.notify(runc.Exit{
			Timestamp: now,
			Pid:       e.Pid,
			Status:    e.Status,
		})

		select {
		case <-done:
		case <-time.After(1 * time.Second):
		}
	}
	return err
}

I create a queue to add this event into it it will make consumer consume event quickly
It's easy to reproduce it add some sleep here (simulate high-load scenarios because sometimes wait lifecycleMu lock may quite a while)

func (s *service) processExits() {
	for e := range s.ec {
              // add some sleep
		time.Sleep(time.Second * 3)
		s.lifecycleMu.Lock()

reproduce

✦2 ❯ cat container.json
{
  "metadata": {
    "name": "TESTFAILPOINTPROFILE_delayUpdate5"
  },
  "image": {
    "image": "busybox:latest"
  },
  "command": [
    'sleep','infinity'
  ],
  "log_path": "busybox5.log",
      "linux": {
        "resources": {
          "memory": {
            "limit": 20971
          }
        }
      }
 }

root in /home/nmx/pods via 🐹 v1.26.3 
✦2 ❯ cat pod.json
{
    "metadata": {
        "name": "busybox-sandbox2",
        "namespace": "default",
        "attempt": 1
    },
      "annotations": {
  },
    "log_directory": "/tmp"
}

crictl run --no-pull container.json pod.json
66abdf4d13
go run main.go

cat main.go

package main

import (
	"fmt"
	"os/exec"
	"sync"
	"time"
)

func main() {
	const (
		totalTask = 100
		maxConcur = 50
	)
	var wg sync.WaitGroup
	ch := make(chan struct{}, maxConcur)

	go func() {
		time.Sleep(time.Second*2)
		cmd := exec.Command("sh", "-c", "kill -9 $(pidof sleep)")
		cmd.CombinedOutput()
	}()
	for i := 0; i < totalTask; i++ {
		ch <- struct{}{}
		wg.Add(1)
		go func(idx int) {
			defer func() {
				<-ch
				wg.Done()
			}()
			cmd := exec.Command("sh", "-c", "crictl exec 66abdf4d13 date")
			_, err := cmd.CombinedOutput()
			if err != nil {
				fmt.Printf("Task %d execution failed: %v\n", idx, err)
			}
		}(i)
	}

	wg.Wait()
	close(ch)
	fmt.Println("done")
}

crictl  ps|grep 66a
66abdf4d13b04       busybox:latest      About a minute ago   Running             TESTFAILPOINTPROFILE_delayUpdate5   0                   bb4899de19161       unknown             unknown

crictl  exec  66a date
FATA[0000] execing command in container 66a: Internal error occurred: error executing command in container: failed to exec in container: failed to start exec "35d0a3f6180055dcc2694b39c53d7e4215613850e622222cb78be205f1016fae": OCI runtime exec failed: exec failed: cannot exec in a stopped container

container is still running even main process is exited (it will keep runing in long time and It will eventually work normally)

@evgfitil

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 aims to prevent shim exit events from being lost under load by decoupling reaper event consumption from the heavier per-exit handling logic (i.e., drain reaper.Default.Subscribe() quickly and process exits asynchronously).

Changes:

  • Introduces a mutex/cond-backed queue (safeList) to buffer reaper exit events.
  • Splits exit handling into a fast producer loop (draining s.ec) and a consumer goroutine (processing queued exits).
  • Adds a package-level eventQueue used by processExits().

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

@ningmingxiao ningmingxiao changed the title shim: optimize reap to prevent event lost shim: send event to a queue to prevent event to be dropped Jun 23, 2026
Copilot AI review requested due to automatic review settings June 23, 2026 03:29

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 5 comments.

@evgfitil

Copy link
Copy Markdown

Hi @ningmingxiao, thanks for working on this!

  1. Could you please confirm whether this PR is expected to resolve the issue described in CRI plugin: container stuck as RUNNING after process exit #12678 — the container stuck in CONTAINER_RUNNING after the process exits?
  2. Also, which release branches/versions is this targeting, and is a backport planned (e.g. for release/1.7)?

@ningmingxiao

Copy link
Copy Markdown
Contributor Author

I'm not sure ,this is very likely the reason.

@ningmingxiao

Copy link
Copy Markdown
Contributor Author

ping @samuelkarp @mikebrow can you take a look?

Copilot AI review requested due to automatic review settings June 27, 2026 01:25

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 3 comments.

Copilot AI review requested due to automatic review settings July 21, 2026 03:49

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 1 comment.

Comments suppressed due to low confidence (1)

cmd/containerd-shim-runc-v2/task/service.go:696

  • processExits now starts a long-lived consumer goroutine that blocks in dequeue() and never observes s.shutdown.Done(). After Shutdown() the shim will continue to enqueue/dequeue and take lifecycleMu even though send() drops events once shutdown is triggered, which adds unnecessary work and makes shutdown behavior harder to reason about. Consider wiring the queue/consumer to s.shutdown.Done() (and optionally unsubscribing from reaper.Default) so both goroutines can exit promptly on shutdown.
func (s *service) processExits() {
	go func() {
		for {
			event := s.dequeue()
			if e, ok := event.(runcC.Exit); ok {
				// While unlikely, it is not impossible for a container process to exit

Copilot AI review requested due to automatic review settings July 21, 2026 04:36

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.

Comments suppressed due to low confidence (3)

cmd/containerd-shim-runc-v2/task/service.go:696

  • The exit-processing goroutine runs for { e := s.dequeue() } and dequeue() blocks on cond.Wait() with no shutdown/close path. If s.ec is closed (or the shim is shutting down) and the queue is empty, this goroutine will block forever, leaking and potentially holding references to service state longer than needed. Consider adding a close mechanism to eventQueue (e.g., closed flag + Broadcast) and make processExits stop the consumer when <-s.shutdown.Done() fires and/or after s.ec is closed and the queue is drained.
	go func() {
		for {
			e := s.dequeue()
			// While unlikely, it is not impossible for a container process to exit
			// and have its PID be recycled for a new container process before we

cmd/containerd-shim-runc-v2/task/service.go:672

  • eventQueue.buf is an unbounded slice that only ever grows via append. Under sustained exit rates (e.g., many short-lived execs) if handling is slower than enqueueing, memory usage can grow without bound; additionally, using s.buf = s.buf[1:] retains the peak backing array capacity even after the queue drains. Consider a ring-buffer implementation, or periodically resetting/shrinking the buffer when it becomes empty to avoid retaining a large backing array indefinitely.
func (s *eventQueue) enqueue(e runcC.Exit) {
	s.qmu.Lock()
	defer s.qmu.Unlock()
	s.buf = append(s.buf, e)
	s.cond.Signal()
}

cmd/containerd-shim-runc-v2/task/service.go:735

  • Grammar: "prevent event to be dropped" reads awkwardly and is easy to misread. Suggest "prevent events from being dropped".
		// send events to a queue to prevent event to be dropped because of timeout.
		s.enqueue(e)

Copilot AI review requested due to automatic review settings July 21, 2026 04:40

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 1 comment.

Comments suppressed due to low confidence (2)

cmd/containerd-shim-runc-v2/task/service.go:699

  • The dequeue/processing goroutine has no termination path. After shutdown (or if the reaper subscription is ever unsubscribed/closed), it can block forever in dequeue() and leak a goroutine, potentially continuing to call handleInitExit/handleProcessExit after shutdown has begun.
			// While unlikely, it is not impossible for a container process to exit
			// and have its PID be recycled for a new container process before we
			// have a chance to process the first exit. As we have no way to tell
			// for sure which of the processes the exit event corresponds to (until
			// pidfd support is implemented) there is no way for us to handle the

cmd/containerd-shim-runc-v2/task/service.go:738

  • Grammar: “prevent event to be dropped” is ungrammatical; consider rephrasing for clarity.
}

Copilot AI review requested due to automatic review settings July 21, 2026 04:44

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.

Comments suppressed due to low confidence (2)

cmd/containerd-shim-runc-v2/task/service.go:682

  • dequeue() pops from the front by reslicing (s.buf = s.buf[1:]). After a large burst drains, the slice can still keep the old backing array alive (even when len==0), retaining memory unnecessarily. Consider nil-ing the slice when it becomes empty to allow GC to reclaim the backing array sooner.
	event := s.buf[0]
	s.buf = s.buf[1:]
	return event

cmd/containerd-shim-runc-v2/task/service.go:734

  • Grammar in this comment is a bit unclear; tightening it will make the rationale easier to understand for future readers.
		// send events to a queue to prevent event to be dropped because of timeout.

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.

Comments suppressed due to low confidence (2)

cmd/containerd-shim-runc-v2/task/service.go:694

  • processExits starts a consumer goroutine that loops forever and blocks in dequeue()/cond.Wait(). There is no shutdown/close path to unblock the wait, so the goroutine can leak and keep running after Shutdown() (or after the ec subscription stops). Consider adding a close/cancel mechanism to eventQueue (e.g., closed flag + Broadcast()), have dequeue() return (exit, ok) and exit the consumer loop when closed, and stop enqueueing when <-s.shutdown.Done() fires.
	go func() {
		for {
			e := s.dequeue()

cmd/containerd-shim-runc-v2/task/service.go:665

  • eventQueue.buf is an unbounded slice, so if exit processing is delayed (e.g., lifecycleMu contention) the shim can accumulate an arbitrarily large number of exit events and potentially run out of memory. If dropping is unacceptable, consider adding backpressure (bounded queue + blocking enqueue), configurability, and/or logging/metrics so pathological growth is observable and controllable.
type eventQueue struct {
	qmu  sync.Mutex
	cond *sync.Cond
	buf  []runcC.Exit
}

@cpuguy83 cpuguy83 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.

This doesn't seem like a correct change.

The channel in reap is a done notification, its not dropping the exit its just no longer waiting for the event to be delivered.

The delivery still happens, though.

@ningmingxiao

ningmingxiao commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor Author

yes you are right the goroutine will exited until send event sucessfully
after dozens of minutes the event will be sent

	go func() {
		defer close(done)

		for {
			var (
				failed      int
				subscribers = m.getSubscribers()
			)
			for _, s := range subscribers {
				s.do(func() {
					if s.closed {
						return
					}
					if _, ok := success[s.c]; ok {
						return
					}
					timer.Reset(timeout)
					recv := true
					select {
					case s.c <- e:
						success[s.c] = struct{}{}
					case <-timer.C:
						recv = false
						failed++
					}
					stop(timer, recv)
				})
			}
			// all subscribers received the message
			if failed == 0 {
				return
			}
		}
	}()

but the disadvantage is that we can't keep the event in order, how about delete the goroutine and send events synchronously(send event to a queue at producer or consumer side ) but waitpid may can't keep the event in right order after reviewing some references @cpuguy83

@cpuguy83

Copy link
Copy Markdown
Member

I'm not sure of the decision that brought us the current implementation. Probably worthwhile to dig into the history here.

I would say doing the whole thing synchronously would be the way to go to give the proper back pressure on a busy system.
But again, need to understand why it is currently the way it is.

Copilot AI balanced review requested due to automatic review settings October 6, 2026 10:04
@ningmingxiao ningmingxiao changed the title shim: send event to a queue to prevent event to be dropped shim: send event to a queue to reduce lock contention Oct 6, 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.

Copilot review overview

🟢 Approval recommended

The queue safely preserves FIFO delivery while preventing slow exit processing from blocking reaper notifications.

Review effort: Balanced
Findings: None

s.handleProcessExit(e, cp.Container, cp.Process)
for _, cp := range cps {
if ip, ok := cp.Process.(*process.Init); ok {
s.handleInitExit(e, cp.Container, ip)

@adamwathieu adamwathieu Oct 6, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Did you consider just putting

    if runc.ShouldKillAllOnExit(s.context, c.Bundle) {
        if err := p.KillAll(s.context); err != nil {
            log.G(s.context).WithError(err).WithField("id", p.ID()).
                Error("failed to kill init's children")
        }
    }

in a goroutine in s.handleInitExit()? I think that would make the producer and consumer async. Then, we wouldn't need to add the queue to this part of the code?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

docker need to keep these events in order and main process exited in container should be send at last @adamwathieu

@adamwathieu

Copy link
Copy Markdown

It depends on how large of a change you want to make this PR (a band-aid fix for just processExits() or a more significant refactor of the Reap pub sub to address all potential deadlocks), but one direction you could take the fix is to make Reap() not block for 1 second for everyone when Default.notify() is blocked by a single subscriber's full channel. I think notify() should be resilient to a single subscriber taking things off the queue slowly. Is this something you considered?

@ningmingxiao

Copy link
Copy Markdown
Contributor Author

my old pr #13543 can implent it ,the code isn’t very clean. @calavera

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 Triage

Development

Successfully merging this pull request may close these issues.

CRI plugin: container stuck as RUNNING after process exit

5 participants