Skip to content

Commit fe8ca91

Browse files
committed
Guard the contextvars import for py3.6 salt-ssh; revert thin typing_extensions bundle
The previous commit bundled typing_extensions into the salt-ssh thin, but the thin ships the build host's (modern) typing_extensions, whose py3.8+ syntax is a SyntaxError on a Python 3.6 target -- and it shadows the target's own compatible typing_extensions, so importlib_metadata (imported at salt-call startup via salt._compat) crashed before reaching any of this PR's code. That broke salt-ssh on every py3.6 target (Rocky Linux 8, Amazon Linux 2). Reverted. Instead, guard "import contextvars" in salt/state.py. On targets where it can only be resolved through the thin's backport -- which drags in immutables/typing_extensions that may be missing (a py3.9 Debian target) or incompatible (py3.6) -- catch ImportError/SyntaxError and fall back to a shared class-level active-HighState stack. salt-ssh runs one execution per target, so the per-context isolation (#63056) is not needed there; on py3.7+ minions and the onedir master/minion, stdlib contextvars is used and the isolation is unchanged. Validated on live Python 3.6.8 (AlmaLinux 8): a modern typing_extensions is a SyntaxError on py3.6, and the guarded import catches both that and a missing typing_extensions, engaging the fallback without crashing. Adds a test for the fallback path.
1 parent cf523c4 commit fe8ca91

4 files changed

Lines changed: 58 additions & 37 deletions

File tree

‎salt/state.py‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,16 @@
1111
}
1212
"""
1313

14-
import contextvars
14+
try:
15+
import contextvars
16+
except (ImportError, SyntaxError):
17+
# Some salt-ssh targets (notably Python 3.6, which lacks a stdlib
18+
# contextvars) resolve ``import contextvars`` to the thin's bundled backport,
19+
# which pulls in immutables/typing_extensions that can be missing or
20+
# syntactically incompatible on the target. Degrade to a shared stack there
21+
# -- salt-ssh runs one execution per target, so the per-context isolation
22+
# contextvars provides (#63056) is not needed.
23+
contextvars = None
1524
import copy
1625
import datetime
1726
import fnmatch
@@ -3911,8 +3920,15 @@ def __init__(self, opts):
39113920
self.avail = self.__gather_avail()
39123921
self.building_highstate = HashableOrderedDict()
39133922

3923+
# Fallback shared stack, used only when contextvars is unavailable (see the
3924+
# guarded import at the top of the module). salt-ssh runs one execution per
3925+
# target, so a shared stack there is safe.
3926+
_shared_active_stack = []
3927+
39143928
@classmethod
39153929
def _active_stack(cls):
3930+
if _active_highstates is None:
3931+
return BaseHighState._shared_active_stack
39163932
# The active-HighState stack for the current execution context, created
39173933
# lazily on first use. A default= on the ContextVar would share one
39183934
# list object across every context, defeating the isolation, so the
@@ -3934,7 +3950,10 @@ def clear_active(cls):
39343950
# Blow away the active-HighState stack for the current execution
39353951
# context. Used primarily by the test runner but also useful in custom
39363952
# wrappers of the HighState class, to reset the stack to a fresh state.
3937-
_active_highstates.set([])
3953+
if _active_highstates is None:
3954+
BaseHighState._shared_active_stack.clear()
3955+
else:
3956+
_active_highstates.set([])
39383957

39393958
@classmethod
39403959
def pop_active(cls):
@@ -5125,7 +5144,10 @@ def __exit__(self, *_):
51255144
# reactor orchestrations rendered in parallel reactor worker threads -- each
51265145
# get their own stack instead of corrupting a shared class-level list
51275146
# (#63056). This mirrors salt.loader's loader_ctxvar.
5128-
_active_highstates = contextvars.ContextVar("salt_active_highstates")
5147+
if contextvars is not None:
5148+
_active_highstates = contextvars.ContextVar("salt_active_highstates")
5149+
else:
5150+
_active_highstates = None
51295151

51305152

51315153
class HighState(BaseHighState):

‎salt/utils/thin.py‎

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -41,17 +41,6 @@
4141
except ImportError:
4242
pass
4343

44-
# ``immutables`` (bundled above for the Python 3.6 contextvars backport) imports
45-
# ``typing_extensions``; without it in the thin, a py3.6 target crashes on
46-
# ``import contextvars`` with ModuleNotFoundError. Bundle it alongside.
47-
has_typing_extensions = False
48-
try:
49-
import typing_extensions
50-
51-
has_typing_extensions = True
52-
except ImportError:
53-
pass
54-
5544

5645
try:
5746
import zlib
@@ -463,8 +452,6 @@ def get_tops(extra_mods="", so_mods=""):
463452
mods.append(contextvars)
464453
if has_immutables:
465454
mods.append(immutables)
466-
if has_typing_extensions:
467-
mods.append(typing_extensions)
468455
for mod in mods:
469456
if mod:
470457
log.debug('Adding module to the tops: "%s"', mod.__name__)

‎tests/pytests/unit/state/test_active_highstate_stack.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import threading
1515

1616
import salt.state
17+
from tests.support.mock import patch
1718

1819

1920
class _Marker(salt.state.HighState):
@@ -122,3 +123,35 @@ def __init__(self): # pylint: disable=super-init-not-called
122123
assert salt.state.HighState.get_active() is None
123124
finally:
124125
salt.state.BaseHighState.clear_active()
126+
127+
128+
def test_active_stack_falls_back_when_contextvars_unavailable():
129+
"""
130+
On a salt-ssh target without a usable ``contextvars`` (e.g. Python 3.6,
131+
where the module is only available through the thin's backport and can pull
132+
in an incompatible ``typing_extensions``), ``import contextvars`` is guarded
133+
and ``_active_highstates`` is ``None``. The active-stack accessors must then
134+
degrade to a shared class-level list instead of raising -- salt-ssh runs a
135+
single execution per target, so a shared stack is safe there.
136+
"""
137+
HighState = salt.state.HighState
138+
with patch.object(salt.state, "_active_highstates", None):
139+
salt.state.BaseHighState._shared_active_stack.clear()
140+
HighState.clear_active()
141+
assert HighState.get_active() is None
142+
143+
a = _Marker("a")
144+
b = _Marker("b")
145+
a.push_active()
146+
assert HighState.get_active() is a
147+
b.push_active()
148+
assert HighState.get_active() is b
149+
b.pop_active()
150+
assert HighState.get_active() is a
151+
a.pop_active()
152+
assert HighState.get_active() is None
153+
154+
a.push_active()
155+
HighState.clear_active()
156+
assert HighState.get_active() is None
157+
salt.state.BaseHighState._shared_active_stack.clear()

‎tests/pytests/unit/utils/test_thin.py‎

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -485,11 +485,6 @@ def test_get_ext_namespaces_failure(thin_ctx):
485485
"salt.utils.thin.immutables",
486486
type("immutables", (), {"__file__": "/site-packages/immutables"}),
487487
)
488-
@patch_if(
489-
salt.utils.thin.has_typing_extensions,
490-
"salt.utils.thin.typing_extensions",
491-
type("typing_extensions", (), {"__file__": "/site-packages/typing_extensions"}),
492-
)
493488
@patch("salt.utils.thin.log", MagicMock())
494489
def test_get_tops(thin_ctx):
495490
"""
@@ -517,8 +512,6 @@ def test_get_tops(thin_ctx):
517512
]
518513
if salt.utils.thin.has_immutables:
519514
base_tops.extend(["immutables"])
520-
if salt.utils.thin.has_typing_extensions:
521-
base_tops.extend(["typing_extensions"])
522515
tops = []
523516
for top in thin.get_tops(extra_mods="foo,bar"):
524517
if top.find("/") != -1:
@@ -603,11 +596,6 @@ def test_get_tops(thin_ctx):
603596
"salt.utils.thin.immutables",
604597
type("immutables", (), {"__file__": "/site-packages/immutables"}),
605598
)
606-
@patch_if(
607-
salt.utils.thin.has_typing_extensions,
608-
"salt.utils.thin.typing_extensions",
609-
type("typing_extensions", (), {"__file__": "/site-packages/typing_extensions"}),
610-
)
611599
@patch("salt.utils.thin.log", MagicMock())
612600
def test_get_tops_extra_mods(thin_ctx):
613601
"""
@@ -637,8 +625,6 @@ def test_get_tops_extra_mods(thin_ctx):
637625
]
638626
if salt.utils.thin.has_immutables:
639627
base_tops.extend(["immutables"])
640-
if salt.utils.thin.has_typing_extensions:
641-
base_tops.extend(["typing_extensions"])
642628
libs = salt.utils.thin.find_site_modules("contextvars")
643629
foo = {"__file__": os.sep + os.path.join("custom", "foo", "__init__.py")}
644630
bar = {"__file__": os.sep + os.path.join("custom", "bar")}
@@ -731,11 +717,6 @@ def test_get_tops_extra_mods(thin_ctx):
731717
"salt.utils.thin.immutables",
732718
type("immutables", (), {"__file__": "/site-packages/immutables"}),
733719
)
734-
@patch_if(
735-
salt.utils.thin.has_typing_extensions,
736-
"salt.utils.thin.typing_extensions",
737-
type("typing_extensions", (), {"__file__": "/site-packages/typing_extensions"}),
738-
)
739720
@patch("salt.utils.thin.log", MagicMock())
740721
def test_get_tops_so_mods(thin_ctx):
741722
"""
@@ -765,8 +746,6 @@ def test_get_tops_so_mods(thin_ctx):
765746
]
766747
if salt.utils.thin.has_immutables:
767748
base_tops.extend(["immutables"])
768-
if salt.utils.thin.has_typing_extensions:
769-
base_tops.extend(["typing_extensions"])
770749
libs = salt.utils.thin.find_site_modules("contextvars")
771750
with patch("salt.utils.thin.find_site_modules", MagicMock(side_effect=[libs])):
772751
with patch(

0 commit comments

Comments
 (0)