Skip to content

runtime: defer/recover support in race detector #26813

Open

Description

@adilbaig

Hi Go Devs,

I've noticed a strange memory leak when running my Go program with the Race Detector. The program is an ad-hit tracker, it receives data from RabbitMQ and writes them down to the database. When there are errors in the DB, the program leaks memory (the RES mem usage grows unchecked until the machine runs out of RAM).

Run the program (below) with and without the -race detector to see the difference.

What version of Go are you using (go version)?

go version go1.10.3 linux/amd64

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

GOARCH="amd64"
GOBIN=""
GOCACHE="/home/adil/.cache/go-build"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/adil/go"
GORACE=""
GOROOT="/snap/go/2130"
GOTMPDIR=""
GOTOOLDIR="/snap/go/2130/pkg/tool/linux_amd64"
GCCGO="gccgo"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build049513405=/tmp/go-build -gno-record-gcc-switches"

What did you do?

Run this program without the race detector:

> go build -o race experimental/rabbitmqmemoryleak.go && ./race

Observe the memory usage in top. It should flatline. Then, run it with the -race detector

> go build -race -o race experimental/rabbitmqmemoryleak.go && ./race

The memory usage grows unchecked.

package main

import (
	"database/sql"
	"log"

	"github.com/go-errors/errors"
	_ "github.com/lib/pq"
	"github.com/streadway/amqp"
)

// This program demonstrates a memory leak in Go's built-in race detector.
// You will need RabbitMQ and Postgres installed on your machine.

// First, run the program like this:
// > 	go build -o race experimental/rabbitmqmemoryleak.go && ./race
// Observe the 'RES' memory in `top`. It should level after a bit
//
// Then, run the program like this:
// > 	go build -race -o race experimental/rabbitmqmemoryleak.go && ./race
// Watch as RAM usage counts unchecked

// Strangely running `go run -race experimental/rabbitmqmemoryleak.go` does not leak memory.

func main() {

	var err error

	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672")
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	channel, err := conn.Channel()
	if err != nil {
		log.Fatal(err)
	}
	defer channel.Close()

	queue := "testing-memory-leak"

	// 1. Create the queue
	var args amqp.Table
	_, err = channel.QueueDeclare(queue, false, true, false, false, args)
	defer channel.QueueDelete(queue, false, false, true)

	// 2. Fill in messages
	cnt := 100000
	log.Printf("Inserting %d messages", cnt)
	for index := 0; index < cnt; index++ {
		msg := `{"date":"2018-07-17 08:44:30.202358+02","campaignID":18275,"affiliateSiteID":70002,"materialID":969206,"referenceID":0,"referenceHash":null,"referenceName":null,"isUnique":true,"merchantCommission":"0","affiliateCommission":"0","IP":"37.74.164.6","postImpressionHash":"0ebdd4720ef7eba5f09a84b8c68367c6","universalFingerprintHash":"c47e486da2ff1a4695b1499052b09807","pushToDynamoDB":true,"timestamp":"1531809870","handlerType":"impression","host":"snipped","pid":7962,"userAgentID":null,"userAgentHash":"08ac6aeb466ccd8f05ad37a144afe0f8","userAgentName":"Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/58.0.3029.110 Safari\/537.36 Edge\/16.16299","requestHash":"29c2363878fee77174d0b1e2491ea93b"}`
		err := channel.Publish("", queue, true, false, amqp.Publishing{ContentType: "application/json", Body: []byte(msg), DeliveryMode: 2})
		if err != nil {
			log.Panic(err)
		}
	}
	log.Printf("Done")

	pgb, err := sql.Open("postgres", "host=localhost user=user password=pass dbname=db sslmode=disable")
	if err != nil {
		log.Fatal(err)
	}
	defer pgb.Close()

	// 2. Listen on the messages
	forever := make(chan bool)
	for i := 0; i < 10; i++ {
		go handler(queue, pgb)
	}
	<-forever
}

func handler(queue string, pgb *sql.DB) {
	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672")
	if err != nil {
		log.Fatal(err)
	}

	channel, err := conn.Channel()
	if err != nil {
		log.Fatal(err)
	}

	for {
		message, ok, err := channel.Get(queue, false)
		if err != nil {
			log.Fatal(err)
		}
		if !ok {
			continue
		}

		log.Printf("%+v", message)

		err = someErroneousSQLTransaction(pgb)
		if err != nil {
			log.Printf("ERROR: %s", err)
			message.Nack(false, true)
		} else {
			message.Ack(false)
		}
	}
}

func someErroneousSQLTransaction(pgb *sql.DB) error {
	refTx, err := pgb.Begin()
	if err != nil {
		return errors.Wrap(err, 0)
	}
	defer func() {
		if err != nil {
			refTx.Rollback()
		} else {
			refTx.Commit()
		}
	}()
	_, err = refTx.Exec(`set transaction isolation level repeatable read`)
	if err != nil {
		return err
	}

	var referenceID int64
	switch err = pgb.QueryRow(`SELECT "ID" FROM public.blah LIMIT 1`).Scan(&referenceID); err {
	case sql.ErrNoRows:
		break
	case nil:
		break
	default:
		return err
	}

	return nil
}

What did you expect to see?

Flatline memory usage, as measured with top when running with -race. I expect it to take more memory to maintain internal data structures, but it should flatline at some point.

What did you see instead?

Constantly growing RES mem usage in top.

Strangely running go run -race experimental/rabbitmqmemoryleak.go does not leak memory.

