diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index e5aab0591..5260896ef 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -42,6 +42,8 @@ """ from __future__ import print_function +import codecs +import ctypes import dis from functools import partial import imp @@ -50,21 +52,30 @@ import logging import opcode import operator +import platform import pickle -import struct +from struct import pack import sys import traceback import types import weakref +try: + import numpy as np +except ImportError: + np = None + + +RUNNING_CPYTHON = platform.python_implementation() == 'CPython' # cloudpickle is meant for inter process communication: we expect all # communicating processes to run the same Python version hence we favor # communication speed over compatibility: DEFAULT_PROTOCOL = pickle.HIGHEST_PROTOCOL +PY_MAJOR_MINOR = sys.version_info[:2] -if sys.version < '3': +if PY_MAJOR_MINOR[0] < 3: from pickle import Pickler try: from cStringIO import StringIO @@ -249,10 +260,225 @@ def _walk_global_ops(code): yield op, instr.arg +class _Py2StrStruct(ctypes.Structure): + """Map the memory layout of a CPython 2 str to access its interned state""" + _fields_ = [ + ("ob_refcnt", ctypes.c_long), + ("ob_type", ctypes.c_void_p), + ("ob_size", ctypes.c_ulong), + ('ob_shash', ctypes.c_long), + ('ob_sstate', ctypes.c_int), + ('ob_sval', ctypes.c_char), + ] + + def is_interned(self): + return self.ob_sstate != 0 + + +def _is_safe_to_mutate(data_holder): + """Helper function, see _memoryview_from_bytes for details.""" + if not RUNNING_CPYTHON: + # sys.getrefcount and ob_sstate are not always available on other + # platforms (e.g. PyPy): better be conservative. + return False + + # If the following call to sys.getrefcount returns 2, it means that there + # is one reference from data_holder and one from the temporary arguments + # datastructure of the sys.getrefcount call. It is therefore safe to reuse + # the memory buffer of the bytes object as writeable buffer to back the + # memoryview: this buffer is no longer reachable from anywhere else. + safe_to_mutate = sys.getrefcount(data_holder[0]) <= 2 + data = data_holder[0] + if safe_to_mutate and isinstance(data, str): + # Python 2 str instances are bytes that can be interned, make sure + # that this is not the case. + safe_to_mutate = not _Py2StrStruct.from_address(id(data)).is_interned() + return safe_to_mutate + + +def _memoryview_from_bytes(data_holder, format, readonly, shape, **kwargs): + """Build a memoryview from raw bytes read from the pickle stream + + This function tries its best not to allocate any extra memory when not + necessary. + + The actual data is provided in a data_holder which is expected to be a + single item list holding the actual bytes object. This makes it easier to + use sys.getrefcount to detect whether or not the bytes are referenced + elsewhere or not. + + If readonly is False and the backing bytes in data_holder are referenced + from other objects, then the bytes contents are copied into a newly + allocated mutable buffer. Otherwise the memory allocated for the bytes + object is directly reused by the new memoryview. + + CPython 2 str buffers can be interned. This method introspect the ob_sstate + field to check if it is the case or not. If the buffer is interned a new + read-write buffer is allocated to ensure safety. + + Python 2 memoryviews doe not support being cast so that the format and + shape parameters are ignored. + + Reference counting cannot be used in PyPy to detect if it is safe to mutate + the bytes object. If readonly is False, a new mutable buffer is always + allocated. + + **kwargs are left ignored. Those are used to add flexibility to implement + backward compatible changes in future versions of cloudpickle. + """ + safe_to_mutate = _is_safe_to_mutate(data_holder) + data = data_holder[0] + del data_holder[:] + if readonly: + # A memoryview of a bytes object is readonly by default. + view = memoryview(data) + else: + # Python 3.4 implementation of memoryviews backed by ctypes buffers + # has a bug: # https://bugs.python.org/issue19803 + if safe_to_mutate and PY_MAJOR_MINOR != (3, 4): + buffer = ctypes.cast(data, ctypes.POINTER(ctypes.c_char)) + addr = ctypes.addressof(buffer.contents) + array = (ctypes.c_char * len(data)).from_address(addr) + # Store a reference to the backing bytes object to make GC work + # correctly. We hide the object itself in a closure to prevent + # unsuspecting users to access it. + + def _hidden_buffer_ref(): + raise TypeError("Access to mutable buffer with id %d is unsafe" + % id(data)) + array._hidden_buffer_ref = _hidden_buffer_ref + view = memoryview(array) + else: + # This buffer can be referenced by external objects: for instance + # empty and single bytes objects are interned under Python 3. + # Longer bytes objects in Python (from the str type) can also be + # interned. Force a copy into a new mutable buffer to avoid a + # violation of the imnmutability of bytes. + view = memoryview(bytearray(data)) + + if PY_MAJOR_MINOR >= (3, 4): + if len(data) > 0: + return view.cast('B').cast(format, shape) + else: + return view.cast('B').cast(format) + else: + # Python 2.7 does not support casting. + return view + + +def _np_array_builder(buffer, dtype, shape, transpose, writeable, **kwargs): + """Rebuild a numpy array from raw bytes & metadata + + kwargs is ignored. It gives flexibility to implement backward compatible + changes in future versions of cloudpickle. + """ + a = np.lib.stride_tricks.as_strided( + np.frombuffer(buffer, dtype), shape=shape) + if writeable is False: + # buffer is expected to be reconstructed by _memoryview_from_bytes + # which can be a mutable buffer even if the original numpy array + # was readonly. + a.flags.writeable = False + return a.T if transpose else a + + +def _reduce_ndarray(a): + """Memoryview based reducer for numpy arrays + + Note that this reducer is only used under Python 3 as it is not possible + to rebuild a numpy array from a memoryview under Python 2. + """ + transpose = False + if a.flags.f_contiguous: + # Transposing a F-contiguous array makes it possible to take + # a C-contiguous memoryview of it so as to benefit from nocopy + # semantics. The array will be transposed by to its original layout + # at unpickling time by array_builder. + a = a.T + transpose = True + elif not a.flags.c_contiguous: + # Make a copy to be able to extract a contiguous memoryview. + a = np.ascontiguousarray(a) + return _np_array_builder, (memoryview(a), a.dtype, a.shape, transpose, + a.flags.writeable) + + +class _Framer: + """Backport of Python 3.7 framer""" + + _FRAME_SIZE_TARGET = 64 * 1024 + + def __init__(self, file_write): + self.file_write = file_write + self.current_frame = None + + def start_framing(self): + self.current_frame = io.BytesIO() + + def end_framing(self): + if self.current_frame and self.current_frame.tell() > 0: + self.commit_frame(force=True) + self.current_frame = None + + def commit_frame(self, force=False): + if self.current_frame: + f = self.current_frame + if f.tell() >= self._FRAME_SIZE_TARGET or force: + data = f.getbuffer() + write = self.file_write + # Issue a single call to the write nethod of the underlying + # file object for the frame opcode with the size of the + # frame. The concatenation is expected to be less expensive + # than issuing an additional call to write. + write(pickle.FRAME + pack(" 0xffffffff and self.proto >= 4: + self._write_large_bytes(pickle.BINBYTES8 + pack("= self.framer._FRAME_SIZE_TARGET: + self._write_large_bytes(pickle.BINBYTES + pack("= '3.5' +scipy; platform_python_implementation != "PyPy" and python_version >= '3.5' diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index 23cbb3dbc..3031733db 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -1,5 +1,6 @@ from __future__ import division +import array import abc import collections import base64 @@ -45,6 +46,7 @@ from .testutils import subprocess_pickle_echo from .testutils import assert_run_python_script +from .testutils import PeakMemoryMonitor def pickle_depickle(obj, protocol=cloudpickle.DEFAULT_PROTOCOL): @@ -134,6 +136,35 @@ def test_buffer(self): def test_memoryview(self): buffer_obj = memoryview(b"Hello") + assert buffer_obj.readonly + cloned = pickle_depickle(buffer_obj, protocol=self.protocol) + self.assertEqual(cloned.tobytes(), buffer_obj.tobytes()) + assert cloned.readonly + + def test_empty_memoryview(self): + for view in [memoryview(b""), memoryview(b"hello")[1:1]]: + assert view.readonly + cloned = pickle_depickle(view, protocol=self.protocol) + self.assertEqual(cloned.tobytes(), view.tobytes()) + assert cloned.readonly + assert cloned.shape == (0,) + assert cloned.format == 'B' + + @pytest.mark.skipif(sys.version_info < (3, 4), + reason="array does not implement the buffer protocol") + def test_memoryview_from_integer_array(self): + buffer_obj = memoryview(array.array('l', range(12))) + assert buffer_obj.format == 'l' + cloned = pickle_depickle(buffer_obj, protocol=self.protocol) + self.assertEqual(cloned.tobytes(), buffer_obj.tobytes()) + assert not cloned.readonly + + if sys.version_info >= (3, 5): + # Python 3.4 is affected by https://bugs.python.org/issue19803 + assert cloned.format == 'l' + + def test_large_memoryview(self): + buffer_obj = memoryview(b"Hello!" * int(1e7)) self.assertEqual(pickle_depickle(buffer_obj, protocol=self.protocol), buffer_obj.tobytes()) @@ -141,15 +172,116 @@ def test_memoryview(self): reason="non-contiguous memoryview not implemented in " "old Python versions") def test_sliced_and_non_contiguous_memoryview(self): + # Small view buffer_obj = memoryview(b"Hello!" * 3)[2:15:2] self.assertEqual(pickle_depickle(buffer_obj, protocol=self.protocol), buffer_obj.tobytes()) - def test_large_memoryview(self): - buffer_obj = memoryview(b"Hello!" * int(1e7)) + # Large view + buffer_obj = memoryview(b"Hello!" * int(1e7))[2:int(1e7):2] self.assertEqual(pickle_depickle(buffer_obj, protocol=self.protocol), buffer_obj.tobytes()) + @pytest.mark.skipif(platform.python_implementation() == 'PyPy', + reason="cast is broken on PyPy < 5.9.0") + def test_complex_memoryviews(self): + # Use numpy to generate complex memory layouts to be able to test the + # preservation of all memoryview attributes. Note that cloudpickle + # does not guarantee nocopy semantics for all of those cases but + # it should reconstruct the same memory layout in any-case. + np = pytest.importorskip("numpy") + arrays = [ + np.arange(12).reshape(3, 4), + np.arange(12000).reshape(3000, 4).astype(np.float32), + ] + if cloudpickle.PY3: + # There is a bug when calling .tobytes() on non-c-contiguous numpy + # memoryviews under Python 2.7. + arrays += [ + np.asfortranarray(np.arange(12).reshape(3, 4)), + np.arange(12).reshape(3, 4)[:, 1:-1], + np.arange(12).reshape(3, 4)[1:-1, :], + np.asfortranarray(np.arange(12).reshape(3, 4))[:, 1:-1], + np.asfortranarray(np.arange(12).reshape(3, 4))[1:-1, :], + ] + readonly_arrays = [] + for a in arrays: + a = a.copy() + a.flags.writeable = False + readonly_arrays.append(a) + arrays += readonly_arrays + + for a in arrays: + readonly = not a.flags.writeable + original_view = memoryview(a) + cloned_view = pickle_depickle(original_view, + protocol=self.protocol) + assert original_view.readonly == readonly + assert original_view.readonly == cloned_view.readonly + + if (cloudpickle.PY_MAJOR_MINOR > (3, 4) + or (cloudpickle.PY_MAJOR_MINOR == (3, 4) and readonly)): + # Python 2.7 does not support casting memoryviews. + # Python 3.4 has a bug that prevents casting when the buffer + # is backed by a ctypes array. + assert original_view.format == cloned_view.format + assert original_view.shape == cloned_view.shape + + assert original_view.tobytes() == cloned_view.tobytes() + + if (cloudpickle.PY_MAJOR_MINOR >= (3, 4) + and platform.python_implementation() != 'PyPy'): + # Cloned view is always C contiguous irrespective of + # the original view contiguity and layout (C vs Fortran). + assert cloned_view.c_contiguous + + def test_numpy_arrays(self): + # Check that numpy arrays with various memory layouts are properly + # handled. Note that the fact that this can be done without additional + # memory copies depends on the Python version, implementation and + # contiguity of the original aray. Checking nocopy semantics are not + # the goal of this test but are instead addressed in separate, + # implementation specific tests. + np = pytest.importorskip("numpy") + arrays = [ + np.arange(12).reshape(3, 4), + np.arange(12).reshape(3, 2, 2), + np.arange(12000).reshape(3000, 4).astype(np.float32), + np.asfortranarray(np.arange(12).reshape(3, 4)), + np.arange(12).reshape(3, 4)[:, 1:-1], + np.arange(12).reshape(3, 4)[1:-1, :], + np.asfortranarray(np.arange(12).reshape(3, 4))[:, 1:-1], + np.asfortranarray(np.arange(12).reshape(3, 4))[1:-1, :], + np.array([]), + np.array(1), + np.array(1)[()], + ] + readonly_arrays = [] + for a in arrays: + try: + a = a.copy() + a.flags.writeable = False + readonly_arrays.append(a) + except ValueError: + # Cannot set flags on array scalars. + pass + arrays += readonly_arrays + + for original in arrays: + cloned = pickle_depickle(original, protocol=self.protocol) + assert original.dtype == cloned.dtype + assert original.shape == cloned.shape + np.testing.assert_array_equal(original, cloned) + + if original.flags.f_contiguous: + assert cloned.flags.f_contiguous + else: + assert cloned.flags.c_contiguous + if sys.version_info[0] > 2: + # Under Python 2, the non-optimized reducer of numpy is used + # and it does not preserve the writeable flag. + assert original.flags.writeable == cloned.flags.writeable + def test_lambda(self): self.assertEqual(pickle_depickle(lambda: 1)(), 1) @@ -868,5 +1000,150 @@ class Protocol2CloudPickleTest(CloudPickleTest): protocol = 2 -if __name__ == '__main__': - unittest.main() +@pytest.mark.skipif(sys.version_info[:2] < (3, 4), + reason="nocopy memoryview only supported on Python 3.4+") +@pytest.mark.skipif(platform.python_implementation() == 'PyPy', + reason="memoryview.c_contiguous is missing") +def test_nocopy_readonly_bytes(tmpdir): + tmpfile = str(tmpdir.join('biggish.pkl')) + mem_tol = int(5e7) # 50 MB + size = int(5e8) # 500 MB + biggish_data_bytes = b'0' * size + biggish_data_view = memoryview(biggish_data_bytes) + for biggish_data in [biggish_data_bytes, biggish_data_view]: + with open(tmpfile, 'wb') as f: + with PeakMemoryMonitor() as monitor: + cloudpickle.dump(biggish_data, f) + + # Check that temporary datastructures used when dumping are no + # larger than 100 MB which is much smaller than the bytes to be + # pickled. + assert monitor.base_mem > size + assert monitor.newly_allocated < mem_tol + + with open(tmpfile, 'rb') as f: + with PeakMemoryMonitor() as monitor: + # C-based pickle.load allocates a temporary variable on Python + # 3.5 and 3.6 while the Python-based pickle._load + # implementation does not have this problem + reconstructed = pickle._load(f) + + # Check that loading does not make a memory copy (it allocates) + # a single binary buffer + assert size - mem_tol < monitor.newly_allocated < size + mem_tol + + assert len(reconstructed) == size + if biggish_data is biggish_data_bytes: + assert reconstructed == biggish_data_bytes + else: + assert reconstructed.readonly + assert reconstructed.format == biggish_data_view.format + assert reconstructed.tobytes() == biggish_data_bytes + + +@pytest.mark.skipif(sys.version_info[:2] < (3, 5), + reason="nocopy writable memoryview only supported on " + "Python 3.5+") +@pytest.mark.skipif(platform.python_implementation() == 'PyPy', + reason="memoryview.c_contiguous is missing") +def test_nocopy_writable_memoryview(tmpdir): + tmpfile = str(tmpdir.join('biggish.pkl')) + mem_tol = int(5e7) # 50 MB + size = int(5e8) # 500 MB + biggish_array = array.array('l', range(size // 8)) + biggish_array_view = memoryview(biggish_array) + assert not biggish_array_view.readonly + + with open(tmpfile, 'wb') as f: + with PeakMemoryMonitor() as monitor: + cloudpickle.dump(biggish_array_view, f) + + # Check that temporary datastructures used when dumping are no + # larger than 100 MB which is much smaller than the bytes to be + # pickled. + assert monitor.base_mem > size + assert monitor.newly_allocated < mem_tol + + with open(tmpfile, 'rb') as f: + with PeakMemoryMonitor() as monitor: + # C-based pickle.load allocates a temporary variable on Python 3.5 + # and 3.6 while the Python-based pickle._load implementation does + # not have this problem + reconstructed = pickle._load(f) + + # Check that loading does not make a memory copy (it allocates) + # a single binary buffer + assert size - mem_tol < monitor.newly_allocated < size + mem_tol + + assert reconstructed.nbytes == size + assert not reconstructed.readonly + assert reconstructed.format == biggish_array_view.format + assert reconstructed == biggish_array_view + + +@pytest.mark.skipif(sys.version_info[:2] < (3, 5), + reason="nocopy writable memoryview only supported on " + "Python 3.5+") +@pytest.mark.skipif(platform.python_implementation() == 'PyPy', + reason="memoryview.c_contiguous is missing") +def test_nocopy_pydata(): + np = pytest.importorskip("numpy") + pd = pytest.importorskip("pandas") + sp = pytest.importorskip("scipy.sparse") + + mem_tol = 50e6 # 50 MB + shape = (int(2e5), 100) + data = np.arange(np.prod(shape)).reshape(shape) + data_with_zeros = data.copy() + data_with_zeros[::2] = 0 + csr = sp.csr_matrix(data_with_zeros) + + large_pydata_objects = [ + (data, data.nbytes), # 160 MB + (data.T, data.nbytes), + (pd.DataFrame(data), data.nbytes), + (csr, csr.indptr.nbytes + csr.indices.nbytes + csr.data.nbytes), + ] + + class ChunksAppender: + + def __init__(self): + self.raw_chunks = [] + + def write(self, data): + # Append reference to raw chunks without triggering any memory + # copy. The bytes will be consumed in a delayed manner after the + # end of the pickling process by the call to materialize. + self.raw_chunks.append(data) + + def materialize(self): + # Concatenate all memoryview and bytes chunks into a single + # bytes object make many memory copies along the way. + return b"".join([c.tobytes() if hasattr(c, 'tobytes') else c + for c in self.raw_chunks]) + + for obj, size in large_pydata_objects: + appender = ChunksAppender() + + # Check that pickling does not make any memory copy of the large data + # buffer of the pandas dataframe: + with PeakMemoryMonitor() as monitor: + cloudpickle.dump(obj, appender) + + assert monitor.newly_allocated < mem_tol + + pickled = appender.materialize() + assert size - mem_tol < len(pickled) < size + mem_tol + + with PeakMemoryMonitor() as monitor: + cloned_obj = pickle._loads(pickled) + + # Check that loading does not make a memory copy (it allocates) + # a single binary buffer + assert size - mem_tol < monitor.newly_allocated < size + mem_tol + if sp.issparse(obj): + np.testing.assert_array_equal(obj.toarray(), cloned_obj.toarray()) + elif isinstance(obj, pd.DataFrame): + np.testing.assert_array_equal(obj.values, cloned_obj.values) + else: + np.testing.assert_array_equal(obj, cloned_obj) diff --git a/tests/memoryview_test.py b/tests/memoryview_test.py new file mode 100644 index 000000000..9490bf258 --- /dev/null +++ b/tests/memoryview_test.py @@ -0,0 +1,195 @@ +import sys +import platform +from cloudpickle.cloudpickle import _is_safe_to_mutate +from cloudpickle.cloudpickle import _memoryview_from_bytes +from cloudpickle.cloudpickle import _Py2StrStruct +import pytest + + +RUNNING_CPYTHON = platform.python_implementation() == 'CPython' + + +@pytest.mark.skipif(sys.version_info[:2] == (3, 4), + reason="https://bugs.python.org/issue19803") +def test_safe_mutable_bytes(): + if sys.version_info[0] >= 3: + buffer = bytes([1, 2, 3]) + else: + # Make the buffer large enough to avoid Python 2 string interning. + buffer = (u'0123' * 100000).encode('ascii') + buffer_id = id(buffer) + buffer_size = len(buffer) + buffer_holder = [buffer] + # Delete the local direct reference to the buffer + del buffer + + # There are no external reference to the bytes object in buffer_holder, the + # _memoryview_from_bytes function can safely reuse the memory allocated for + # the bytes object to expose it as a mutable buffer to back the memoryview + # when running CPython. + if RUNNING_CPYTHON: + assert _is_safe_to_mutate(buffer_holder) + else: + assert not _is_safe_to_mutate(buffer_holder) + view = _memoryview_from_bytes(buffer_holder, 'B', False, (buffer_size,)) + assert not view.readonly + assert len(buffer_holder) == 0 + + # CPython 2 and PyPy do not expose the obj attribute. + if hasattr(view, 'obj') and RUNNING_CPYTHON: + # The last reference to the original bytes object is hold in a closure + # to discourage direct access by the user: + with pytest.raises(TypeError) as exc_info: + view.obj._hidden_buffer_ref() + msg = "Access to mutable buffer with id %d is unsafe" % buffer_id + assert exc_info.value.args[0] == msg + + # It's possible to mutate the content of the buffer + view[:] = b'\x00' * buffer_size + + +@pytest.mark.skipif(sys.version_info[0] < 3 or not RUNNING_CPYTHON, + reason="Test relies on CPython 3 implementation details") +def test_mutate_py3_single_element_bytes(): + """Check the safety of mutating a single element bytes instance. + + The _memoryview_from_bytes relies on implementation details of the + CPython 3 interpreter when deciding whether it is safe to mutate the + existing buffer or not. + + In particular it assumes that when a singleton bytes instance is implicitly + interned, it has always at least one external reference somewhere else in + the interpreter and the _safe_to_mutate will therefore always return False. + + If this assumption is ever violated in some future version of CPython, + this test will fail and will tell the cloudpickle maintainers that safety + of mutating singleton bytes is no longer guaranteed. + + This test is therefore a canary test for future Python 3 versions + """ + # Single element bytes can be singleton (implicitly interned), for instance + # when they are sliced from a larger bytes object or when encoding a + # single symbol unicode string. + joined_bytes = bytes(range(256)) + implicitly_interned_bytes = [] + for i in range(256): + assert sys.getrefcount(joined_bytes[i:i + 1]) >= 2 + buffer_holder = [joined_bytes[i:i + 1]] + assert not _is_safe_to_mutate(buffer_holder) + implicitly_interned_bytes.append(buffer_holder[0]) + assert chr(i).encode('latin1') is implicitly_interned_bytes[i] + assert joined_bytes[i:i + 1] is implicitly_interned_bytes[i] + + # In this case, a new read-write buffer is allocated to back the + # memoryview. + view = _memoryview_from_bytes(buffer_holder, 'B', False, (1,)) + assert not view.readonly + if sys.version_info[:2] != (3, 4): + assert not hasattr(view.obj, '_hidden_buffer_ref') + + # Single item bytes instances are not interned when using the bytes([i]) + # constructor and in this case, they can be mutated safely, they will not + # impact the implicitly interned bytes singleton instances. + for i in range(256): + buffer_holder = [bytes([i])] + assert buffer_holder[0] == implicitly_interned_bytes[i] + assert buffer_holder[0] is not implicitly_interned_bytes[i] + assert _is_safe_to_mutate(buffer_holder) + view = _memoryview_from_bytes(buffer_holder, 'B', False, (1,)) + if sys.version_info[:2] != (3, 4): + with pytest.raises(TypeError): + view.obj._hidden_buffer_ref() + view[:] = b'\x00' + assert view.tobytes() == b'\x00' + + # The singleton are not impacted by the changes in the views. + for i in range(256): + assert implicitly_interned_bytes[i] == bytes([i]) + assert implicitly_interned_bytes[i] is not bytes([i]) + + +@pytest.mark.skipif(sys.version_info[0] < 3, + reason="Test checks assumption on Python 3 implementation") +def test_check_no_explicit_py3_bytes_interning(): + """Ensure that Python 3+ does not allow explicit interning for bytes. + + The _memoryview_from_bytes function makes the assumption that it is not + possible to explicitly intern bytes objects. If this assumption is ever + violated in future versions of Python, the implementation of + _memoryview_from_bytes will have to be updated accordingly to preserve the + safety of directly reusing a bytes buffer to a mutable memoryview. + + This is a canary test: this does not actually test anything in cloudpickle + besides assumptions made on the language implementation. + """ + with pytest.raises(TypeError): + sys.intern(b'some bytes instance') + + +def test_unsafe_mutable_bytes_with_external_references(): + buffer = u"\x01\x02\x03".encode('ascii') + buffer_holder = [buffer] + + # The local 'buffer' variable still holds a reference to the bytes object + # instance: _memoryview_from_bytes cannot safely reuse the same buffer. + assert not _is_safe_to_mutate(buffer_holder) + + # Instead new mutable memory is allocated to back the buffer: + view = _memoryview_from_bytes(buffer_holder, 'B', False, (3,)) + assert not view.readonly + assert len(buffer_holder) == 0 + if hasattr(view, 'obj'): + # CPython 2 and PyPy does not expose the 'obj attribute'. + assert not hasattr(view.obj, '_hidden_buffer_ref') + + # Check that changing the content of the view does not change the content + # of original buffer: + view[:] = b'\x00\x00\x00' + assert buffer == b"\x01\x02\x03" + + +@pytest.mark.skipif(sys.version_info[0] != 2, + reason="Test relies on Python 2 str interning") +@pytest.mark.skipif(platform.python_implementation != 'CPython', + reason="Test requires access to ob_sstate field.") +def test_py2_interned_string_detection(): + def process_str(original): + """Return non-interned version of original str object""" + return ' '.join(x for x in original.split(' ')) + s1 = process_str('some python 2 str') + s2 = intern('some python 2 str') + s3 = intern('some python 2 str') + assert s1 == s2 + assert s1 is not s2 + assert s2 is s3 + assert not _Py2StrStruct.from_address(id(s1)).is_interned() + assert _Py2StrStruct.from_address(id(s2)).is_interned() + assert _Py2StrStruct.from_address(id(s3)).is_interned() + + # Interned CPython str buffers are never safe to mutate even without + # external references. + buffer_holder = [intern(process_str('other python 2 str'))] + assert not _is_safe_to_mutate(buffer_holder) + + # Non-interned CPython str buffers without any external references are + # safe to mutate: + buffer_holder = [process_str('other python 2 str')] + assert _is_safe_to_mutate(buffer_holder) + + +@pytest.mark.skipif(sys.version_info[0] != 2, + reason="Test relies on Python 2 str interning") +def test_unsafe_mutable_bytes_with_python_2_interning(): + buffer_holder = [intern(u"\x01\x02\x03".encode('ascii'))] + + assert not _is_safe_to_mutate(buffer_holder) + view = _memoryview_from_bytes(buffer_holder, 'B', False, (3,)) + assert not view.readonly + assert len(buffer_holder) == 0 + + # Create a new interned buffer with the same original content + interned_buffer = intern(b"\x01\x02\x03") + + # Mutate the view pointing the to the original buffer + view[:] = b'\x00\x00\x00' + assert interned_buffer == b'\x01\x02\x03' diff --git a/tests/testutils.py b/tests/testutils.py index a8187baf3..7fcfdaa0c 100644 --- a/tests/testutils.py +++ b/tests/testutils.py @@ -3,9 +3,12 @@ import os.path as op import tempfile from subprocess import Popen, check_output, PIPE, STDOUT, CalledProcessError +import gc +import multiprocessing as mp from cloudpickle import dumps from pickle import loads +import pytest try: from suprocess import TimeoutExpired @@ -110,5 +113,56 @@ def assert_run_python_script(source_code, timeout=5): os.unlink(source_file) +def monitor_worker(pid, queue, started_event, stop_event, delay=0.010): + import psutil + p = psutil.Process(pid) + peak = 0 + + def make_measurement(peak): + mem = p.memory_info().rss + if mem > peak: + peak = mem + return peak + + peak = make_measurement(peak) + started_event.set() + + # Make measurements every 'delay' seconds until we receive the stop event: + while not stop_event.wait(timeout=delay): + peak = make_measurement(peak) + + # Make one last measurement in case memory has increased just before + # receiving the stop event: + peak = make_measurement(peak) + queue.put(peak) + + +class PeakMemoryMonitor: + + def __enter__(self): + psutil = pytest.importorskip("psutil") + pid = os.getpid() + gc.collect() + self.queue = q = mp.Queue() + e_started = mp.Event() + self.stop_event = e_stop = mp.Event() + self.worker = mp.Process(target=monitor_worker, + args=(pid, q, e_started, e_stop)) + self.worker.start() + e_started.wait() + self.base_mem = psutil.Process(pid).memory_info().rss + return self + + def __exit__(self, exc_type, exc_value, tb): + self.stop_event.set() + if exc_type is not None: + self.worker.terminate() + return False + else: + self.peak_mem = self.queue.get() + self.newly_allocated = self.peak_mem - self.base_mem + return True + + if __name__ == '__main__': pickle_echo()