Skip to content

Skip transport __del__ warnings in forked children - #70260

Merged
dwoz merged 2 commits into
saltstack:3008.xfrom
dwoz:dwoz/fix/transport-fork-safety-warn-until-close-3008.x
Sep 10, 2026
Merged

dwoz merged 2 commits into
saltstack:3008.xfrom
dwoz:dwoz/fix/transport-fork-safety-warn-until-close-3008.x

Conversation

@dwoz

@dwoz dwoz commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

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.

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.
@dwoz
dwoz requested a review from a team as a code owner September 10, 2026 08:01
@dwoz dwoz added the test:full Run the full test suite label Sep 10, 2026
``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.
@dwoz
dwoz merged commit 94bb352 into saltstack:3008.x Sep 10, 2026
903 of 909 checks passed
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
dwoz deleted the dwoz/fix/transport-fork-safety-warn-until-close-3008.x branch November 13, 2026 08:30

This branch was previously deployed

1 inactive deployment
ci — 7b932209 Deployed Sep 10, 2026 by dwoz via Build Onedir Packages / DEB (x86_64) #27069
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

test:full Run the full test suite

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants