-
Notifications
You must be signed in to change notification settings - Fork 1.3k
fix: lazily initialize DEFAULT_JUMPSTART_SAGEMAKER_SESSION (#4468) [v2] #6331
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mohamedzeidan2021
wants to merge
2
commits into
aws:master-v2
Choose a base branch
from
mohamedzeidan2021:fix/issue-4468-lazy-jumpstart-session-v2
base: master-v2
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"). You | ||
| # may not use this file except in compliance with the License. A copy of | ||
| # the License is located at | ||
| # | ||
| # http://aws.amazon.com/apache2.0/ | ||
| # | ||
| # or in the "license" file accompanying this file. This file is | ||
| # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF | ||
| # ANY KIND, either express or implied. See the License for the specific | ||
| # language governing permissions and limitations under the License. | ||
| """Tests for lazy initialization of DEFAULT_JUMPSTART_SAGEMAKER_SESSION (GH #4468).""" | ||
|
|
||
| from __future__ import absolute_import | ||
|
|
||
| import copy | ||
| from types import SimpleNamespace | ||
|
|
||
| import pytest | ||
| from mock import MagicMock, patch | ||
|
|
||
| from sagemaker.jumpstart import constants | ||
| from sagemaker.jumpstart.constants import _LazyJumpStartSagemakerSession | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def reset_lazy_session_cache(): | ||
| """Start each test with an unresolved proxy cache, then restore what we found. | ||
|
|
||
| The cache lives on the class, i.e. it is process-wide. Blanking it on teardown | ||
| would discard a session that earlier tests in the same worker had already | ||
| resolved and mutated, so save and restore the original values instead. | ||
| """ | ||
| saved_resolved = _LazyJumpStartSagemakerSession._resolved | ||
| saved_session = _LazyJumpStartSagemakerSession._session | ||
| _LazyJumpStartSagemakerSession._resolved = False | ||
| _LazyJumpStartSagemakerSession._session = None | ||
| try: | ||
| yield | ||
| finally: | ||
| _LazyJumpStartSagemakerSession._resolved = saved_resolved | ||
| _LazyJumpStartSagemakerSession._session = saved_session | ||
|
|
||
|
|
||
| def test_default_session_is_a_lazy_proxy(): | ||
| assert isinstance(constants.DEFAULT_JUMPSTART_SAGEMAKER_SESSION, _LazyJumpStartSagemakerSession) | ||
|
|
||
|
|
||
| def test_truthiness_does_not_build_a_session(): | ||
| """``session or DEFAULT_...`` / ``if session:`` must stay lazy (no boto clients).""" | ||
| with patch.object(constants, "Session") as session_cls: | ||
| assert bool(constants.DEFAULT_JUMPSTART_SAGEMAKER_SESSION) is True | ||
| assert _LazyJumpStartSagemakerSession._resolved is False | ||
| session_cls.assert_not_called() | ||
|
|
||
|
|
||
| def test_first_attribute_access_builds_session_once(): | ||
| fake = MagicMock() | ||
| fake.boto_region_name = "us-west-2" | ||
| with patch.object(constants, "Session", return_value=fake) as session_cls: | ||
| assert constants.DEFAULT_JUMPSTART_SAGEMAKER_SESSION.boto_region_name == "us-west-2" | ||
| assert _LazyJumpStartSagemakerSession._resolved is True | ||
| _ = constants.DEFAULT_JUMPSTART_SAGEMAKER_SESSION.boto_region_name | ||
| session_cls.assert_called_once() | ||
|
|
||
|
|
||
| def test_setattr_is_forwarded_to_real_session(): | ||
| fake = MagicMock() | ||
| with patch.object(constants, "Session", return_value=fake): | ||
| constants.DEFAULT_JUMPSTART_SAGEMAKER_SESSION.sagemaker_client = "client" | ||
| assert fake.sagemaker_client == "client" | ||
|
|
||
|
|
||
| def test_copy_returns_the_real_session(): | ||
| """utils.get_default_jumpstart_session_with_user_agent_suffix copies then mutates, | ||
| so copy.copy(proxy) must yield a real (copyable, mutable) session, not the proxy.""" | ||
| fake = SimpleNamespace(boto_session="orig", sagemaker_client="orig") | ||
| with patch.object(constants, "Session", return_value=fake): | ||
| result = copy.copy(constants.DEFAULT_JUMPSTART_SAGEMAKER_SESSION) | ||
| assert not isinstance(result, _LazyJumpStartSagemakerSession) | ||
| assert isinstance(result, SimpleNamespace) | ||
| assert result is not fake | ||
| result.boto_session = "new" | ||
| assert fake.boto_session == "orig" | ||
|
|
||
|
|
||
| def test_failed_build_degrades_to_none_contract(): | ||
| """If Session construction raises, resolution yields None and logs a warning; | ||
| attribute access then behaves exactly as it would on ``None``.""" | ||
| with patch.object(constants, "Session", side_effect=RuntimeError("boom")): | ||
| assert bool(constants.DEFAULT_JUMPSTART_SAGEMAKER_SESSION) is True | ||
| assert _LazyJumpStartSagemakerSession._resolve() is None | ||
| with pytest.raises(AttributeError): | ||
| _ = constants.DEFAULT_JUMPSTART_SAGEMAKER_SESSION.boto_region_name | ||
|
|
||
|
|
||
| def test_mock_patch_of_class_level_attribute_tears_down_cleanly(): | ||
| """``mock.patch`` on a class-level session method must restore the original and | ||
| leave nothing behind on the process-wide session. | ||
|
|
||
| mock records ``is_local=False`` for a class-level attribute (it is absent from | ||
| the instance ``__dict__``) and restores it by calling ``delattr``, so the proxy | ||
| must forward ``__delattr__``. Without that forwarding the teardown raises | ||
| ``AttributeError`` and the mock leaks into every later test in the same worker. | ||
| """ | ||
|
|
||
| class FakeSession: | ||
| """Stands in for ``Session``: ``read_s3_file`` is a class-level attribute.""" | ||
|
|
||
| def read_s3_file(self): | ||
| return "real" | ||
|
|
||
| fake = FakeSession() | ||
| with patch.object(constants, "Session", return_value=fake): | ||
| proxy = constants.DEFAULT_JUMPSTART_SAGEMAKER_SESSION | ||
| assert proxy.read_s3_file() == "real" | ||
|
|
||
| with patch.object(proxy, "read_s3_file", return_value="mocked"): | ||
| assert proxy.read_s3_file() == "mocked" | ||
|
|
||
| # Teardown must restore the class method and leave no shadowing instance | ||
| # attribute behind on the shared session. | ||
| assert proxy.read_s3_file() == "real" | ||
| assert "read_s3_file" not in fake.__dict__ | ||
|
|
||
|
|
||
| def test_mock_patch_of_instance_level_attribute_tears_down_cleanly(): | ||
| """The instance-attribute path (``is_local=True``, restored via ``setattr``) | ||
| must keep working -- guards against a regression in ``__setattr__`` forwarding.""" | ||
|
|
||
| class FakeSession: | ||
| def __init__(self): | ||
| self.sagemaker_client = "real-client" | ||
|
|
||
| fake = FakeSession() | ||
| with patch.object(constants, "Session", return_value=fake): | ||
| proxy = constants.DEFAULT_JUMPSTART_SAGEMAKER_SESSION | ||
| with patch.object(proxy, "sagemaker_client", "mock-client"): | ||
| assert proxy.sagemaker_client == "mock-client" | ||
| assert proxy.sagemaker_client == "real-client" |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
_resolve()setscls._resolved = Truebefore the (self-described several-second)Session(...)build completes, with no lock. Under concurrent first use — two threads reading an attribute off the default session — thread B enters_resolve, finds_resolvedalreadyTrue, and returnscls._session, which is still the initialNone.__getattr__then doesgetattr(None, name)and raisesAttributeErroron the success path, not just the documented failure path. The old eager init ran under the import lock, so this race is new. Guard the build with a lock and publish_resolvedlast, inside the lock:Note
__slots__ = ()is on the instance; a class-level_lockattribute is unaffected by it.