salt icon indicating copy to clipboard operation
salt copied to clipboard

[BUG] New ReqServer memory leak in 3006.10

Open OrangeDog opened this issue 1 year ago • 46 comments

Description I recently upgraded from 3006.9 to 3006.10, and a new memory leak appears to have been introduced. I now have to restart salt-master basically every day to avoid OOM issues, and will probably have to revert to .9

Setup Master is on KVM. I have only twelve minions, on a mix of machine, but all the same version as the master. They run state.apply every fifteen minutes, and a couple run some other scheduled script that doesn't interact with the master. Both gitfs and git_pillar are in use, as well as x509 (v1) states and mine requests.

Steps to Reproduce the behavior Salt process shortly after a restart:

    PID USER       PRI  NI  VIRT   RES   SHR S  CPU% MEM%▽  TIME+  Command
    977 root        20   0  693M 87812  8960 S   0.0  1.5  1h23:53 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-minion MultiMinionProcessManager MinionProcessManager
4046378 root        20   0  394M 71880 18692 S   0.0  1.2  0:00.91 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master FileServerUpdate
4046359 root        20   0  216M 65960 23808 S   0.0  1.1  0:01.21 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master MainProcess
4046376 root        20   0  223M 62496 13700 S   0.0  1.1  0:00.50 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master Maintenance
4046392 root        20   0  306M 62256 11140 S   0.0  1.1  0:01.02 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorker-4
4046382 root        20   0  306M 60976 11012 S   0.0  1.0  0:00.99 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorker-1
4046384 root        20   0  304M 57008  7172 S   0.0  1.0  0:01.01 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorker-2
4046380 root        20   0  303M 56240  6404 S   0.0  1.0  0:00.98 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorker-0
4046385 root        20   0  303M 56240  6404 S   0.0  1.0  0:01.04 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorker-3
4046379 root        20   0  584M 48944  6020 S   0.0  0.8  0:00.01 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorkerQueue
4046372 root        20   0  296M 48624  6660 S   0.0  0.8  0:00.05 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master PubServerChannel._publish_daemon
4046377 root        20   0  216M 47520  5252 S   0.0  0.8  0:00.03 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer ReqServer_ProcessManager
4046373 root        20   0  217M 47360  5508 S   0.0  0.8  0:00.01 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master EventPublisher
    947 root        20   0  168M 24728   256 S   0.0  0.4  0:00.54 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-minion

Salt processes thirty minutes later:

    PID USER       PRI  NI  VIRT   RES   SHR S  CPU% MEM%▽  TIME+  Command
4046392 root        20   0  616M  126M 31236 S   0.0  2.2  0:44.65 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorker-4
4046380 root        20   0  617M  126M 31236 S   0.0  2.2  0:45.11 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorker-0
4046382 root        20   0  615M  124M 31108 S   0.0  2.2  0:50.88 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorker-1
4046385 root        20   0  615M  123M 31108 S   0.0  2.1  0:38.10 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorker-3
4046384 root        20   0  614M  122M 31108 S   0.0  2.1  0:37.49 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorker-2
    977 root        20   0  694M 88836  9984 S   0.0  1.5  1h23:57 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-minion MultiMinionProcessManager MinionProcessManager
4046378 root        20   0  398M 75720 18180 S   0.0  1.3  0:07.85 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master FileServerUpdate
4046376 root        20   0  231M 70304 14340 S   0.0  1.2  0:11.13 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master Maintenance
4046359 root        20   0  216M 65704 23552 S   0.0  1.1  0:01.24 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master MainProcess
4046372 root        20   0  297M 54256 10884 S   0.0  0.9  0:00.30 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master PubServerChannel._publish_daemon
4046373 root        20   0  254M 52932  5508 S   0.0  0.9  0:00.68 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master EventPublisher
4046379 root        20   0  584M 50096  6020 S   0.0  0.9  0:08.88 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorkerQueue
4046377 root        20   0  216M 47520  5252 S   0.0  0.8  0:00.07 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer ReqServer_ProcessManager
    947 root        20   0  168M 24728   256 S   0.0  0.4  0:00.54 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-minion

24 hours later:

    PID USER       PRI  NI  VIRT   RES   SHR S  CPU% MEM%▽  TIME+  Command
4046392 root        20   0  690M  174M  4868 S   0.0  3.0 30:42.23 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorker-4
4046384 root        20   0  755M  173M  4996 S   0.0  3.0 29:52.55 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorker-2
4046380 root        20   0  753M  173M  4996 S   0.0  3.0 30:54.94 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorker-0
4046382 root        20   0  688M  172M  4996 S   0.0  3.0 30:44.35 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorker-1
4046385 root        20   0  689M  172M  4868 S   0.0  3.0 30:51.85 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorker-3
    977 root        20   0  692M 83744  3840 S   0.0  1.4  1h27:26 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-minion MultiMinionProcessManager MinionProcessManager
4046378 root        20   0  402M 63048  1284 S   0.0  1.1  0:29.32 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master FileServerUpdate
 503265 root        20   0  230M 58304  3456 S   0.0  1.0  0:28.76 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master Maintenance
4046373 root        20   0  254M 56928  2564 S   0.0  1.0  0:26.97 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master EventPublisher
4046372 root        20   0  299M 46704  2948 S   0.0  0.8  0:09.60 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master PubServerChannel._publish_daemon
4046379 root        20   0  584M 45744  1156 S   0.0  0.8  6:18.52 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer MWorkerQueue
4046377 root        20   0  216M 43552  1284 S   0.0  0.7  0:03.25 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master ReqServer ReqServer_ProcessManager
4046359 root        20   0  216M 43432  1280 S   0.0  0.7  0:04.29 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-master MainProcess
    947 root        20   0  168M 24728   256 S   0.0  0.4  0:00.54 /opt/saltstack/salt/bin/python3.10 /usr/bin/salt-minion

Expected behavior Memory usage should not keep growing.

Versions Report

salt --versions-report
Salt Version:
          Salt: 3006.10

Python Version:
        Python: 3.10.16 (main, Mar  6 2025, 02:23:15) [GCC 11.2.0]

Dependency Versions:
          cffi: 1.17.1
      cherrypy: unknown
  cryptography: 42.0.5
      dateutil: 2.8.1
     docker-py: Not Installed
         gitdb: Not Installed
     gitpython: Not Installed
        Jinja2: 3.1.6
       libgit2: 1.9.0
  looseversion: 1.0.2
      M2Crypto: 0.38.0
          Mako: Not Installed
       msgpack: 1.0.2
  msgpack-pure: Not Installed
  mysql-python: Not Installed
     packaging: 22.0
     pycparser: 2.21
      pycrypto: Not Installed
  pycryptodome: 3.19.1
        pygit2: 1.17.0
  python-gnupg: 0.4.8
        PyYAML: 6.0.1
         PyZMQ: 23.2.0
        relenv: 0.18.1
         smmap: Not Installed
       timelib: 0.2.4
       Tornado: 4.5.3
           ZMQ: 4.3.4

System Versions:
          dist: ubuntu 24.04.2 noble
        locale: utf-8
       machine: x86_64
       release: 6.8.0-56-generic
        system: Linux
       version: Ubuntu 24.04.2 noble

Additional information Version report from before the upgrade is here: #67207

OrangeDog avatar Apr 01 '25 08:04 OrangeDog

I recorded some overall memory usage of salt-master. This may of course be due to multiple leaks.

graph showing ~600MB increase per day

Is there some way to get object graphs or totals from a running Python? If I can do that it should provide more clues as to where the issue is.

(I have also upgraded to x509_v2 before this)

OrangeDog avatar Jul 14 '25 10:07 OrangeDog

I am also hitting this on version 3006.12 and 3007.6. After a few days all of my top memory using processes are ReqServer MWorker-<N> and systems are running out of memory:

Version report:

Salt Version:
          Salt: 3007.6

Python Version:
        Python: 3.9.21 (main, Jun 27 2025, 00:00:00)

Dependency Versions:
          cffi: 1.14.6
      cherrypy: Not Installed
  cryptography: 42.0.8
      dateutil: 2.9.0.post0
     docker-py: Not Installed
         gitdb: Not Installed
     gitpython: Not Installed
        Jinja2: 2.10.3
       libgit2: Not Installed
  looseversion: 1.3.0
      M2Crypto: Not Installed
          Mako: Not Installed
       msgpack: 1.1.0
  msgpack-pure: Not Installed
  mysql-python: Not Installed
     packaging: 24.1
     pycparser: 2.19
      pycrypto: Not Installed
  pycryptodome: 3.9.8
        pygit2: Not Installed
  python-gnupg: 0.5.2
        PyYAML: 6.0.1
         PyZMQ: 26.2.0
        relenv: Not Installed
         smmap: Not Installed
       timelib: 0.3.0
       Tornado: 6.4.1
           ZMQ: 4.3.5

Salt Package Information:
  Package Type: Not Installed

System Versions:
          dist: oracle 9.6
        locale: utf-8
       machine: x86_64
       release: 5.15.0-310.184.5.2.el9uek.x86_64
        system: Linux
       version: Oracle Linux Server 9.6

We are using tcp for our transport and the main activity the last few days is a single beacon sending an event from four minions every 30 seconds.

I would be happy to test out a fix if there is one available, we need to find a solution to this.

tcarroll25 avatar Sep 17 '25 20:09 tcarroll25

I updated to the 3007.8 patch as well as the latest msgpack and tornado and I'm still seeing the leak:

Salt Version:
          Salt: 3007.8

Python Version:
        Python: 3.9.21 (main, Aug 19 2025, 00:00:00)

Dependency Versions:
          cffi: 1.14.6
      cherrypy: Not Installed
  cryptography: 42.0.8
      dateutil: 2.9.0.post0
     docker-py: Not Installed
         gitdb: Not Installed
     gitpython: Not Installed
        Jinja2: 2.10.3
       libgit2: Not Installed
  looseversion: 1.3.0
      M2Crypto: Not Installed
          Mako: Not Installed
       msgpack: 1.1.1
  msgpack-pure: Not Installed
  mysql-python: Not Installed
     packaging: 24.1
     pycparser: 2.19
      pycrypto: Not Installed
  pycryptodome: 3.9.8
        pygit2: Not Installed
  python-gnupg: 0.5.2
        PyYAML: 6.0.1
         PyZMQ: 26.2.0
        relenv: Not Installed
         smmap: Not Installed
       timelib: 0.3.0
       Tornado: 6.5.2
           ZMQ: 4.3.5

Salt Package Information:
  Package Type: Not Installed

System Versions:
          dist: oracle 9.6
        locale: utf-8
       machine: x86_64
       release: 5.15.0-310.184.5.2.el9uek.x86_64
        system: Linux
       version: Oracle Linux Server 9.6

To reproduce the leak I run saltutil.sync_all followed by highstate on a loop and the memory will slowly but continuously grow. We sync custom modules and states. The highstate will sync files from the salt file roots and but we don't use any pillars.

I'm trying to inject tracemalloc into the ReqServer MWorker-<N> processes but any tips would be appreciated.

tcarroll25 avatar Sep 25 '25 15:09 tcarroll25

Quick update, running the following command on the master was enough to grow the memory of the ReqServer MWorker-<N> processes:

while true; do salt '*' saltutil.sync_all; done

tcarroll25 avatar Sep 25 '25 19:09 tcarroll25

I also have custom modules (11) that are synced.

OrangeDog avatar Sep 29 '25 13:09 OrangeDog

@OrangeDog are you also using tcp for your transport?

tcarroll25 avatar Oct 03 '25 12:10 tcarroll25

@OrangeDog are you also using tcp for your transport?

No. Default zeromq.

OrangeDog avatar Oct 03 '25 13:10 OrangeDog

If any saltstack maintainers have any tips on how to integrate tracemalloc into the codebase to track memory leaks then that would be greatly helpful since I can easily reproduce the leak. I have tried integrating it into the MWorker class but haven't identified anything useful so far.

tcarroll25 avatar Oct 03 '25 14:10 tcarroll25

I used tracemalloc to track the source of the memory leak to local salt.utils.msgpack.Unpacker() objects which were being preserved in the exception stack in salt/transport/tcp.py in the handle_stream method of SaltMessageServer. I changed the salt.utils.msgpack.Unpacker() to be a class member that gets reset in both the exception blocks. Resetting the unpacker object is a common pattern in the salt code and the recommended method in the msgpack documentation to clear the unpacker object buffer. With this fix the memory is stable after running saltutil.sync_all requests continuously for 24 hours straight.

diff --git a/salt/transport/tcp.py b/salt/transport/tcp.py
index e64b013a97..b2a1587121 100644
--- a/salt/transport/tcp.py
+++ b/salt/transport/tcp.py
@@ -402,6 +402,7 @@ class SaltMessageServer(salt.ext.tornado.tcpserver.TCPServer):
         self.io_loop = io_loop
         self.clients = []
         self.message_handler = message_handler
+        self.unpacker = salt.utils.msgpack.Unpacker()

     @salt.ext.tornado.gen.coroutine
     def handle_stream(  # pylint: disable=arguments-differ
@@ -415,22 +416,23 @@ class SaltMessageServer(salt.ext.tornado.tcpserver.TCPServer):
         """
         log.trace("Req client %s connected", address)
         self.clients.append((stream, address))
-        unpacker = salt.utils.msgpack.Unpacker()
         try:
             while True:
                 wire_bytes = yield stream.read_bytes(4096, partial=True)
-                unpacker.feed(wire_bytes)
-                for framed_msg in unpacker:
+                self.unpacker.feed(wire_bytes)
+                for framed_msg in self.unpacker:
                     framed_msg = salt.transport.frame.decode_embedded_strs(framed_msg)
                     header = framed_msg["head"]
                     self.io_loop.spawn_callback(
                         self.message_handler, stream, framed_msg["body"], header
                     )
         except _StreamClosedError:
+            self.unpacker = salt.utils.msgpack.Unpacker()
             log.trace("req client disconnected %s", address)
             self.remove_client((stream, address))
-        except Exception as e:  # pylint: disable=broad-except
-            log.trace("other master-side exception: %s", e, exc_info=True)
+        except Exception:  # pylint: disable=broad-except
+            self.unpacker = salt.utils.msgpack.Unpacker()
+            log.trace("other master-side exception")
             self.remove_client((stream, address))
             stream.close()

This exact fix is based off of 3006.12 but its applicable to all 3006.x and 3007.x branches (at a minimum).

Without the fix the memory leak is very obvious when running saltutil.sync_all requests continuously. Here is part of my tracemalloc output showing 1GB of msgpack objects allocated:

2025-10-03 17:58:51,756 [salt.master      :2717][INFO    ][877739] Top 10 lines
2025-10-03 17:58:51,757 [salt.master      :2722][INFO    ][877739] #1: utils/msgpack.py:84: 1016832.0 KiB
2025-10-03 17:58:51,758 [salt.master      :2726][INFO    ][877739]     msgpack.Unpacker.__init__(

tcarroll25 avatar Oct 06 '25 02:10 tcarroll25

That would be a memory leak, but not the one I reported with this issue, as I don't use TCP. Spamming "sync_all" doesn't appear to affect my system either.

100% you should make a PR for it though.

any tips on how to integrate tracemalloc into the codebase to track memory leaks

Do you have some of those now?

OrangeDog avatar Oct 06 '25 08:10 OrangeDog

@OrangeDog yes I do. Here is the diff I used to integrate tracemalloc into the ReqServer MWorker-<N> process. Note that this diff was created off of salt version 3007.8:

diff --git a/salt/master.py b/salt/master.py
index 4e42320540..9eca535a2d 100644
--- a/salt/master.py
+++ b/salt/master.py
@@ -17,6 +17,9 @@ import sys
 import threading
 import time

+import linecache
+import tracemalloc
+
 import tornado.gen

 import salt.acl
@@ -1137,6 +1140,9 @@ class MWorker(salt.utils.process.SignalHandlingProcess):
         self.k_mtime = 0
         self.stats = collections.defaultdict(lambda: {"mean": 0, "runs": 0})
         self.stat_clock = time.time()
+        tracemalloc.start(25)
+        self.start_snapshot = tracemalloc.take_snapshot()
+        display_top("MWorker init", self.start_snapshot)

     # We need __setstate__ and __getstate__ to also pickle 'SMaster.secrets'.
     # Otherwise, 'SMaster.secrets' won't be copied over to the spawned process
@@ -1153,7 +1159,11 @@ class MWorker(salt.utils.process.SignalHandlingProcess):
         state.update({"k_mtime": self.k_mtime, "secrets": SMaster.secrets})
         return state

+    def take_snapshot(self):
+        display_top("MWorker handle signal", tracemalloc.take_snapshot(), compare_snapshot=self.start_snapshot)
+
     def _handle_signals(self, signum, sigframe):
+        self.take_snapshot()
         for channel in getattr(self, "req_channels", ()):
             try:
                 channel.close()
@@ -2694,3 +2704,50 @@ class ClearFuncs(TransportMethods):
         for transport, opts in iter_transport_opts(self.opts):
             chan = salt.channel.server.PubServerChannel.factory(opts)
             self.channels.append(chan)
+
+
+def display_top(name, snapshot, key_type='lineno', limit=10, compare_snapshot=None):
+    log.info(f"==================== START {name} ====================")
+    snapshot = snapshot.filter_traces((
+        tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
+        tracemalloc.Filter(False, "<unknown>"),
+    ))
+    top_stats = snapshot.statistics(key_type)
+
+    log.info("Top %s lines" % limit)
+    for index, stat in enumerate(top_stats[:limit], 1):
+        frame = stat.traceback[0]
+        # replace "/path/to/module/file.py" with "module/file.py"
+        filename = os.sep.join(frame.filename.split(os.sep)[-2:])
+        log.info("#%s: %s:%s: %.1f KiB"
+              % (index, filename, frame.lineno, stat.size / 1024))
+        line = linecache.getline(frame.filename, frame.lineno).strip()
+        if line:
+            log.info('    %s' % line)
+
+    other = top_stats[limit:]
+    if other:
+        size = sum(stat.size for stat in other)
+        log.info("%s other: %.1f KiB" % (len(other), size / 1024))
+    total = sum(stat.size for stat in top_stats)
+    log.info("Total allocated size: %.1f KiB" % (total / 1024))
+
+    top_stats = snapshot.statistics('traceback')
+
+    # pick the biggest memory block
+    log.info("Top 1 memory block")
+    try:
+        stat = top_stats[0]
+        log.info("%s memory blocks: %.1f KiB" % (stat.count, stat.size / 1024))
+        for line in stat.traceback.format():
+            log.info(line)
+    except IndexError:
+        log.info("No memory blocks found")
+
+    if compare_snapshot:
+        top_stats = snapshot.compare_to(compare_snapshot, 'lineno')
+        log.info("[ Top 10 differences ]")
+        for stat in top_stats[:10]:
+            log.info(stat)
+
+    log.info(f"==================== END {name} ====================")
diff --git a/salt/utils/process.py b/salt/utils/process.py
index 3aa43e76ce..c2bd6a0291 100644
--- a/salt/utils/process.py
+++ b/salt/utils/process.py
@@ -702,6 +702,8 @@ class ProcessManager:

         end_time = time.time() + self.wait_for_kill  # when to die

+        time.sleep(60)
+
         log.trace("Waiting to kill process manager children")
         while self._process_map and time.time() < end_time:
             for pid, p_map in self._process_map.copy().items():

The time.sleep(60) that I hacked into process.py was key so that the worker processes have enough time to dump their memory before the process manager starts sending sigkills. Let it run for a while then stop the salt master. Each worker should dump output to the logs like this when they stop. It will dump the Top 10 lines with the most memory allocations, the full stack trace of the Top 1 memory block and the Top 10 differences between the start of the process and the end:

2025-10-04 20:42:55,810 [salt.master      :2710][INFO    ][2181310] ==================== START MWorker handle signal ====================
2025-10-04 20:43:16,728 [salt.master      :2717][INFO    ][2181310] Top 10 lines
2025-10-04 20:43:16,737 [salt.master      :2722][INFO    ][2181310] #1: utils/msgpack.py:84: 167936.0 KiB
2025-10-04 20:43:16,738 [salt.master      :2726][INFO    ][2181310]     msgpack.Unpacker.__init__(
2025-10-04 20:43:16,739 [salt.master      :2722][INFO    ][2181310] #2: transport/tcp.py:652: 6445.4 KiB
2025-10-04 20:43:16,742 [salt.master      :2726][INFO    ][2181310]     unpacker = salt.utils.msgpack.Unpacker()
2025-10-04 20:43:16,743 [salt.master      :2722][INFO    ][2181310] #3: python3.9/posixpath.py:88: 3354.5 KiB
2025-10-04 20:43:16,744 [salt.master      :2726][INFO    ][2181310]     path += sep + b
2025-10-04 20:43:16,745 [salt.master      :2722][INFO    ][2181310] #4: loader/lazy.py:599: 3135.7 KiB
2025-10-04 20:43:16,747 [salt.master      :2726][INFO    ][2181310]     self.file_mapping[f_noext] = (fpath, ext, opt_index)
2025-10-04 20:43:16,758 [salt.master      :2722][INFO    ][2181310] #5: python3.9/genericpath.py:139: 2420.8 KiB
2025-10-04 20:43:16,759 [salt.master      :2726][INFO    ][2181310]     return p[:dotIndex], p[dotIndex:]
2025-10-04 20:43:16,759 [salt.master      :2722][INFO    ][2181310] #6: loader/lazy.py:642: 2297.5 KiB
2025-10-04 20:43:16,760 [salt.master      :2726][INFO    ][2181310]     mod_opts[key] = val
2025-10-04 20:43:16,760 [salt.master      :2722][INFO    ][2181310] #7: <frozen importlib._bootstrap_external>:647: 1045.3 KiB
2025-10-04 20:43:16,760 [salt.master      :2722][INFO    ][2181310] #8: python3.9/copy.py:230: 804.4 KiB
2025-10-04 20:43:16,761 [salt.master      :2726][INFO    ][2181310]     y[deepcopy(key, memo)] = deepcopy(value, memo)
2025-10-04 20:43:16,761 [salt.master      :2722][INFO    ][2181310] #9: loader/lazy.py:894: 775.0 KiB
2025-10-04 20:43:16,762 [salt.master      :2726][INFO    ][2181310]     mod.__opts__.update(self.opts)
2025-10-04 20:43:16,762 [salt.master      :2722][INFO    ][2181310] #10: python3.9/linecache.py:137: 752.8 KiB
2025-10-04 20:43:16,762 [salt.master      :2726][INFO    ][2181310]     lines = fp.readlines()
2025-10-04 20:43:16,763 [salt.master      :2731][INFO    ][2181310] 2740 other: 8270.2 KiB
2025-10-04 20:43:16,763 [salt.master      :2733][INFO    ][2181310] Total allocated size: 197237.7 KiB
2025-10-04 20:43:18,665 [salt.master      :2738][INFO    ][2181310] Top 1 memory block
2025-10-04 20:43:18,666 [salt.master      :2741][INFO    ][2181310] 160 memory blocks: 163840.0 KiB
2025-10-04 20:43:18,674 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib64/python3.9/multiprocessing/context.py", line 224
2025-10-04 20:43:18,674 [salt.master      :2743][INFO    ][2181310]     return _default_context.get_context().Process._Popen(process_obj)
2025-10-04 20:43:18,674 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib64/python3.9/multiprocessing/context.py", line 277
2025-10-04 20:43:18,675 [salt.master      :2743][INFO    ][2181310]     return Popen(process_obj)
2025-10-04 20:43:18,675 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib64/python3.9/multiprocessing/popen_fork.py", line 19
2025-10-04 20:43:18,675 [salt.master      :2743][INFO    ][2181310]     self._launch(process_obj)
2025-10-04 20:43:18,675 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib64/python3.9/multiprocessing/popen_fork.py", line 71
2025-10-04 20:43:18,676 [salt.master      :2743][INFO    ][2181310]     code = process_obj._bootstrap(parent_sentinel=child_r)
2025-10-04 20:43:18,676 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib64/python3.9/multiprocessing/process.py", line 315
2025-10-04 20:43:18,676 [salt.master      :2743][INFO    ][2181310]     self.run()
2025-10-04 20:43:18,676 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/utils/process.py", line 1001
2025-10-04 20:43:18,677 [salt.master      :2743][INFO    ][2181310]     return run_func()
2025-10-04 20:43:18,677 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/master.py", line 1102
2025-10-04 20:43:18,677 [salt.master      :2743][INFO    ][2181310]     self.__bind()
2025-10-04 20:43:18,678 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/master.py", line 1091
2025-10-04 20:43:18,678 [salt.master      :2743][INFO    ][2181310]     self.process_manager.add_process(
2025-10-04 20:43:18,678 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/utils/process.py", line 532
2025-10-04 20:43:18,678 [salt.master      :2743][INFO    ][2181310]     process.start()
2025-10-04 20:43:18,679 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/utils/process.py", line 1122
2025-10-04 20:43:18,679 [salt.master      :2743][INFO    ][2181310]     super().start()
2025-10-04 20:43:18,679 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib64/python3.9/multiprocessing/process.py", line 121
2025-10-04 20:43:18,679 [salt.master      :2743][INFO    ][2181310]     self._popen = self._Popen(self)
2025-10-04 20:43:18,680 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib64/python3.9/multiprocessing/context.py", line 224
2025-10-04 20:43:18,680 [salt.master      :2743][INFO    ][2181310]     return _default_context.get_context().Process._Popen(process_obj)
2025-10-04 20:43:18,680 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib64/python3.9/multiprocessing/context.py", line 277
2025-10-04 20:43:18,680 [salt.master      :2743][INFO    ][2181310]     return Popen(process_obj)
2025-10-04 20:43:18,681 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib64/python3.9/multiprocessing/popen_fork.py", line 19
2025-10-04 20:43:18,681 [salt.master      :2743][INFO    ][2181310]     self._launch(process_obj)
2025-10-04 20:43:18,681 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib64/python3.9/multiprocessing/popen_fork.py", line 71
2025-10-04 20:43:18,681 [salt.master      :2743][INFO    ][2181310]     code = process_obj._bootstrap(parent_sentinel=child_r)
2025-10-04 20:43:18,682 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib64/python3.9/multiprocessing/process.py", line 315
2025-10-04 20:43:18,682 [salt.master      :2743][INFO    ][2181310]     self.run()
2025-10-04 20:43:18,682 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/utils/process.py", line 1001
2025-10-04 20:43:18,682 [salt.master      :2743][INFO    ][2181310]     return run_func()
2025-10-04 20:43:18,683 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/master.py", line 1339
2025-10-04 20:43:18,683 [salt.master      :2743][INFO    ][2181310]     self.__bind()
2025-10-04 20:43:18,683 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/master.py", line 1193
2025-10-04 20:43:18,683 [salt.master      :2743][INFO    ][2181310]     self.io_loop.start()
2025-10-04 20:43:18,684 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__tornado_6_5_2/tornado/platform/asyncio.py", line 211
2025-10-04 20:43:18,684 [salt.master      :2743][INFO    ][2181310]     self.asyncio_loop.run_forever()
2025-10-04 20:43:18,684 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib64/python3.9/asyncio/base_events.py", line 601
2025-10-04 20:43:18,684 [salt.master      :2743][INFO    ][2181310]     self._run_once()
2025-10-04 20:43:18,685 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib64/python3.9/asyncio/base_events.py", line 1905
2025-10-04 20:43:18,685 [salt.master      :2743][INFO    ][2181310]     handle._run()
2025-10-04 20:43:18,685 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib64/python3.9/asyncio/events.py", line 80
2025-10-04 20:43:18,685 [salt.master      :2743][INFO    ][2181310]     self._context.run(self._callback, *self._args)
2025-10-04 20:43:18,686 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/transport/tcp.py", line 652
2025-10-04 20:43:18,686 [salt.master      :2743][INFO    ][2181310]     unpacker = salt.utils.msgpack.Unpacker()
2025-10-04 20:43:18,686 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/utils/msgpack.py", line 84
2025-10-04 20:43:18,686 [salt.master      :2743][INFO    ][2181310]     msgpack.Unpacker.__init__(
2025-10-04 20:43:20,722 [salt.master      :2749][INFO    ][2181310] [ Top 10 differences ]
2025-10-04 20:43:20,723 [salt.master      :2751][INFO    ][2181310] /usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/utils/msgpack.py:84: size=164 MiB (+164 MiB), count=164 (+164), average=1024 KiB
2025-10-04 20:43:20,723 [salt.master      :2751][INFO    ][2181310] /usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/transport/tcp.py:652: size=6445 KiB (+6445 KiB), count=161 (+161), average=40.0 KiB
2025-10-04 20:43:20,724 [salt.master      :2751][INFO    ][2181310] /usr/lib64/python3.9/posixpath.py:88: size=3354 KiB (+3354 KiB), count=23341 (+23341), average=147 B
2025-10-04 20:43:20,724 [salt.master      :2751][INFO    ][2181310] /usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/loader/lazy.py:599: size=3136 KiB (+3136 KiB), count=45530 (+45530), average=71 B
2025-10-04 20:43:20,725 [salt.master      :2751][INFO    ][2181310] /usr/lib64/python3.9/genericpath.py:139: size=2421 KiB (+2421 KiB), count=45396 (+45396), average=55 B
2025-10-04 20:43:20,725 [salt.master      :2751][INFO    ][2181310] /usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/loader/lazy.py:642: size=2298 KiB (+2298 KiB), count=179 (+179), average=12.8 KiB
2025-10-04 20:43:20,726 [salt.master      :2751][INFO    ][2181310] <frozen importlib._bootstrap_external>:647: size=1045 KiB (+1045 KiB), count=10334 (+10334), average=104 B
2025-10-04 20:43:20,726 [salt.master      :2751][INFO    ][2181310] /usr/lib64/python3.9/copy.py:230: size=804 KiB (+804 KiB), count=1078 (+1078), average=764 B
2025-10-04 20:43:20,726 [salt.master      :2751][INFO    ][2181310] /usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/loader/lazy.py:894: size=775 KiB (+775 KiB), count=43 (+43), average=18.0 KiB
2025-10-04 20:43:20,727 [salt.master      :2751][INFO    ][2181310] /usr/lib64/python3.9/copy.py:201: size=634 KiB (+634 KiB), count=11596 (+11596), average=56 B
2025-10-04 20:43:20,727 [salt.master      :2753][INFO    ][2181310] ==================== END MWorker handle signal ====================
2025-10-04 20:43:20,800 [salt.transport.tcp:1704][DEBUG   ][2181310] Closing _TCPPubServerPublisher instance
2025-10-04 20:43:20,809 [salt.utils.process:1078][DEBUG   ][2181310] MWorker received a SIGTERM. Exiting

The most useful information for me was the Top 1 memory block and the Top 10 differences. The top memory block traced right down where the message pack objects were being allocated in tcp.py:

2025-10-04 20:43:18,686 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/transport/tcp.py", line 652
2025-10-04 20:43:18,686 [salt.master      :2743][INFO    ][2181310]     unpacker = salt.utils.msgpack.Unpacker()
2025-10-04 20:43:18,686 [salt.master      :2743][INFO    ][2181310]   File "/usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/utils/msgpack.py", line 84
2025-10-04 20:43:18,686 [salt.master      :2743][INFO    ][2181310]     msgpack.Unpacker.__init__(

And the top 10 differences showed the amount of memory allocated during the run, in this case +164MB. This stack trace was not from a long run:

2025-10-04 20:43:20,723 [salt.master      :2751][INFO    ][2181310] /usr/lib/128technology/unzip/runfiles/x86_el9_pypi__39__salt_128tech_3007_8/salt/utils/msgpack.py:84: size=164 MiB (+164 MiB), count=164 (+164), average=1024 KiB

However, another longer run showed 1GB off msgpack objects:

2025-10-03 17:58:51,756 [salt.master      :2717][INFO    ][877739] Top 10 lines
2025-10-03 17:58:51,757 [salt.master      :2722][INFO    ][877739] #1: utils/msgpack.py:84: 1016832.0 KiB
2025-10-03 17:58:51,758 [salt.master      :2726][INFO    ][877739]     msgpack.Unpacker.__init__(

So it should be very obvious where the leak is if you run the salt master for long enough.

tcarroll25 avatar Oct 06 '25 18:10 tcarroll25

After a few days of attempts, I finally got some results from 3006.14.

[ Top 10 differences ]
<frozen importlib._bootstrap_external>:672: size=4448 KiB (+4448 KiB), count=49106 (+49106), average=93 B
/opt/saltstack/salt/lib/python3.10/site-packages/salt/utils/msgpack.py:84: size=3072 KiB (+3072 KiB), count=3 (+3), average=1024 KiB
/opt/saltstack/salt/lib/python3.10/pathlib.py:74: size=2560 KiB (+2560 KiB), count=1 (+1), average=2560 KiB
/opt/saltstack/salt/lib/python3.10/site-packages/salt/loader/lazy.py:859: size=1856 KiB (+1856 KiB), count=103 (+103), average=18.0 KiB
/opt/saltstack/salt/lib/python3.10/site-packages/salt/loader/lazy.py:559: size=1836 KiB (+1836 KiB), count=26449 (+26449), average=71 B
/opt/saltstack/salt/lib/python3.10/posixpath.py:88: size=1645 KiB (+1645 KiB), count=13876 (+13876), average=121 B
/opt/saltstack/salt/lib/python3.10/site-packages/salt/loader/lazy.py:608: size=1485 KiB (+1485 KiB), count=128 (+128), average=11.6 KiB
/opt/saltstack/salt/lib/python3.10/genericpath.py:139: size=1430 KiB (+1430 KiB), count=26756 (+26756), average=55 B
/opt/saltstack/salt/lib/python3.10/linecache.py:137: size=1640 KiB (+1143 KiB), count=16843 (+11688), average=100 B
/opt/saltstack/salt/lib/python3.10/copy.py:231: size=821 KiB (+821 KiB), count=3423 (+3423), average=246 B

So there's a leak rendering this template:

  File "/opt/saltstack/salt/lib/python3.10/site-packages/jinja2/environment.py", line 1537
    body_stream = list(template.root_render_func(context))
  File "/var/cache/salt/master/git_pillar/Bs+8Fi8tvxAv7ugyt4wK8MTI8jsF1qK13YM5OWpWhFo=/master/pillar/network.sls", line 31
    db: []
  File "/opt/saltstack/salt/lib/python3.10/site-packages/jinja2/sandbox.py", line 401
    return __context.call(__obj, *args, **kwargs)
  File "/opt/saltstack/salt/lib/python3.10/site-packages/jinja2/runtime.py", line 303
    return __obj(*args, **kwargs)
  File "/opt/saltstack/salt/lib/python3.10/site-packages/salt/loader/lazy.py", line 162
    ret = self.loader.run(run_func, *args, **kwargs)
  File "/opt/saltstack/salt/lib/python3.10/site-packages/salt/loader/lazy.py", line 1248
    return self._last_context.run(self._run_as, _func_or_method, *args, **kwargs)
  File "/opt/saltstack/salt/lib/python3.10/site-packages/salt/loader/lazy.py", line 1263
    ret = _func_or_method(*args, **kwargs)
  File "/opt/saltstack/salt/lib/python3.10/site-packages/salt/modules/saltutil.py", line 1787
    return rclient.cmd(
  File "/opt/saltstack/salt/lib/python3.10/site-packages/salt/runner.py", line 186
    return super().cmd(fun, arg, pub_data, kwarg, print_event, full_return)
  File "/opt/saltstack/salt/lib/python3.10/site-packages/salt/client/mixins.py", line 251
    return self.low(fun, low, print_event=print_event, full_return=full_return)
  File "/opt/saltstack/salt/lib/python3.10/site-packages/salt/client/mixins.py", line 347
    for mod_name in self_functions.keys():
  File "/opt/saltstack/salt/lib/python3.10/_collections_abc.py", line 886
    yield from self._mapping
  File "/opt/saltstack/salt/lib/python3.10/site-packages/salt/utils/lazy.py", line 116
    self._load_all()
  File "/opt/saltstack/salt/lib/python3.10/site-packages/salt/loader/lazy.py", line 1102
    self._load_module(name)
  File "/opt/saltstack/salt/lib/python3.10/site-packages/salt/loader/lazy.py", line 788
    mod = self.run(spec.loader.load_module)
  File "/opt/saltstack/salt/lib/python3.10/site-packages/salt/loader/lazy.py", line 1248
    return self._last_context.run(self._run_as, _func_or_method, *args, **kwargs)
  File "/opt/saltstack/salt/lib/python3.10/site-packages/salt/loader/lazy.py", line 1263
    ret = _func_or_method(*args, **kwargs)
  File "<frozen importlib._bootstrap_external>", line 548
  File "<frozen importlib._bootstrap_external>", line 1063
  File "<frozen importlib._bootstrap_external>", line 888
  File "<frozen importlib._bootstrap>", line 287
  File "<frozen importlib._bootstrap>", line 619
  File "<frozen importlib._bootstrap_external>", line 879
  File "<frozen importlib._bootstrap_external>", line 1012
  File "<frozen importlib._bootstrap_external>", line 672
{% load_yaml as network %}
# <other data redacted>
all: []
db: []
redis: []
{% endload %}

{% for host, addrs in salt.saltutil.runner('mine.get', tgt='*', fun='network.ip_addrs').items() %}
  {% do network['all'].extend(addrs) %}
  {% if host.startswith('db') %}
    {% do network['db'].extend(addrs) %}
  {% elif host.startswith('redis') %}
    {% do network['redis'].extend(addrs) %}
  {% endif %}
{% endfor %}

OrangeDog avatar Oct 08 '25 16:10 OrangeDog

I rewrote the template to avoid load_yaml and I think the leaking has reduced, but I'll need to spend longer to pin down how much.

Edit: no, I don't think it has :( Further investigation to follow.

OrangeDog avatar Oct 14 '25 11:10 OrangeDog

and the recommended method in the msgpack documentation to clear the unpacker object buffer.

@tcarroll25 I could not find in the msgpack documentation where this is recommend. Can you give me a link? For my own knowledge (and maybe others that happen to look at this in the future), can you explain why the Unpacker going out of scope in the handle_stream method does not clear the object buffer?

bdrx312 avatar Oct 14 '25 19:10 bdrx312

The file identified in the previous trace is imported in other pillars thus: {% from 'network.sls' import network %} Removing the use of load_yaml did not have any noticeable effect.

I tried running all of these in a loop, and none showed any acceleration of the leak that I could see:

  • salt-run pillar.show_pillar
  • salt-call pillar.data
  • salt-call saltutil.refresh_pillar wait=true

This one did show an increase. Hard to judge from what I currently have, but roughly doubling the rate of memory growth compared to regular activity.

  • salt-call saltutil.sync_all clean_pillar_cache=true

OrangeDog avatar Oct 16 '25 13:10 OrangeDog

and the recommended method in the msgpack documentation to clear the unpacker object buffer.

@tcarroll25 I could not find in the msgpack documentation where this is recommend. Can you give me a link? For my own knowledge (and maybe others that happen to look at this in the future), can you explain why the Unpacker going out of scope in the handle_stream method does not clear the object buffer?

I wrote up an explanation here: https://github.com/saltstack/salt/pull/68399#issuecomment-3410915948

tcarroll25 avatar Oct 16 '25 13:10 tcarroll25

I've not made much progress on minimal reproduction or workarounds. Hopefully someone with better knowledge of the code will find these tracemalloc logs useful. https://gist.github.com/OrangeDog/930b8156f471947e069044f87aa2ac3d

I may do another run to get some logs without the interleaving.

OrangeDog avatar Oct 21 '25 10:10 OrangeDog

Has this been confirmed as fixed?

dwoz avatar Dec 05 '25 11:12 dwoz

No. It is 100% not fixed. As previously stated, I am not using TCP, so that had nothing to do with it.

Please read what I collected above. There are tracemalloc outputs identifying a few sites to look at.

OrangeDog avatar Dec 05 '25 11:12 OrangeDog

An updated graph for 3006.18. The big drops are my scheduled restarts.

Image

OrangeDog avatar Jan 12 '26 11:01 OrangeDog