Activity

  1. added
    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.
    on Aug 5, 2018
  2. changed the title [-]Go's race detector is leaking memory on RabbitMQ and Postgres[/-] [+]runtime: Go's race detector is leaking memory on RabbitMQ and Postgres[/+] on Aug 5, 2018
  3. added this to the Go1.12 milestone on Aug 5, 2018
  4. ianlancetaylor commented on Aug 5, 2018

    @ianlancetaylor
    Contributor
  5. dvyukov commented on Aug 6, 2018

    @dvyukov
    Member

    Difference between go build and go run looks strange. Do we have any known precedent of differences?

  6. dvyukov commented on Aug 6, 2018

    @dvyukov
    Member

    @adilbaig can you provide a step-by-step repro instructions?

  7. agnivade commented on Aug 6, 2018

    @agnivade
    Contributor

    It is there in the code comments I believe -

    // This program demonstrates a memory leak in Go's built-in race detector.
    // You will need RabbitMQ and Postgres installed on your machine.
    
    // First, run the program like this:
    // > 	go build -o race experimental/rabbitmqmemoryleak.go && ./race
    // Observe the 'RES' memory in `top`. It should level after a bit
    //
    // Then, run the program like this:
    // > 	go build -race -o race experimental/rabbitmqmemoryleak.go && ./race
    // Watch as RAM usage counts unchecked
    

    Did you want anything specific ?

  8. dvyukov commented on Aug 6, 2018

    @dvyukov
    Member

    Something that I can copy-paste into my console.

  9. adilbaig commented on Aug 6, 2018

    @adilbaig
    Author

    @dvyukov How about this.

    # Have RabbitMQ and Postgres setup (tested with version 9.6), on Ubuntu
    sudo apt install rabbitmq-server postgresql-9.6
    go get "github.com/streadway/amqp"
    go build -o race rabbitmqmemoryleak.go && ./race
    # Open `top` in another shell and see that memory usage (RES) is flat for this process. CTRL+C ./race.
    go build -race -o race rabbitmqmemoryleak.go && ./race
    # Now, open `top` in another shell and see the memory leak

    You don't actually need to create Postgres tables. I see the leaks when the SQL errors out (for example due to bad login credentials).

  10. dvyukov commented on Aug 6, 2018

    @dvyukov
    Member

    Can reproduce it now.
    The problem is that the program grows infinite stack with infinite recursion:

    ...
      database/sql.(*DB).Begin()
          database/sql/sql.go:1637 +0x6d
      main.someErroneousSQLTransaction()
          /tmp/rabbitmqmemoryleak.go:107 +0x5b
      main.handler()
          /tmp/rabbitmqmemoryleak.go:96 +0x22b
      database/sql.(*DB).Begin()
          database/sql/sql.go:1637 +0x6d
      main.someErroneousSQLTransaction()
          /tmp/rabbitmqmemoryleak.go:107 +0x5b
      main.handler()
          /tmp/rabbitmqmemoryleak.go:96 +0x22b
      database/sql.(*DB).Begin()
          database/sql/sql.go:1637 +0x6d
      main.someErroneousSQLTransaction()
          /tmp/rabbitmqmemoryleak.go:107 +0x5b
      main.handler()
          /tmp/rabbitmqmemoryleak.go:96 +0x22b
      database/sql.(*DB).Begin()
          database/sql/sql.go:1637 +0x6d
      main.someErroneousSQLTransaction()
          /tmp/rabbitmqmemoryleak.go:107 +0x5b
      main.handler()
          /tmp/rabbitmqmemoryleak.go:96 +0x22b
      database/sql.(*DB).Begin()
          database/sql/sql.go:1637 +0x6d
      main.someErroneousSQLTransaction()
          /tmp/rabbitmqmemoryleak.go:107 +0x5b
      main.handler()
          /tmp/rabbitmqmemoryleak.go:96 +0x22b
      database/sql.(*DB).Begin()
          database/sql/sql.go:1637 +0x6d
      main.someErroneousSQLTransaction()
          /tmp/rabbitmqmemoryleak.go:107 +0x5b
      main.handler()
          /tmp/rabbitmqmemoryleak.go:96 +0x22b
      database/sql.(*DB).Begin()
          database/sql/sql.go:1637 +0x6d
      main.someErroneousSQLTransaction()
          /tmp/rabbitmqmemoryleak.go:107 +0x5b
      main.handler()
          /tmp/rabbitmqmemoryleak.go:96 +0x22b
      database/sql.(*DB).Begin()
          database/sql/sql.go:1637 +0x6d
    ...
    

    So it will crash without race detector sooner or later too, makes GC slow, crash messages unreadable, etc.
    It's just that race detector is more sensitive to thousands of unique stacks as it memorizes tons of contextual information about the program as it runs. In this case it memorizes several variations of the stack per recursion frame, which is quadratic memory consumption.

  11. adilbaig commented on Aug 6, 2018

    @adilbaig
    Author

    @dvnagorny

    So it will crash without race detector sooner or later too

    I haven't seen that happen, as I ran it without the race detector over the weekend. Can you confirm that it's stable without -race?

    I'm a novice at Go, but, given your explanation, am i right to think this will be an issue for any evented system (that errors out on events).?

  12. dvyukov commented on Aug 6, 2018

    @dvyukov
    Member

    Can you confirm that it's stable without -race?

    no.

    I'm a novice at Go, but, given your explanation, am i right to think this will be an issue for any evented system (that errors out on events).?

    I don't know about these libraries, but what first comes to my mind is that there is a way to use them without infinite recursion. You both have an infinite loop in handler and call it recursively. I would expect that you need to do only 1 of these things, but not both. Have you looked at other usage examples of these libraries? Do all of them use it in the same way?

  13. adilbaig commented on Aug 7, 2018

    @adilbaig
    Author

    I don't know about these libraries, but what first comes to my mind is that there is a way to use them without infinite recursion. You both have an infinite loop in handler and call it recursively. I would expect that you need to do only 1 of these things, but not both.

    I guess it only looks recursive in the dump, but it isn't, it's just running in a loop one message after another erroring out at every message. So I'm guessing with the race detector on, a reference to something in the sql package is still being bandied around. I tried replacing the sql error with a plain fmt.Errorf, memory usage remained flat. So it isn't any error that causes the leak, but something specific to the sql library. That's my guess.

    for {
    		message, ok, err := channel.Get(queue, false)
    		if err != nil {
    			log.Fatal(err)
    		}
    		if !ok {
    			continue
    		}
    
    		log.Printf("%+v", message)
    
    		// err = someErroneousSQLTransaction(pgb)
    		err = fmt.Errorf("FAKE ERROR!") //Didn't leak
    		if err != nil {
    			log.Printf("ERROR: %s", err)
    			message.Nack(false, true)
    		} else {
    			message.Ack(false)
    		}
    	}
    ...
    

    Have you looked at other usage examples of these libraries? Do all of them use it in the same way?

    Yep, it's largely just fetching and processing a message in a loop. Here's a canonical example from the site: https://www.rabbitmq.com/tutorials/tutorial-one-go.html (Code is at https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/go/receive.go)

    @dvnagorny

  14. dvyukov commented on Aug 8, 2018

    @dvyukov
    Member

    I guess it only looks recursive in the dump, but it isn't, it's just running in a loop one message after another erroring out at every message.

    No, it calls someErroneousSQLTransaction which calls sql.(*DB).Begin which calls handler again.

  15. 19 remaining items

  16. gopherbot commented on Feb 24, 2020

    @gopherbot
    Contributor

    Change https://golang.org/cl/220586 mentions this issue: doc/articles: mention memory leak in race detector docs

  17. gopherbot commented on Feb 25, 2020

    @gopherbot
    Contributor

    Change https://golang.org/cl/221019 mentions this issue: [release-branch.go1.14] doc/articles/race_detector: mention memory leak potential

  18. added
    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.
    on Feb 26, 2020
  19. edaniels commented on Jul 15, 2020

    @edaniels
    Contributor

    We just realized we were hitting this for many months in our dev and qa environments where we are running a server compiled with the race defector enabled. Ultimately disabling it kept the resident memory stable and not leaking to the point of being OOM killed over the course of the day. We however were not seeing 8 bytes of leakage at a time as opposed to many MB. When I core dumped the process and ran strings on it, I saw many duplicates of a record we pull from the database although we cache that value in a go map internally.

    I eventually ran strace -k filtering for mmap calls since malloc can call mmap if the size requested is over a threshold. Doing this showed a lot of calls into tsan/sanitizer library shadow methods. I’m wondering if the shadow variables maintained end up making wholesale copies of certain values or regions of memory?

    Either way, the detector is too useful and we will keep it on, but getting it to not leak memory would excise a lot of noise from our development and testing processes.

  20. dvyukov commented on Jul 15, 2020

    @dvyukov
    Member

    I’m wondering if the shadow variables maintained end up making wholesale copies of certain values or regions of memory?

    No, the additional regions allocated by the race runtime should only hold internal metadata and never user data, or copies of user data.

  21. edaniels commented on Jul 15, 2020

    @edaniels
    Contributor

    I see. So around 7/15 02:00 is when we turned off the detector and as soon as we turned it back on today we started leaking again.
    data

    We've had that type of trend for at least 3 months now and not running it for a 12 hour period showed no kind of abnormal leakage of memory. So maybe something else is going on that is causing a ton of 8 byte leakages?

    Screen Shot 2020-07-15 at 12 44 58 PM

    Keeping in mind that this is mostly HTTP traffic load that stays consistent day over day.

  22. anacrolix commented on Feb 8, 2021

    @anacrolix
    Contributor

    I've had users report this when using https://github.com/anacrolix/stm with the race detector enabled. Per other comments above, there is a lot of defer/recover, and very long call stacks that don't look correct.

  23. gopherbot commented on Feb 9, 2023

    @gopherbot
    Contributor

    Change https://go.dev/cl/458218 mentions this issue: runtime: implement traceback iterator

  24. aclements commented on Feb 13, 2023

    @aclements
    Member

    Once this is fixed, we should unwind the documentation change in CL 221019

  25. mdempsky commented on Aug 8, 2023

    @mdempsky
    Contributor

    FYI, @dvyukov 's test case no longer reproduces for me.

    I also tried forcing baz to use stack-allocated defers (by adding a named result parameter) and heap-allocated defers (by adding a for { ...; break } wrapper around the defer statement).

    I also tried adding a runtime.Gosched() call after the go func() { x++ }() statement, to ensure the "Read at" and "Previous write at" match the same goroutines as in @dvyukov 's output.

  26. anacrolix commented on Aug 8, 2023

    @anacrolix
    Contributor

    Could something have changed in recent versions is Go (I presume 1.21 @mdempsky ?) that could have fixed this issue?

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.RaceDetector

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions