Repository navigation
Conversation
Python fork() gives a child a copy-on-write reference to every live
object in the parent, including transport publisher / publish-server
/ subscriber / publisher-client objects that own real socket FDs.
The FD *numbers* are shared -- the parent still owns the underlying
kernel objects. If the child's copy is garbage-collected before an
explicit `.close()`, `__del__` used to unconditionally emit a
`warn_until_close(...)` ResourceWarning that surfaced as `unclosed
publisher client` / `unclosed publish server` / `unclosed publish
subscriber` / `unclosed tcp puller` noise -- cosmetic, but flagged
as a leak in tests and cluttered logs.
Fix: record `self._creator_pid = os.getpid()` in `__init__` and
short-circuit `__del__` when `os.getpid() != self._creator_pid`.
The forked child *must not* `.close()` the underlying stream -- that
would call `close(2)` on the shared FD number and break the parent's
transport. It merely returns early and skips the warning. Guards
use `getattr(self, "_creator_pid", None)` / `getattr(self, "_closing",
True)` so partially-initialized objects (`__init__` raised early, or
constructed via `object.__new__`) do not raise `AttributeError` from
the finalizer.
Precedent for the same pattern: `salt/utils/process.py:845`.
`os.register_at_fork` is deliberately not wired -- the `__del__`-time
PID check is the minimal, correct fix.
Classes touched:
* salt/transport/tcp.py
- Subscriber
- TCPPuller
- PublishServer
- _TCPPubServerPublisher
* salt/transport/ws.py
- PublishClient
- RequestClient
Zeromq's PublishServer has no `warn_until_close` in `__del__`
so it needs no change.
Tests: tests/pytests/unit/transport/test_fork_safety_del.py
(parametrized across every fixed class):
1. `_creator_pid` recorded in `__init__`.
2. Parent PID still emits the warning (creating-process behavior
preserved).
3. Simulated different-PID `__del__` suppresses the warning.
4. Partially-initialized `object.__new__` doesn't crash `__del__`.
5. Real fork() child (Linux) emits nothing to stderr.
``salt.utils.asynchronous.SyncWrapper.__del__`` was missing the
``_creator_pid`` guard added to the transport classes in the previous
commit. As a result, a forked child that inherited a ``SyncWrapper``
via copy-on-write (any minion job child, which inherits the master
event bus wrappers from the parent minion) still emitted
``unclosed SyncWrapper for cls=<class '...'>`` on GC.
Same rationale + pattern as the tcp/ws classes:
* ``__init__`` now records ``self._creator_pid = os.getpid()``.
* ``__del__`` short-circuits with an early return when
``os.getpid() != self._creator_pid`` -- the parent still owns the
wrapped ``obj`` / io_loop / asyncio_loop, and the child must not
``close()`` any of them (would break the parent's transport).
Recursion guard: ``SyncWrapper.__getattr__`` delegates missing
attributes to ``self.obj``. A partially-initialized wrapper
(``object.__new__`` bypass, or ``__init__`` raised before ``self.obj``
was assigned) would recurse infinitely through ``__getattr__`` if
``__del__`` used ``getattr(self, "_creator_pid", None)``. Use
``self.__dict__.get(...)`` for the ``_creator_pid`` / ``obj`` /
``asyncio_loop`` probes to bypass the descriptor protocol.
Tests: extended the parametrized suite in
``tests/pytests/unit/transport/test_fork_safety_del.py`` with a
``SyncWrapper`` case (factory wraps a benign ``_Stub``). All five
existing test scenarios (creator-pid recorded, parent PID emits
warning, simulated-fork suppresses, real ``fork()`` child stderr
empty, partially-initialized ``__del__`` safe) pass for
``SyncWrapper``. Full suite: 35 passed.
twangboy
approved these changes
Sep 10, 2026
dwoz
added a commit
to dwoz/salt
that referenced
this pull request
Sep 11, 2026
``_stream_read`` retained a 1 MiB msgpack.Unpacker per accepted stream because the ``client -> _read_task -> coroutine frame -> client`` reference cycle only collected on the next cyclic-GC pass -- under sustained per-job subscriber churn (each state.apply child forks a fresh event-bus subscriber) tracemalloc showed +35 pinned Unpackers ~= +37 MiB retained after only 20 jobs on a live minion. ``_discard_on_close._cb()`` also leaked the per-subscriber ``self._writers`` entry -- an ``asyncio.Queue`` + drain-Task tuple, ~25 kB apiece. ``_discard_slow_client`` already popped this on the drain-timeout path, but the clean-close callback did not. This is the follow-up to PR saltstack#70260 (which cancelled the read task): that alone was not enough because the coroutine frame stayed pinned via the cycle above. Fixes: * ``_stream_read`` gains a ``try/finally`` that does ``del unpacker`` and clears ``client._read_task = None`` so refcount collection reclaims the coroutine frame (and its Unpacker) immediately on exit. * ``_discard_on_close._cb()`` also clears ``client._read_task`` (for the case where the coroutine has not yet resumed to observe the cancellation) and pops the ``self._writers`` entry, cancelling the drain task -- matching what ``_discard_slow_client`` already does. Combined with saltstack#70260 this drops retained per-job Python memory from ~85 kB/job to ~1.8 kB/job (measured with tracemalloc on a live 200-job RaaS-driven burst). Regression tests in ``tests/pytests/unit/transport/`` verify both invariants and were confirmed to fail on ``origin/3008.x`` without this patch. See issue saltstack#70175.
dwoz
deleted the
dwoz/fix/transport-fork-safety-warn-until-close-3008.x
branch
November 13, 2026 08:30
This branch was previously deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Python fork() gives a child a copy-on-write reference to every live object in the parent, including transport publisher / publish-server / subscriber / publisher-client objects that own real socket FDs. The FD numbers are shared -- the parent still owns the underlying kernel objects. If the child's copy is garbage-collected before an explicit
.close(),__del__used to unconditionally emit awarn_until_close(...)ResourceWarning that surfaced asunclosed publisher client/unclosed publish server/unclosed publish subscriber/unclosed tcp pullernoise -- cosmetic, but flagged as a leak in tests and cluttered logs.Fix: record
self._creator_pid = os.getpid()in__init__and short-circuit__del__whenos.getpid() != self._creator_pid. The forked child must not.close()the underlying stream -- that would callclose(2)on the shared FD number and break the parent's transport. It merely returns early and skips the warning. Guards usegetattr(self, "_creator_pid", None)/getattr(self, "_closing", True)so partially-initialized objects (__init__raised early, or constructed viaobject.__new__) do not raiseAttributeErrorfrom the finalizer.Precedent for the same pattern:
salt/utils/process.py:845.os.register_at_forkis deliberately not wired -- the__del__-time PID check is the minimal, correct fix.Classes touched:
Zeromq's PublishServer has no
warn_until_closein__del__so it needs no change.Tests: tests/pytests/unit/transport/test_fork_safety_del.py (parametrized across every fixed class):
_creator_pidrecorded in__init__.__del__suppresses the warning.object.__new__doesn't crash__del__.